@monochange/feedback 0.0.0-stage → 0.3.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 +24 -0
- package/README.md +22 -2
- package/dist/client.d.ts +117 -0
- package/dist/client.js +253 -0
- package/dist/embed/feedback.iife.js +7 -0
- package/dist/hosted/feedback-frame.iife.js +7 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +3 -0
- package/dist/widget.d.ts +41 -0
- package/dist/widget.js +334 -0
- package/package.json +33 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
This is free and unencumbered software released into the public domain.
|
|
2
|
+
|
|
3
|
+
Anyone is free to copy, modify, publish, use, compile, sell, or
|
|
4
|
+
distribute this software, either in source code form or as a compiled
|
|
5
|
+
binary, for any purpose, commercial or non-commercial, and by any
|
|
6
|
+
means.
|
|
7
|
+
|
|
8
|
+
In jurisdictions that recognize copyright laws, the author or authors
|
|
9
|
+
of this software dedicate any and all copyright interest in the
|
|
10
|
+
software to the public domain. We make this dedication for the benefit
|
|
11
|
+
of the public at large and to the detriment of our heirs and
|
|
12
|
+
successors. We intend this dedication to be an overt act of
|
|
13
|
+
relinquishment in perpetuity of all present and future rights to this
|
|
14
|
+
software under copyright law.
|
|
15
|
+
|
|
16
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
17
|
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
18
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
|
19
|
+
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
|
20
|
+
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
|
21
|
+
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
|
22
|
+
OTHER DEALINGS IN THE SOFTWARE.
|
|
23
|
+
|
|
24
|
+
For more information, please refer to <http://unlicense.org/>
|
package/README.md
CHANGED
|
@@ -1,3 +1,23 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Website feedback
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Install `@monochange/feedback` for an accessible Shadow DOM widget or a framework-independent API client. It supports conversations, similar requests, voting, submission, replies, and delivery status.
|
|
4
|
+
|
|
5
|
+
Read the [installation guide](https://github.com/monochange/monochange/blob/main/docs/src/guide/feedback-widget.md) for registration, authenticated backend token issuance, custom launchers, themes, translations, and script-tag installation.
|
|
6
|
+
|
|
7
|
+
For a website builder or CMS that only accepts HTML, paste the hosted iframe from the installation guide. Visitors sign in through monochange; the host needs no SDK, JavaScript, or backend. See `examples/iframe.html` for a complete page.
|
|
8
|
+
|
|
9
|
+
For a headless integration:
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { FeedbackClient } from "@monochange/feedback/client";
|
|
13
|
+
|
|
14
|
+
const feedback = new FeedbackClient({
|
|
15
|
+
endpoint: "https://monochange.dev",
|
|
16
|
+
project: 123,
|
|
17
|
+
getClientToken: () => authenticatedHostApi.feedbackSession("web"),
|
|
18
|
+
});
|
|
19
|
+
const matches = await feedback.suggest("Export invoices to CSV");
|
|
20
|
+
// Ask the user before voting for a match or submitting a new request.
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
The host backend credential belongs on the backend. Call `reset()` on account changes and `destroy()` when disposing the client. Session errors expose `code`, `status`, and `retryAfter`; interrupted submissions reuse their original idempotency key. No browser storage is used.
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
//#region packages/monochange__feedback/src/client.d.ts
|
|
2
|
+
/** Framework-independent transport shared by browser and React Native integrations. */
|
|
3
|
+
type FeedbackKind = "feature_request" | "bug_report";
|
|
4
|
+
interface FeedbackContext {
|
|
5
|
+
route: string;
|
|
6
|
+
app_version?: string;
|
|
7
|
+
locale?: string;
|
|
8
|
+
element?: {
|
|
9
|
+
selector: string;
|
|
10
|
+
label?: string;
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
interface ClientToken {
|
|
14
|
+
token: string;
|
|
15
|
+
expires_at: number;
|
|
16
|
+
}
|
|
17
|
+
interface FeedbackOptions {
|
|
18
|
+
endpoint: string;
|
|
19
|
+
project: number;
|
|
20
|
+
getClientToken: () => Promise<ClientToken | string>;
|
|
21
|
+
getContext?: () => FeedbackContext | undefined;
|
|
22
|
+
fetch?: typeof globalThis.fetch;
|
|
23
|
+
}
|
|
24
|
+
interface Suggestion {
|
|
25
|
+
id: string;
|
|
26
|
+
title: string;
|
|
27
|
+
status: string;
|
|
28
|
+
votes: number;
|
|
29
|
+
voted: boolean;
|
|
30
|
+
}
|
|
31
|
+
interface AssistantReply {
|
|
32
|
+
reply: string;
|
|
33
|
+
similar: Suggestion[];
|
|
34
|
+
mode: string;
|
|
35
|
+
}
|
|
36
|
+
interface Message {
|
|
37
|
+
role: "user" | "assistant";
|
|
38
|
+
body: string;
|
|
39
|
+
}
|
|
40
|
+
interface Conversation {
|
|
41
|
+
id: string;
|
|
42
|
+
version: number;
|
|
43
|
+
kind: FeedbackKind;
|
|
44
|
+
messages: Message[];
|
|
45
|
+
item?: string;
|
|
46
|
+
}
|
|
47
|
+
interface ConversationReply {
|
|
48
|
+
conversation: Conversation;
|
|
49
|
+
similar: Suggestion[];
|
|
50
|
+
mode: string;
|
|
51
|
+
}
|
|
52
|
+
interface Receipt {
|
|
53
|
+
id: string;
|
|
54
|
+
stage: string;
|
|
55
|
+
}
|
|
56
|
+
interface Item extends Receipt {
|
|
57
|
+
title: string;
|
|
58
|
+
status: string;
|
|
59
|
+
votes: number;
|
|
60
|
+
voted: boolean;
|
|
61
|
+
messages: {
|
|
62
|
+
author: string;
|
|
63
|
+
body: string;
|
|
64
|
+
}[];
|
|
65
|
+
update?: {
|
|
66
|
+
summary: string;
|
|
67
|
+
detail: string;
|
|
68
|
+
links: {
|
|
69
|
+
label: string;
|
|
70
|
+
url: string;
|
|
71
|
+
}[];
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
declare class FeedbackError extends Error {
|
|
75
|
+
readonly code: string;
|
|
76
|
+
readonly status: number;
|
|
77
|
+
readonly retryAfter?: number;
|
|
78
|
+
constructor(message: string, code?: string, status?: number, retryAfter?: number);
|
|
79
|
+
}
|
|
80
|
+
/** No browser storage or host identity is sent; the host callback supplies a scoped token. */
|
|
81
|
+
declare class FeedbackClient {
|
|
82
|
+
private readonly options;
|
|
83
|
+
/** The site's RPC operations live under `${origin}/api/<operation>`. */
|
|
84
|
+
readonly origin: string;
|
|
85
|
+
/** The REST routes a site released before the RPC operations serves. */
|
|
86
|
+
readonly base: string;
|
|
87
|
+
private legacy;
|
|
88
|
+
private token?;
|
|
89
|
+
private refreshing?;
|
|
90
|
+
private epoch;
|
|
91
|
+
private disposed;
|
|
92
|
+
private requests;
|
|
93
|
+
private submissionKeys;
|
|
94
|
+
private fetcher;
|
|
95
|
+
constructor(options: FeedbackOptions);
|
|
96
|
+
private session;
|
|
97
|
+
private request;
|
|
98
|
+
suggest(text: string): Promise<AssistantReply>;
|
|
99
|
+
startConversation(message: string, kind?: FeedbackKind): Promise<ConversationReply>;
|
|
100
|
+
getConversation(id: string): Promise<{
|
|
101
|
+
conversation: Conversation;
|
|
102
|
+
}>;
|
|
103
|
+
sendMessage(conversation: Conversation, body: string): Promise<ConversationReply>;
|
|
104
|
+
submit(conversation: string, version: number): Promise<Receipt>;
|
|
105
|
+
getItem(id: string): Promise<Item>;
|
|
106
|
+
reply(id: string, body: string): Promise<Receipt>;
|
|
107
|
+
vote(id: string, on?: boolean): Promise<{
|
|
108
|
+
id: string;
|
|
109
|
+
votes: number;
|
|
110
|
+
voted: boolean;
|
|
111
|
+
}>;
|
|
112
|
+
/** Call on logout or account change before requesting another user's token. */
|
|
113
|
+
reset(): void;
|
|
114
|
+
destroy(): void;
|
|
115
|
+
}
|
|
116
|
+
//#endregion
|
|
117
|
+
export { AssistantReply, ClientToken, Conversation, ConversationReply, FeedbackClient, FeedbackContext, FeedbackError, FeedbackKind, FeedbackOptions, Item, Message, Receipt, Suggestion };
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
//#region packages/monochange__feedback/src/client.ts
|
|
2
|
+
var FeedbackError = class extends Error {
|
|
3
|
+
constructor(message, code = "request_failed", status = 0, retryAfter) {
|
|
4
|
+
super(message);
|
|
5
|
+
this.code = code;
|
|
6
|
+
this.status = status;
|
|
7
|
+
this.retryAfter = retryAfter;
|
|
8
|
+
this.name = "FeedbackError";
|
|
9
|
+
}
|
|
10
|
+
};
|
|
11
|
+
let sequence = 0;
|
|
12
|
+
const V1_SESSION_LIFETIME_SECONDS = 600;
|
|
13
|
+
/** No browser storage or host identity is sent; the host callback supplies a scoped token. */
|
|
14
|
+
var FeedbackClient = class {
|
|
15
|
+
/** The site's RPC operations live under `${origin}/api/<operation>`. */
|
|
16
|
+
origin;
|
|
17
|
+
/** The REST routes a site released before the RPC operations serves. */
|
|
18
|
+
base;
|
|
19
|
+
legacy = false;
|
|
20
|
+
token;
|
|
21
|
+
refreshing;
|
|
22
|
+
epoch = 0;
|
|
23
|
+
disposed = false;
|
|
24
|
+
requests = /* @__PURE__ */ new Set();
|
|
25
|
+
submissionKeys = /* @__PURE__ */ new Map();
|
|
26
|
+
fetcher;
|
|
27
|
+
constructor(options) {
|
|
28
|
+
this.options = options;
|
|
29
|
+
const url = new URL(options.endpoint);
|
|
30
|
+
if (url.protocol !== "https:" && !(url.protocol === "http:" && [
|
|
31
|
+
"localhost",
|
|
32
|
+
"127.0.0.1",
|
|
33
|
+
"[::1]"
|
|
34
|
+
].includes(url.hostname))) throw new FeedbackError("Feedback requires HTTPS", "invalid_configuration");
|
|
35
|
+
if (url.username || url.password || url.search || url.hash || !Number.isSafeInteger(options.project) || options.project < 1) throw new FeedbackError("Invalid feedback endpoint or project", "invalid_configuration");
|
|
36
|
+
this.origin = url.href.replace(/\/$/, "");
|
|
37
|
+
this.base = `${this.origin}/api/v1/feedback/${options.project}`;
|
|
38
|
+
this.fetcher = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
39
|
+
}
|
|
40
|
+
async session() {
|
|
41
|
+
if (this.disposed) throw new FeedbackError("Feedback client was destroyed", "disposed");
|
|
42
|
+
if (this.token && this.token.expires_at > Date.now() / 1e3 + 30) return this.token;
|
|
43
|
+
if (this.refreshing) return this.refreshing;
|
|
44
|
+
const epoch = this.epoch;
|
|
45
|
+
const pending = this.options.getClientToken().then((value) => {
|
|
46
|
+
if (epoch !== this.epoch || this.disposed) throw new FeedbackError("Feedback identity changed", "identity_changed");
|
|
47
|
+
const token = typeof value === "string" ? {
|
|
48
|
+
token: value,
|
|
49
|
+
expires_at: Date.now() / 1e3 + V1_SESSION_LIFETIME_SECONDS
|
|
50
|
+
} : value;
|
|
51
|
+
if (!token.token || !Number.isFinite(token.expires_at) || token.expires_at <= Date.now() / 1e3) throw new FeedbackError("Host returned an expired feedback session", "invalid_session");
|
|
52
|
+
this.token = token;
|
|
53
|
+
return token;
|
|
54
|
+
});
|
|
55
|
+
this.refreshing = pending;
|
|
56
|
+
try {
|
|
57
|
+
return await pending;
|
|
58
|
+
} finally {
|
|
59
|
+
if (this.refreshing === pending) this.refreshing = void 0;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
async request(call, key, refresh = true) {
|
|
63
|
+
const legacy = this.legacy;
|
|
64
|
+
const { project } = this.options;
|
|
65
|
+
const url = legacy ? `${this.base}${call.legacy.path}` : `${this.origin}/api/${call.operation}?project=${project}`;
|
|
66
|
+
const method = legacy ? call.legacy.method : "POST";
|
|
67
|
+
const body = legacy ? call.legacy.body : {
|
|
68
|
+
project,
|
|
69
|
+
...call.args
|
|
70
|
+
};
|
|
71
|
+
const epoch = this.epoch;
|
|
72
|
+
const session = await this.session();
|
|
73
|
+
if (epoch !== this.epoch) throw new FeedbackError("Feedback identity changed", "identity_changed");
|
|
74
|
+
const controller = new AbortController();
|
|
75
|
+
this.requests.add(controller);
|
|
76
|
+
const timer = setTimeout(() => controller.abort(), 2e4);
|
|
77
|
+
try {
|
|
78
|
+
const headers = {
|
|
79
|
+
Authorization: `Bearer ${session.token}`,
|
|
80
|
+
"Content-Type": "application/json"
|
|
81
|
+
};
|
|
82
|
+
if (key) headers["Idempotency-Key"] = key;
|
|
83
|
+
const response = await this.fetcher(url, {
|
|
84
|
+
method,
|
|
85
|
+
headers,
|
|
86
|
+
body: body === void 0 ? void 0 : JSON.stringify(body),
|
|
87
|
+
signal: controller.signal,
|
|
88
|
+
credentials: "omit",
|
|
89
|
+
redirect: "error"
|
|
90
|
+
});
|
|
91
|
+
if (epoch !== this.epoch) throw new FeedbackError("Feedback identity changed", "identity_changed");
|
|
92
|
+
if (response.status === 401 && refresh) {
|
|
93
|
+
if (this.token === session) this.token = void 0;
|
|
94
|
+
return this.request(call, key, false);
|
|
95
|
+
}
|
|
96
|
+
const text = await response.text();
|
|
97
|
+
if (epoch !== this.epoch) throw new FeedbackError("Feedback identity changed", "identity_changed");
|
|
98
|
+
if (text.length > 262144) throw new FeedbackError("Feedback response exceeded its size limit", "invalid_response");
|
|
99
|
+
let value;
|
|
100
|
+
try {
|
|
101
|
+
value = text ? JSON.parse(text) : {};
|
|
102
|
+
} catch {
|
|
103
|
+
if (response.status === 404 && !legacy) {
|
|
104
|
+
this.legacy = true;
|
|
105
|
+
return this.request(call, key, refresh);
|
|
106
|
+
}
|
|
107
|
+
throw new FeedbackError("Feedback returned an invalid response", "invalid_response", response.status);
|
|
108
|
+
}
|
|
109
|
+
if (response.status === 404 && !legacy && typeof value?.code !== "string") {
|
|
110
|
+
this.legacy = true;
|
|
111
|
+
return this.request(call, key, refresh);
|
|
112
|
+
}
|
|
113
|
+
if (!response.ok) throw new FeedbackError(value.message ?? "Feedback request failed", value.code, response.status, Number(response.headers.get("retry-after")) || void 0);
|
|
114
|
+
return value;
|
|
115
|
+
} finally {
|
|
116
|
+
clearTimeout(timer);
|
|
117
|
+
this.requests.delete(controller);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
suggest(text) {
|
|
121
|
+
const input = { text };
|
|
122
|
+
return this.request({
|
|
123
|
+
operation: "feedback_sdk_suggestions",
|
|
124
|
+
args: { input },
|
|
125
|
+
legacy: {
|
|
126
|
+
path: "/suggestions",
|
|
127
|
+
method: "POST",
|
|
128
|
+
body: input
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
startConversation(message, kind = "feature_request") {
|
|
133
|
+
const supplied = this.options.getContext?.();
|
|
134
|
+
const context = supplied ? { ...supplied } : void 0;
|
|
135
|
+
if (context) context.route = context.route.split(/[?#]/, 1)[0];
|
|
136
|
+
const input = {
|
|
137
|
+
message,
|
|
138
|
+
kind,
|
|
139
|
+
context
|
|
140
|
+
};
|
|
141
|
+
return this.request({
|
|
142
|
+
operation: "feedback_sdk_create_conversation",
|
|
143
|
+
args: { input },
|
|
144
|
+
legacy: {
|
|
145
|
+
path: "/conversations",
|
|
146
|
+
method: "POST",
|
|
147
|
+
body: input
|
|
148
|
+
}
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
getConversation(id) {
|
|
152
|
+
return this.request({
|
|
153
|
+
operation: "feedback_sdk_conversation",
|
|
154
|
+
args: { id },
|
|
155
|
+
legacy: {
|
|
156
|
+
path: `/conversations/${encodeURIComponent(id)}`,
|
|
157
|
+
method: "GET"
|
|
158
|
+
}
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
sendMessage(conversation, body) {
|
|
162
|
+
const input = {
|
|
163
|
+
body,
|
|
164
|
+
version: conversation.version
|
|
165
|
+
};
|
|
166
|
+
return this.request({
|
|
167
|
+
operation: "feedback_sdk_conversation_message",
|
|
168
|
+
args: {
|
|
169
|
+
id: conversation.id,
|
|
170
|
+
input
|
|
171
|
+
},
|
|
172
|
+
legacy: {
|
|
173
|
+
path: `/conversations/${encodeURIComponent(conversation.id)}/messages`,
|
|
174
|
+
method: "POST",
|
|
175
|
+
body: input
|
|
176
|
+
}
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
submit(conversation, version) {
|
|
180
|
+
const scope = `${conversation}:${version}`;
|
|
181
|
+
let key = this.submissionKeys.get(scope);
|
|
182
|
+
if (!key) {
|
|
183
|
+
key = globalThis.crypto?.randomUUID?.() ?? `request-${Date.now()}-${sequence++}`;
|
|
184
|
+
this.submissionKeys.set(scope, key);
|
|
185
|
+
}
|
|
186
|
+
const input = {
|
|
187
|
+
conversation,
|
|
188
|
+
version
|
|
189
|
+
};
|
|
190
|
+
return this.request({
|
|
191
|
+
operation: "feedback_sdk_submit",
|
|
192
|
+
args: { input },
|
|
193
|
+
legacy: {
|
|
194
|
+
path: "/items",
|
|
195
|
+
method: "POST",
|
|
196
|
+
body: input
|
|
197
|
+
}
|
|
198
|
+
}, key);
|
|
199
|
+
}
|
|
200
|
+
getItem(id) {
|
|
201
|
+
return this.request({
|
|
202
|
+
operation: "feedback_sdk_item",
|
|
203
|
+
args: { id },
|
|
204
|
+
legacy: {
|
|
205
|
+
path: `/items/${encodeURIComponent(id)}`,
|
|
206
|
+
method: "GET"
|
|
207
|
+
}
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
reply(id, body) {
|
|
211
|
+
const input = { body };
|
|
212
|
+
return this.request({
|
|
213
|
+
operation: "feedback_sdk_reply",
|
|
214
|
+
args: {
|
|
215
|
+
id,
|
|
216
|
+
input
|
|
217
|
+
},
|
|
218
|
+
legacy: {
|
|
219
|
+
path: `/items/${encodeURIComponent(id)}/messages`,
|
|
220
|
+
method: "POST",
|
|
221
|
+
body: input
|
|
222
|
+
}
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
vote(id, on = true) {
|
|
226
|
+
return this.request({
|
|
227
|
+
operation: "feedback_sdk_vote",
|
|
228
|
+
args: {
|
|
229
|
+
id,
|
|
230
|
+
voted: on
|
|
231
|
+
},
|
|
232
|
+
legacy: {
|
|
233
|
+
path: `/items/${encodeURIComponent(id)}/vote`,
|
|
234
|
+
method: on ? "PUT" : "DELETE"
|
|
235
|
+
}
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
/** Call on logout or account change before requesting another user's token. */
|
|
239
|
+
reset() {
|
|
240
|
+
this.epoch += 1;
|
|
241
|
+
this.token = void 0;
|
|
242
|
+
this.refreshing = void 0;
|
|
243
|
+
this.submissionKeys.clear();
|
|
244
|
+
for (const request of this.requests) request.abort();
|
|
245
|
+
this.requests.clear();
|
|
246
|
+
}
|
|
247
|
+
destroy() {
|
|
248
|
+
this.reset();
|
|
249
|
+
this.disposed = true;
|
|
250
|
+
}
|
|
251
|
+
};
|
|
252
|
+
//#endregion
|
|
253
|
+
export { FeedbackClient, FeedbackError };
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
var monochangeFeedback=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t=class extends Error{constructor(e,t=`request_failed`,n=0,r){super(e),this.code=t,this.status=n,this.retryAfter=r,this.name=`FeedbackError`}};let n=0;var r=class{origin;base;legacy=!1;token;refreshing;epoch=0;disposed=!1;requests=new Set;submissionKeys=new Map;fetcher;constructor(e){this.options=e;let n=new URL(e.endpoint);if(n.protocol!==`https:`&&!(n.protocol===`http:`&&[`localhost`,`127.0.0.1`,`[::1]`].includes(n.hostname)))throw new t(`Feedback requires HTTPS`,`invalid_configuration`);if(n.username||n.password||n.search||n.hash||!Number.isSafeInteger(e.project)||e.project<1)throw new t(`Invalid feedback endpoint or project`,`invalid_configuration`);this.origin=n.href.replace(/\/$/,``),this.base=`${this.origin}/api/v1/feedback/${e.project}`,this.fetcher=e.fetch??globalThis.fetch.bind(globalThis)}async session(){if(this.disposed)throw new t(`Feedback client was destroyed`,`disposed`);if(this.token&&this.token.expires_at>Date.now()/1e3+30)return this.token;if(this.refreshing)return this.refreshing;let e=this.epoch,n=this.options.getClientToken().then(n=>{if(e!==this.epoch||this.disposed)throw new t(`Feedback identity changed`,`identity_changed`);let r=typeof n==`string`?{token:n,expires_at:Date.now()/1e3+600}:n;if(!r.token||!Number.isFinite(r.expires_at)||r.expires_at<=Date.now()/1e3)throw new t(`Host returned an expired feedback session`,`invalid_session`);return this.token=r,r});this.refreshing=n;try{return await n}finally{this.refreshing===n&&(this.refreshing=void 0)}}async request(e,n,r=!0){let i=this.legacy,{project:a}=this.options,o=i?`${this.base}${e.legacy.path}`:`${this.origin}/api/${e.operation}?project=${a}`,s=i?e.legacy.method:`POST`,c=i?e.legacy.body:{project:a,...e.args},l=this.epoch,u=await this.session();if(l!==this.epoch)throw new t(`Feedback identity changed`,`identity_changed`);let d=new AbortController;this.requests.add(d);let f=setTimeout(()=>d.abort(),2e4);try{let a={Authorization:`Bearer ${u.token}`,"Content-Type":`application/json`};n&&(a[`Idempotency-Key`]=n);let f=await this.fetcher(o,{method:s,headers:a,body:c===void 0?void 0:JSON.stringify(c),signal:d.signal,credentials:`omit`,redirect:`error`});if(l!==this.epoch)throw new t(`Feedback identity changed`,`identity_changed`);if(f.status===401&&r)return this.token===u&&(this.token=void 0),this.request(e,n,!1);let p=await f.text();if(l!==this.epoch)throw new t(`Feedback identity changed`,`identity_changed`);if(p.length>262144)throw new t(`Feedback response exceeded its size limit`,`invalid_response`);let m;try{m=p?JSON.parse(p):{}}catch{if(f.status===404&&!i)return this.legacy=!0,this.request(e,n,r);throw new t(`Feedback returned an invalid response`,`invalid_response`,f.status)}if(f.status===404&&!i&&typeof m?.code!=`string`)return this.legacy=!0,this.request(e,n,r);if(!f.ok)throw new t(m.message??`Feedback request failed`,m.code,f.status,Number(f.headers.get(`retry-after`))||void 0);return m}finally{clearTimeout(f),this.requests.delete(d)}}suggest(e){let t={text:e};return this.request({operation:`feedback_sdk_suggestions`,args:{input:t},legacy:{path:`/suggestions`,method:`POST`,body:t}})}startConversation(e,t=`feature_request`){let n=this.options.getContext?.(),r=n?{...n}:void 0;r&&(r.route=r.route.split(/[?#]/,1)[0]);let i={message:e,kind:t,context:r};return this.request({operation:`feedback_sdk_create_conversation`,args:{input:i},legacy:{path:`/conversations`,method:`POST`,body:i}})}getConversation(e){return this.request({operation:`feedback_sdk_conversation`,args:{id:e},legacy:{path:`/conversations/${encodeURIComponent(e)}`,method:`GET`}})}sendMessage(e,t){let n={body:t,version:e.version};return this.request({operation:`feedback_sdk_conversation_message`,args:{id:e.id,input:n},legacy:{path:`/conversations/${encodeURIComponent(e.id)}/messages`,method:`POST`,body:n}})}submit(e,t){let r=`${e}:${t}`,i=this.submissionKeys.get(r);i||(i=globalThis.crypto?.randomUUID?.()??`request-${Date.now()}-${n++}`,this.submissionKeys.set(r,i));let a={conversation:e,version:t};return this.request({operation:`feedback_sdk_submit`,args:{input:a},legacy:{path:`/items`,method:`POST`,body:a}},i)}getItem(e){return this.request({operation:`feedback_sdk_item`,args:{id:e},legacy:{path:`/items/${encodeURIComponent(e)}`,method:`GET`}})}reply(e,t){let n={body:t};return this.request({operation:`feedback_sdk_reply`,args:{id:e,input:n},legacy:{path:`/items/${encodeURIComponent(e)}/messages`,method:`POST`,body:n}})}vote(e,t=!0){return this.request({operation:`feedback_sdk_vote`,args:{id:e,voted:t},legacy:{path:`/items/${encodeURIComponent(e)}/vote`,method:t?`PUT`:`DELETE`}})}reset(){this.epoch+=1,this.token=void 0,this.refreshing=void 0,this.submissionKeys.clear();for(let e of this.requests)e.abort();this.requests.clear()}destroy(){this.reset(),this.disposed=!0}};let i={title:`Feedback`,launcher:`Share feedback`,close:`Close`,message:`What would you like to change?`,feature:`Feature or change`,bug:`Bug report`,send:`Find similar requests`,reply:`Send reply`,submit:`Submit a new request`,voted:`Upvoted`,vote:`Upvote`,another:`Start another request`,loading:`Working…`,sent:`Request submitted`,placeholder:`Describe the outcome you want, or what went wrong…`};function a(e,t={},n=[]){let r=document.createElement(e);for(let[e,n]of Object.entries(t))r.setAttribute(e,n);return r.append(...n),r}function o(e){let t={...i,...e.labels},n=document.createElement(`div`);n.dataset.monochangeFeedback=``,n.dataset.presentation=e.presentation??`dialog`;let r=n.attachShadow({mode:`open`}),o=document.createElement(`style`);e.styleNonce&&(o.nonce=e.styleNonce),o.textContent=`
|
|
2
|
+
:host{--bg:#fff;--fg:#19152e;--muted:#5b5472;--rule:#d8d2e9;--brand:#4f46e5;font:15px/1.5 system-ui,sans-serif;color:var(--fg);color-scheme:light}
|
|
3
|
+
:host([data-theme=dark]){--bg:#241f3b;--fg:#f5f3ff;--muted:#c0b8d8;--rule:#49415f;color-scheme:dark}
|
|
4
|
+
*{box-sizing:border-box}button,textarea,select{font:inherit}button{cursor:pointer;border:1px solid var(--rule);border-radius:10px;padding:10px 14px;background:var(--bg);color:var(--fg)}button:disabled{cursor:wait;opacity:.6}button:focus-visible,textarea:focus-visible,select:focus-visible{outline:3px solid #a78bfa;outline-offset:2px}.primary{background:var(--brand);border-color:var(--brand);color:#fff}.launcher{position:fixed;right:20px;bottom:20px;z-index:2147483000;box-shadow:0 6px 24px #0003}
|
|
5
|
+
dialog{background:var(--bg);color:var(--fg);border:1px solid var(--rule);border-radius:16px;padding:0;width:min(480px,calc(100vw - 24px));max-height:calc(100dvh - 32px);box-shadow:0 24px 80px #0005}dialog::backdrop{background:#19152e66}header{display:flex;align-items:center;justify-content:space-between;padding:16px 20px;border-bottom:1px solid var(--rule)}h2{font-size:20px;margin:0}.body{padding:20px;overflow:auto;max-height:calc(100dvh - 130px)}label{display:block;font-weight:600;margin-bottom:8px}textarea{width:100%;min-height:110px;resize:vertical;border:1px solid var(--rule);border-radius:10px;padding:12px;color:var(--fg);background:var(--bg)}select{padding:8px;border:1px solid var(--rule);border-radius:8px;color:var(--fg);background:var(--bg);margin-bottom:14px}.actions{display:flex;gap:8px;flex-wrap:wrap;margin-top:12px}.messages p{white-space:pre-wrap;padding:12px;border-radius:10px;background:color-mix(in srgb,var(--brand) 8%,var(--bg));overflow-wrap:anywhere}.messages .user{margin-left:24px;background:color-mix(in srgb,var(--brand) 15%,var(--bg))}.match{border:1px solid var(--rule);border-radius:12px;padding:12px;margin:10px 0}.match p{margin:0 0 8px}small,.status{color:var(--muted)}.error{color:#c23748;white-space:pre-wrap}.hidden{display:none}a{color:var(--brand)}
|
|
6
|
+
:host([data-presentation=inline]){display:block} :host([data-presentation=inline]) dialog{position:static;margin:0;width:100%;max-height:none;border:0;border-radius:0;box-shadow:none} :host([data-presentation=inline]) .body{max-height:none}
|
|
7
|
+
`;let s=document.createElement(`dialog`);s.setAttribute(`aria-labelledby`,`feedback-title`),s.lang=e.locale??document.documentElement.lang??`en`,s.append(a(`header`,{},[a(`h2`,{id:`feedback-title`}),a(`button`,{type:`button`,"data-close":``})]),a(`div`,{class:`body`},[a(`p`,{class:`error`,role:`alert`}),a(`p`,{class:`status`,role:`status`,"aria-live":`polite`}),a(`div`,{class:`messages`,role:`log`,"aria-live":`polite`}),a(`div`,{class:`matches`}),a(`form`,{},[a(`label`,{for:`feedback-kind`}),a(`select`,{id:`feedback-kind`},[a(`option`,{value:`feature_request`}),a(`option`,{value:`bug_report`})]),a(`label`,{for:`feedback-message`}),a(`textarea`,{id:`feedback-message`,maxlength:`4000`,required:``}),a(`div`,{class:`actions`},[a(`button`,{class:`primary`,type:`submit`,"data-send":``}),a(`button`,{type:`button`,"data-submit":``,class:`hidden`}),a(`button`,{type:`button`,"data-another":``,class:`hidden`})])])])),e.presentation===`inline`&&(s.open=!0,s.querySelector(`[data-close]`).hidden=!0),r.append(o,s),(e.target??document.body).append(n);let c=e=>s.querySelector(e),l=c(`textarea`),u=c(`select`),d=c(`[data-send]`),f=c(`[data-submit]`),p=c(`[data-another]`),m=c(`.messages`),h=c(`.matches`),g=c(`.status`),_=c(`.error`);return c(`h2`).textContent=t.title,c(`[data-close]`).textContent=t.close,c(`label[for=feedback-kind]`).textContent=t.title,c(`label[for=feedback-message]`).textContent=t.message,u.options[0].textContent=t.feature,u.options[1].textContent=t.bug,l.placeholder=t.placeholder,d.textContent=t.send,f.textContent=t.submit,p.textContent=t.another,{labels:t,host:n,root:r,dialog:s,input:l,kind:u,send:d,submit:f,another:p,messages:m,matches:h,status:g,error:_}}var s=class{ui;client;theme=matchMedia(`(prefers-color-scheme: dark)`);conversation;item;opened=!1;destroyed=!1;pending=!1;epoch=0;returnFocus=null;poll;launcher;constructor(e){this.options=e,this.client=new r(e),this.ui=o(e),this.theme.addEventListener(`change`,this.applyTheme),this.applyTheme(),this.bindControls(),this.createLauncher(),this.opened=e.presentation===`inline`}applyTheme=()=>{this.ui.host.dataset.theme=this.options.theme===`auto`||!this.options.theme?this.theme.matches?`dark`:`light`:this.options.theme};launch=()=>this.open();createLauncher(){this.options.presentation===`inline`||this.options.launcher===!1||(this.launcher=this.options.launcher,this.launcher||(this.launcher=document.createElement(`button`),this.launcher.className=`launcher primary`,this.launcher.textContent=this.ui.labels.launcher,this.ui.root.append(this.launcher)),this.launcher.addEventListener(`click`,this.launch))}bindControls(){let{dialog:e,submit:t,another:n}=this.ui;e.querySelector(`form`).addEventListener(`submit`,this.sendMessage),t.addEventListener(`click`,()=>void this.run(()=>this.submitDraft())),n.addEventListener(`click`,()=>this.reset()),e.querySelector(`[data-close]`).addEventListener(`click`,()=>this.close()),e.addEventListener(`cancel`,e=>{e.preventDefault(),this.close()}),e.addEventListener(`click`,t=>{if(t.target!==e)return;let n=e.getBoundingClientRect();(t.clientX<n.left||t.clientX>n.right||t.clientY<n.top||t.clientY>n.bottom)&&this.close()})}renderMessages(e){this.ui.messages.replaceChildren(...e.map(e=>{let t=document.createElement(`p`);return t.textContent=e.body,t.className=e.role===`user`||e.author===`submitter`?`user`:`assistant`,t}))}renderMatches(e){this.ui.matches.replaceChildren(...e.map(t=>this.matchCard(t,e)))}matchCard(e,t){let n=document.createElement(`article`);n.className=`match`;let r=document.createElement(`p`);r.textContent=e.title;let i=document.createElement(`small`);i.textContent=`${e.status.replaceAll(`_`,` `)} · ${e.votes}`;let a=document.createElement(`button`);return a.type=`button`,a.textContent=e.voted?this.ui.labels.voted:this.ui.labels.vote,a.setAttribute(`aria-pressed`,String(e.voted)),a.addEventListener(`click`,()=>void this.run(async()=>{let n=await this.client.vote(e.id,!e.voted);e.voted=n.voted,e.votes=n.votes,this.renderMatches(t)})),n.append(r,i,document.createElement(`br`),a),n}controls(){let{dialog:e,input:t,kind:n,send:r,submit:i,another:a,labels:o}=this.ui;for(let t of e.querySelectorAll(`.body button`))t.disabled=this.pending;t.disabled=this.pending,n.disabled=this.pending||!!this.conversation||!!this.item,r.textContent=this.pending?o.loading:this.conversation||this.item?o.reply:o.send,i.classList.toggle(`hidden`,!this.conversation||!!this.item),a.classList.toggle(`hidden`,!this.item)}async run(e){if(this.pending||this.destroyed)return;let t=this.epoch;this.pending=!0,this.ui.error.textContent=``,this.controls();try{await e()}catch(e){t===this.epoch&&(this.ui.error.textContent=e instanceof Error?e.message:`Feedback could not be sent. Please retry.`)}finally{t===this.epoch&&(this.pending=!1,this.controls())}}async refreshItem(e){let t=this.epoch,n=await this.client.getItem(e);t!==this.epoch||this.destroyed||(this.item=n,this.ui.status.textContent=`${n.title} · ${n.status}`,this.renderMessages(n.messages),this.controls())}polling(){this.poll&&clearInterval(this.poll),this.poll=setInterval(()=>{this.opened&&this.item&&!this.pending&&this.run(()=>this.refreshItem(this.item.id))},3e4)}sendMessage=e=>{e.preventDefault();let t=this.ui.input.value.trim();t&&this.run(async()=>{if(this.item)await this.client.reply(this.item.id,t),await this.refreshItem(this.item.id);else{let e=this.conversation?await this.client.sendMessage(this.conversation,t):await this.client.startConversation(t,this.ui.kind.value);this.conversation=e.conversation,this.renderMessages(this.conversation.messages),this.renderMatches(e.similar)}this.ui.input.value=``})};async submitDraft(){if(!this.conversation)return;let e=await this.client.submit(this.conversation.id,this.conversation.version);this.ui.status.textContent=this.ui.labels.sent,this.ui.matches.replaceChildren(),await this.refreshItem(e.id),this.polling(),this.options.onSubmitted?.(e)}open(e){this.destroyed||(this.returnFocus=document.activeElement,this.opened||(this.options.presentation===`inline`?this.ui.dialog.open=!0:this.ui.dialog.showModal()),this.opened=!0,this.ui.input.focus(),e&&this.run(()=>this.refreshItem(e)),this.polling())}close(){this.opened=!1,this.ui.dialog.close(),this.returnFocus?.focus(),this.poll&&clearInterval(this.poll)}reset(){this.epoch+=1,this.client.reset(),this.conversation=void 0,this.item=void 0,this.pending=!1,this.ui.input.value=``,this.ui.messages.replaceChildren(),this.ui.matches.replaceChildren(),this.ui.status.textContent=``,this.ui.error.textContent=``,this.poll&&clearInterval(this.poll),this.controls()}destroy(){this.destroyed||(this.close(),this.reset(),this.destroyed=!0,this.client.destroy(),this.launcher?.removeEventListener(`click`,this.launch),this.theme.removeEventListener(`change`,this.applyTheme),this.ui.host.remove())}};function c(e){return new s(e)}return e.FeedbackClient=r,e.FeedbackError=t,e.mountFeedback=c,e})({});
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
(function(){var e=class extends Error{constructor(e,t=`request_failed`,n=0,r){super(e),this.code=t,this.status=n,this.retryAfter=r,this.name=`FeedbackError`}};let t=0;var n=class{origin;base;legacy=!1;token;refreshing;epoch=0;disposed=!1;requests=new Set;submissionKeys=new Map;fetcher;constructor(t){this.options=t;let n=new URL(t.endpoint);if(n.protocol!==`https:`&&!(n.protocol===`http:`&&[`localhost`,`127.0.0.1`,`[::1]`].includes(n.hostname)))throw new e(`Feedback requires HTTPS`,`invalid_configuration`);if(n.username||n.password||n.search||n.hash||!Number.isSafeInteger(t.project)||t.project<1)throw new e(`Invalid feedback endpoint or project`,`invalid_configuration`);this.origin=n.href.replace(/\/$/,``),this.base=`${this.origin}/api/v1/feedback/${t.project}`,this.fetcher=t.fetch??globalThis.fetch.bind(globalThis)}async session(){if(this.disposed)throw new e(`Feedback client was destroyed`,`disposed`);if(this.token&&this.token.expires_at>Date.now()/1e3+30)return this.token;if(this.refreshing)return this.refreshing;let t=this.epoch,n=this.options.getClientToken().then(n=>{if(t!==this.epoch||this.disposed)throw new e(`Feedback identity changed`,`identity_changed`);let r=typeof n==`string`?{token:n,expires_at:Date.now()/1e3+600}:n;if(!r.token||!Number.isFinite(r.expires_at)||r.expires_at<=Date.now()/1e3)throw new e(`Host returned an expired feedback session`,`invalid_session`);return this.token=r,r});this.refreshing=n;try{return await n}finally{this.refreshing===n&&(this.refreshing=void 0)}}async request(t,n,r=!0){let i=this.legacy,{project:a}=this.options,o=i?`${this.base}${t.legacy.path}`:`${this.origin}/api/${t.operation}?project=${a}`,s=i?t.legacy.method:`POST`,c=i?t.legacy.body:{project:a,...t.args},l=this.epoch,u=await this.session();if(l!==this.epoch)throw new e(`Feedback identity changed`,`identity_changed`);let d=new AbortController;this.requests.add(d);let f=setTimeout(()=>d.abort(),2e4);try{let a={Authorization:`Bearer ${u.token}`,"Content-Type":`application/json`};n&&(a[`Idempotency-Key`]=n);let f=await this.fetcher(o,{method:s,headers:a,body:c===void 0?void 0:JSON.stringify(c),signal:d.signal,credentials:`omit`,redirect:`error`});if(l!==this.epoch)throw new e(`Feedback identity changed`,`identity_changed`);if(f.status===401&&r)return this.token===u&&(this.token=void 0),this.request(t,n,!1);let p=await f.text();if(l!==this.epoch)throw new e(`Feedback identity changed`,`identity_changed`);if(p.length>262144)throw new e(`Feedback response exceeded its size limit`,`invalid_response`);let m;try{m=p?JSON.parse(p):{}}catch{if(f.status===404&&!i)return this.legacy=!0,this.request(t,n,r);throw new e(`Feedback returned an invalid response`,`invalid_response`,f.status)}if(f.status===404&&!i&&typeof m?.code!=`string`)return this.legacy=!0,this.request(t,n,r);if(!f.ok)throw new e(m.message??`Feedback request failed`,m.code,f.status,Number(f.headers.get(`retry-after`))||void 0);return m}finally{clearTimeout(f),this.requests.delete(d)}}suggest(e){let t={text:e};return this.request({operation:`feedback_sdk_suggestions`,args:{input:t},legacy:{path:`/suggestions`,method:`POST`,body:t}})}startConversation(e,t=`feature_request`){let n=this.options.getContext?.(),r=n?{...n}:void 0;r&&(r.route=r.route.split(/[?#]/,1)[0]);let i={message:e,kind:t,context:r};return this.request({operation:`feedback_sdk_create_conversation`,args:{input:i},legacy:{path:`/conversations`,method:`POST`,body:i}})}getConversation(e){return this.request({operation:`feedback_sdk_conversation`,args:{id:e},legacy:{path:`/conversations/${encodeURIComponent(e)}`,method:`GET`}})}sendMessage(e,t){let n={body:t,version:e.version};return this.request({operation:`feedback_sdk_conversation_message`,args:{id:e.id,input:n},legacy:{path:`/conversations/${encodeURIComponent(e.id)}/messages`,method:`POST`,body:n}})}submit(e,n){let r=`${e}:${n}`,i=this.submissionKeys.get(r);i||(i=globalThis.crypto?.randomUUID?.()??`request-${Date.now()}-${t++}`,this.submissionKeys.set(r,i));let a={conversation:e,version:n};return this.request({operation:`feedback_sdk_submit`,args:{input:a},legacy:{path:`/items`,method:`POST`,body:a}},i)}getItem(e){return this.request({operation:`feedback_sdk_item`,args:{id:e},legacy:{path:`/items/${encodeURIComponent(e)}`,method:`GET`}})}reply(e,t){let n={body:t};return this.request({operation:`feedback_sdk_reply`,args:{id:e,input:n},legacy:{path:`/items/${encodeURIComponent(e)}/messages`,method:`POST`,body:n}})}vote(e,t=!0){return this.request({operation:`feedback_sdk_vote`,args:{id:e,voted:t},legacy:{path:`/items/${encodeURIComponent(e)}/vote`,method:t?`PUT`:`DELETE`}})}reset(){this.epoch+=1,this.token=void 0,this.refreshing=void 0,this.submissionKeys.clear();for(let e of this.requests)e.abort();this.requests.clear()}destroy(){this.reset(),this.disposed=!0}};let r={title:`Feedback`,launcher:`Share feedback`,close:`Close`,message:`What would you like to change?`,feature:`Feature or change`,bug:`Bug report`,send:`Find similar requests`,reply:`Send reply`,submit:`Submit a new request`,voted:`Upvoted`,vote:`Upvote`,another:`Start another request`,loading:`Working…`,sent:`Request submitted`,placeholder:`Describe the outcome you want, or what went wrong…`};function i(e,t={},n=[]){let r=document.createElement(e);for(let[e,n]of Object.entries(t))r.setAttribute(e,n);return r.append(...n),r}function a(e){let t={...r,...e.labels},n=document.createElement(`div`);n.dataset.monochangeFeedback=``,n.dataset.presentation=e.presentation??`dialog`;let a=n.attachShadow({mode:`open`}),o=document.createElement(`style`);e.styleNonce&&(o.nonce=e.styleNonce),o.textContent=`
|
|
2
|
+
:host{--bg:#fff;--fg:#19152e;--muted:#5b5472;--rule:#d8d2e9;--brand:#4f46e5;font:15px/1.5 system-ui,sans-serif;color:var(--fg);color-scheme:light}
|
|
3
|
+
:host([data-theme=dark]){--bg:#241f3b;--fg:#f5f3ff;--muted:#c0b8d8;--rule:#49415f;color-scheme:dark}
|
|
4
|
+
*{box-sizing:border-box}button,textarea,select{font:inherit}button{cursor:pointer;border:1px solid var(--rule);border-radius:10px;padding:10px 14px;background:var(--bg);color:var(--fg)}button:disabled{cursor:wait;opacity:.6}button:focus-visible,textarea:focus-visible,select:focus-visible{outline:3px solid #a78bfa;outline-offset:2px}.primary{background:var(--brand);border-color:var(--brand);color:#fff}.launcher{position:fixed;right:20px;bottom:20px;z-index:2147483000;box-shadow:0 6px 24px #0003}
|
|
5
|
+
dialog{background:var(--bg);color:var(--fg);border:1px solid var(--rule);border-radius:16px;padding:0;width:min(480px,calc(100vw - 24px));max-height:calc(100dvh - 32px);box-shadow:0 24px 80px #0005}dialog::backdrop{background:#19152e66}header{display:flex;align-items:center;justify-content:space-between;padding:16px 20px;border-bottom:1px solid var(--rule)}h2{font-size:20px;margin:0}.body{padding:20px;overflow:auto;max-height:calc(100dvh - 130px)}label{display:block;font-weight:600;margin-bottom:8px}textarea{width:100%;min-height:110px;resize:vertical;border:1px solid var(--rule);border-radius:10px;padding:12px;color:var(--fg);background:var(--bg)}select{padding:8px;border:1px solid var(--rule);border-radius:8px;color:var(--fg);background:var(--bg);margin-bottom:14px}.actions{display:flex;gap:8px;flex-wrap:wrap;margin-top:12px}.messages p{white-space:pre-wrap;padding:12px;border-radius:10px;background:color-mix(in srgb,var(--brand) 8%,var(--bg));overflow-wrap:anywhere}.messages .user{margin-left:24px;background:color-mix(in srgb,var(--brand) 15%,var(--bg))}.match{border:1px solid var(--rule);border-radius:12px;padding:12px;margin:10px 0}.match p{margin:0 0 8px}small,.status{color:var(--muted)}.error{color:#c23748;white-space:pre-wrap}.hidden{display:none}a{color:var(--brand)}
|
|
6
|
+
:host([data-presentation=inline]){display:block} :host([data-presentation=inline]) dialog{position:static;margin:0;width:100%;max-height:none;border:0;border-radius:0;box-shadow:none} :host([data-presentation=inline]) .body{max-height:none}
|
|
7
|
+
`;let s=document.createElement(`dialog`);s.setAttribute(`aria-labelledby`,`feedback-title`),s.lang=e.locale??document.documentElement.lang??`en`,s.append(i(`header`,{},[i(`h2`,{id:`feedback-title`}),i(`button`,{type:`button`,"data-close":``})]),i(`div`,{class:`body`},[i(`p`,{class:`error`,role:`alert`}),i(`p`,{class:`status`,role:`status`,"aria-live":`polite`}),i(`div`,{class:`messages`,role:`log`,"aria-live":`polite`}),i(`div`,{class:`matches`}),i(`form`,{},[i(`label`,{for:`feedback-kind`}),i(`select`,{id:`feedback-kind`},[i(`option`,{value:`feature_request`}),i(`option`,{value:`bug_report`})]),i(`label`,{for:`feedback-message`}),i(`textarea`,{id:`feedback-message`,maxlength:`4000`,required:``}),i(`div`,{class:`actions`},[i(`button`,{class:`primary`,type:`submit`,"data-send":``}),i(`button`,{type:`button`,"data-submit":``,class:`hidden`}),i(`button`,{type:`button`,"data-another":``,class:`hidden`})])])])),e.presentation===`inline`&&(s.open=!0,s.querySelector(`[data-close]`).hidden=!0),a.append(o,s),(e.target??document.body).append(n);let c=e=>s.querySelector(e),l=c(`textarea`),u=c(`select`),d=c(`[data-send]`),f=c(`[data-submit]`),p=c(`[data-another]`),m=c(`.messages`),h=c(`.matches`),g=c(`.status`),_=c(`.error`);return c(`h2`).textContent=t.title,c(`[data-close]`).textContent=t.close,c(`label[for=feedback-kind]`).textContent=t.title,c(`label[for=feedback-message]`).textContent=t.message,u.options[0].textContent=t.feature,u.options[1].textContent=t.bug,l.placeholder=t.placeholder,d.textContent=t.send,f.textContent=t.submit,p.textContent=t.another,{labels:t,host:n,root:a,dialog:s,input:l,kind:u,send:d,submit:f,another:p,messages:m,matches:h,status:g,error:_}}var o=class{ui;client;theme=matchMedia(`(prefers-color-scheme: dark)`);conversation;item;opened=!1;destroyed=!1;pending=!1;epoch=0;returnFocus=null;poll;launcher;constructor(e){this.options=e,this.client=new n(e),this.ui=a(e),this.theme.addEventListener(`change`,this.applyTheme),this.applyTheme(),this.bindControls(),this.createLauncher(),this.opened=e.presentation===`inline`}applyTheme=()=>{this.ui.host.dataset.theme=this.options.theme===`auto`||!this.options.theme?this.theme.matches?`dark`:`light`:this.options.theme};launch=()=>this.open();createLauncher(){this.options.presentation===`inline`||this.options.launcher===!1||(this.launcher=this.options.launcher,this.launcher||(this.launcher=document.createElement(`button`),this.launcher.className=`launcher primary`,this.launcher.textContent=this.ui.labels.launcher,this.ui.root.append(this.launcher)),this.launcher.addEventListener(`click`,this.launch))}bindControls(){let{dialog:e,submit:t,another:n}=this.ui;e.querySelector(`form`).addEventListener(`submit`,this.sendMessage),t.addEventListener(`click`,()=>void this.run(()=>this.submitDraft())),n.addEventListener(`click`,()=>this.reset()),e.querySelector(`[data-close]`).addEventListener(`click`,()=>this.close()),e.addEventListener(`cancel`,e=>{e.preventDefault(),this.close()}),e.addEventListener(`click`,t=>{if(t.target!==e)return;let n=e.getBoundingClientRect();(t.clientX<n.left||t.clientX>n.right||t.clientY<n.top||t.clientY>n.bottom)&&this.close()})}renderMessages(e){this.ui.messages.replaceChildren(...e.map(e=>{let t=document.createElement(`p`);return t.textContent=e.body,t.className=e.role===`user`||e.author===`submitter`?`user`:`assistant`,t}))}renderMatches(e){this.ui.matches.replaceChildren(...e.map(t=>this.matchCard(t,e)))}matchCard(e,t){let n=document.createElement(`article`);n.className=`match`;let r=document.createElement(`p`);r.textContent=e.title;let i=document.createElement(`small`);i.textContent=`${e.status.replaceAll(`_`,` `)} · ${e.votes}`;let a=document.createElement(`button`);return a.type=`button`,a.textContent=e.voted?this.ui.labels.voted:this.ui.labels.vote,a.setAttribute(`aria-pressed`,String(e.voted)),a.addEventListener(`click`,()=>void this.run(async()=>{let n=await this.client.vote(e.id,!e.voted);e.voted=n.voted,e.votes=n.votes,this.renderMatches(t)})),n.append(r,i,document.createElement(`br`),a),n}controls(){let{dialog:e,input:t,kind:n,send:r,submit:i,another:a,labels:o}=this.ui;for(let t of e.querySelectorAll(`.body button`))t.disabled=this.pending;t.disabled=this.pending,n.disabled=this.pending||!!this.conversation||!!this.item,r.textContent=this.pending?o.loading:this.conversation||this.item?o.reply:o.send,i.classList.toggle(`hidden`,!this.conversation||!!this.item),a.classList.toggle(`hidden`,!this.item)}async run(e){if(this.pending||this.destroyed)return;let t=this.epoch;this.pending=!0,this.ui.error.textContent=``,this.controls();try{await e()}catch(e){t===this.epoch&&(this.ui.error.textContent=e instanceof Error?e.message:`Feedback could not be sent. Please retry.`)}finally{t===this.epoch&&(this.pending=!1,this.controls())}}async refreshItem(e){let t=this.epoch,n=await this.client.getItem(e);t!==this.epoch||this.destroyed||(this.item=n,this.ui.status.textContent=`${n.title} · ${n.status}`,this.renderMessages(n.messages),this.controls())}polling(){this.poll&&clearInterval(this.poll),this.poll=setInterval(()=>{this.opened&&this.item&&!this.pending&&this.run(()=>this.refreshItem(this.item.id))},3e4)}sendMessage=e=>{e.preventDefault();let t=this.ui.input.value.trim();t&&this.run(async()=>{if(this.item)await this.client.reply(this.item.id,t),await this.refreshItem(this.item.id);else{let e=this.conversation?await this.client.sendMessage(this.conversation,t):await this.client.startConversation(t,this.ui.kind.value);this.conversation=e.conversation,this.renderMessages(this.conversation.messages),this.renderMatches(e.similar)}this.ui.input.value=``})};async submitDraft(){if(!this.conversation)return;let e=await this.client.submit(this.conversation.id,this.conversation.version);this.ui.status.textContent=this.ui.labels.sent,this.ui.matches.replaceChildren(),await this.refreshItem(e.id),this.polling(),this.options.onSubmitted?.(e)}open(e){this.destroyed||(this.returnFocus=document.activeElement,this.opened||(this.options.presentation===`inline`?this.ui.dialog.open=!0:this.ui.dialog.showModal()),this.opened=!0,this.ui.input.focus(),e&&this.run(()=>this.refreshItem(e)),this.polling())}close(){this.opened=!1,this.ui.dialog.close(),this.returnFocus?.focus(),this.poll&&clearInterval(this.poll)}reset(){this.epoch+=1,this.client.reset(),this.conversation=void 0,this.item=void 0,this.pending=!1,this.ui.input.value=``,this.ui.messages.replaceChildren(),this.ui.matches.replaceChildren(),this.ui.status.textContent=``,this.ui.error.textContent=``,this.poll&&clearInterval(this.poll),this.controls()}destroy(){this.destroyed||(this.close(),this.reset(),this.destroyed=!0,this.client.destroy(),this.launcher?.removeEventListener(`click`,this.launch),this.theme.removeEventListener(`change`,this.applyTheme),this.ui.host.remove())}};function s(e){return new o(e)}function c(e){let t=new URL(e.location.href).searchParams,n=t.get(`organization`)??``,r=t.get(`project`)??``;if(!/^[\w.-]{1,100}$/.test(n)||!/^[\w.-]{1,100}$/.test(r))throw Error(`Choose a project in the iframe URL.`);return{organization:n,project:r,query:new URLSearchParams({organization:n,project:r}).toString()}}function l(e){return!!e&&typeof e.token==`string`&&e.token.startsWith(`mcfs.${e.project}.`)&&Number.isSafeInteger(e.project)&&e.project>0&&typeof e.identity==`string`&&!!e.identity&&Number.isFinite(e.expires_at)&&e.expires_at>Date.now()/1e3}var u=class{status;signIn;disconnect;target;widget;session;popup=null;channel=``;query=``;constructor(e,t){this.win=e,this.mount=t;let n=e.document;this.status=n.querySelector(`[data-status]`),this.signIn=n.querySelector(`[data-sign-in]`),this.disconnect=n.querySelector(`[data-disconnect]`),this.target=n.querySelector(`[data-feedback]`);let r=n.querySelector(`[data-portal]`);try{let t=c(e);this.query=t.query,r.href=`/p/${encodeURIComponent(t.organization)}/${encodeURIComponent(t.project)}`,this.status.textContent=`Sign in to share feedback, vote, and follow progress.`,this.signIn.addEventListener(`click`,this.launch)}catch(e){this.status.textContent=e.message,this.signIn.disabled=!0,r.hidden=!0}this.disconnect.addEventListener(`click`,this.clear),e.addEventListener(`message`,this.receive),e.addEventListener(`pagehide`,this.dispose)}launch=()=>{this.popup?.close(),this.channel=this.win.crypto.randomUUID(),this.popup=this.win.open(`/embed/feedback-auth.html?${this.query}#${this.channel}`,`_blank`,`popup,width=540,height=720`),this.status.textContent=this.popup?`Complete sign-in in the window that opened.`:`Your browser blocked sign-in. Allow popups or open the feedback portal.`};receive=e=>{if(!this.popup||e.source!==this.popup||e.origin!==this.win.location.origin||e.data?.type!==`monochange:feedback-session`||e.data.channel!==this.channel)return;let t=e.data.session;l(t)&&(this.session?.identity!==t.identity&&(this.widget?.destroy(),this.widget=void 0),this.session=t,this.popup.close(),this.popup=null,this.disconnect.hidden=!1,this.status.textContent=`Signed in. You can share feedback below.`,this.widget??=this.mount({endpoint:this.win.location.origin,project:t.project,target:this.target,presentation:`inline`,getClientToken:this.getClientToken}))};getClientToken=async()=>{if(!this.session||this.session.expires_at<=Date.now()/1e3+30)throw this.status.textContent=`Sign in again to continue. Your draft is kept while you reconnect.`,Error(`Select Sign in to continue.`);return this.session};clear=()=>{this.popup?.close(),this.popup=null,this.session=void 0,this.widget?.destroy(),this.widget=void 0,this.disconnect.hidden=!0,this.status.textContent=`Disconnected. Sign in to share feedback.`};dispose=()=>{this.clear(),this.win.removeEventListener(`message`,this.receive),this.win.removeEventListener(`pagehide`,this.dispose),this.signIn.removeEventListener(`click`,this.launch),this.disconnect.removeEventListener(`click`,this.clear)}};function d(e,t=s){return new u(e,t).dispose}function f(e,t=e.fetch.bind(e)){let n=e.document,r=n.querySelector(`[data-status]`),i=n.querySelector(`[data-continue]`);try{let n=c(e),a=e.location.hash.slice(1);if(!/^[\w-]{36}$/.test(a)||!e.opener||e.parent!==e)throw Error(`Open sign-in from the feedback widget.`);r.textContent=`Continue to feedback for ${n.organization}/${n.project}. This shares only a feedback session with the widget.`,i.addEventListener(`click`,async()=>{i.disabled=!0;try{let i=await t(`/api/feedback_iframe_session`,{method:`POST`,credentials:`same-origin`,redirect:`error`,headers:{"Content-Type":`application/json`},body:JSON.stringify({input:{organization:n.organization,project:n.project}})});if(i.status===401){let t=`/embed/feedback-auth.html?${n.query}#${a}`;e.location.replace(`/login?next=${encodeURIComponent(t)}`);return}if(!i.ok)throw Error(`Feedback sign-in is unavailable. Please try again later.`);e.opener.postMessage({type:`monochange:feedback-session`,channel:a,session:await i.json()},e.location.origin),r.textContent=`Connected. You can close this window.`}catch(e){r.textContent=e.message}finally{i.disabled=!1}})}catch(e){r.textContent=e.message,i.disabled=!0}}document.querySelector(`[data-continue]`)?f(window):d(window)})();
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { AssistantReply, ClientToken, Conversation, ConversationReply, FeedbackClient, FeedbackContext, FeedbackError, FeedbackKind, FeedbackOptions, Item, Message, Receipt, Suggestion } from "./client.js";
|
|
2
|
+
import { FeedbackWidget, WidgetOptions, mountFeedback } from "./widget.js";
|
|
3
|
+
export { AssistantReply, ClientToken, Conversation, ConversationReply, FeedbackClient, FeedbackContext, FeedbackError, FeedbackKind, FeedbackOptions, FeedbackWidget, Item, Message, Receipt, Suggestion, WidgetOptions, mountFeedback };
|
package/dist/index.js
ADDED
package/dist/widget.d.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { FeedbackOptions, Receipt } from "./client.js";
|
|
2
|
+
|
|
3
|
+
//#region packages/monochange__feedback/src/widget.d.ts
|
|
4
|
+
interface WidgetOptions extends FeedbackOptions {
|
|
5
|
+
/** Inline presentation fills an embedded page without opening a modal. */
|
|
6
|
+
presentation?: "dialog" | "inline";
|
|
7
|
+
target?: HTMLElement;
|
|
8
|
+
launcher?: HTMLElement | false;
|
|
9
|
+
theme?: "light" | "dark" | "auto";
|
|
10
|
+
locale?: string;
|
|
11
|
+
styleNonce?: string;
|
|
12
|
+
labels?: Partial<typeof defaultLabels>;
|
|
13
|
+
onSubmitted?: (receipt: Receipt) => void;
|
|
14
|
+
}
|
|
15
|
+
declare const defaultLabels: {
|
|
16
|
+
title: string;
|
|
17
|
+
launcher: string;
|
|
18
|
+
close: string;
|
|
19
|
+
message: string;
|
|
20
|
+
feature: string;
|
|
21
|
+
bug: string;
|
|
22
|
+
send: string;
|
|
23
|
+
reply: string;
|
|
24
|
+
submit: string;
|
|
25
|
+
voted: string;
|
|
26
|
+
vote: string;
|
|
27
|
+
another: string;
|
|
28
|
+
loading: string;
|
|
29
|
+
sent: string;
|
|
30
|
+
placeholder: string;
|
|
31
|
+
};
|
|
32
|
+
interface FeedbackWidget {
|
|
33
|
+
open(item?: string): void;
|
|
34
|
+
close(): void;
|
|
35
|
+
reset(): void;
|
|
36
|
+
destroy(): void;
|
|
37
|
+
}
|
|
38
|
+
/** Mounts an isolated, keyboard-accessible widget; user content is always text. */
|
|
39
|
+
declare function mountFeedback(options: WidgetOptions): FeedbackWidget;
|
|
40
|
+
//#endregion
|
|
41
|
+
export { FeedbackWidget, WidgetOptions, mountFeedback };
|
package/dist/widget.js
ADDED
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
import { FeedbackClient } from "./client.js";
|
|
2
|
+
//#region packages/monochange__feedback/src/widget.ts
|
|
3
|
+
const defaultLabels = {
|
|
4
|
+
title: "Feedback",
|
|
5
|
+
launcher: "Share feedback",
|
|
6
|
+
close: "Close",
|
|
7
|
+
message: "What would you like to change?",
|
|
8
|
+
feature: "Feature or change",
|
|
9
|
+
bug: "Bug report",
|
|
10
|
+
send: "Find similar requests",
|
|
11
|
+
reply: "Send reply",
|
|
12
|
+
submit: "Submit a new request",
|
|
13
|
+
voted: "Upvoted",
|
|
14
|
+
vote: "Upvote",
|
|
15
|
+
another: "Start another request",
|
|
16
|
+
loading: "Working…",
|
|
17
|
+
sent: "Request submitted",
|
|
18
|
+
placeholder: "Describe the outcome you want, or what went wrong…"
|
|
19
|
+
};
|
|
20
|
+
function node(tag, attributes = {}, children = []) {
|
|
21
|
+
const element = document.createElement(tag);
|
|
22
|
+
for (const [name, value] of Object.entries(attributes)) element.setAttribute(name, value);
|
|
23
|
+
element.append(...children);
|
|
24
|
+
return element;
|
|
25
|
+
}
|
|
26
|
+
function createWidgetView(options) {
|
|
27
|
+
const labels = {
|
|
28
|
+
...defaultLabels,
|
|
29
|
+
...options.labels
|
|
30
|
+
};
|
|
31
|
+
const host = document.createElement("div");
|
|
32
|
+
host.dataset.monochangeFeedback = "";
|
|
33
|
+
host.dataset.presentation = options.presentation ?? "dialog";
|
|
34
|
+
const root = host.attachShadow({ mode: "open" });
|
|
35
|
+
const style = document.createElement("style");
|
|
36
|
+
if (options.styleNonce) style.nonce = options.styleNonce;
|
|
37
|
+
style.textContent = `
|
|
38
|
+
:host{--bg:#fff;--fg:#19152e;--muted:#5b5472;--rule:#d8d2e9;--brand:#4f46e5;font:15px/1.5 system-ui,sans-serif;color:var(--fg);color-scheme:light}
|
|
39
|
+
:host([data-theme=dark]){--bg:#241f3b;--fg:#f5f3ff;--muted:#c0b8d8;--rule:#49415f;color-scheme:dark}
|
|
40
|
+
*{box-sizing:border-box}button,textarea,select{font:inherit}button{cursor:pointer;border:1px solid var(--rule);border-radius:10px;padding:10px 14px;background:var(--bg);color:var(--fg)}button:disabled{cursor:wait;opacity:.6}button:focus-visible,textarea:focus-visible,select:focus-visible{outline:3px solid #a78bfa;outline-offset:2px}.primary{background:var(--brand);border-color:var(--brand);color:#fff}.launcher{position:fixed;right:20px;bottom:20px;z-index:2147483000;box-shadow:0 6px 24px #0003}
|
|
41
|
+
dialog{background:var(--bg);color:var(--fg);border:1px solid var(--rule);border-radius:16px;padding:0;width:min(480px,calc(100vw - 24px));max-height:calc(100dvh - 32px);box-shadow:0 24px 80px #0005}dialog::backdrop{background:#19152e66}header{display:flex;align-items:center;justify-content:space-between;padding:16px 20px;border-bottom:1px solid var(--rule)}h2{font-size:20px;margin:0}.body{padding:20px;overflow:auto;max-height:calc(100dvh - 130px)}label{display:block;font-weight:600;margin-bottom:8px}textarea{width:100%;min-height:110px;resize:vertical;border:1px solid var(--rule);border-radius:10px;padding:12px;color:var(--fg);background:var(--bg)}select{padding:8px;border:1px solid var(--rule);border-radius:8px;color:var(--fg);background:var(--bg);margin-bottom:14px}.actions{display:flex;gap:8px;flex-wrap:wrap;margin-top:12px}.messages p{white-space:pre-wrap;padding:12px;border-radius:10px;background:color-mix(in srgb,var(--brand) 8%,var(--bg));overflow-wrap:anywhere}.messages .user{margin-left:24px;background:color-mix(in srgb,var(--brand) 15%,var(--bg))}.match{border:1px solid var(--rule);border-radius:12px;padding:12px;margin:10px 0}.match p{margin:0 0 8px}small,.status{color:var(--muted)}.error{color:#c23748;white-space:pre-wrap}.hidden{display:none}a{color:var(--brand)}
|
|
42
|
+
:host([data-presentation=inline]){display:block} :host([data-presentation=inline]) dialog{position:static;margin:0;width:100%;max-height:none;border:0;border-radius:0;box-shadow:none} :host([data-presentation=inline]) .body{max-height:none}
|
|
43
|
+
`;
|
|
44
|
+
const dialog = document.createElement("dialog");
|
|
45
|
+
dialog.setAttribute("aria-labelledby", "feedback-title");
|
|
46
|
+
dialog.lang = options.locale ?? document.documentElement.lang ?? "en";
|
|
47
|
+
dialog.append(node("header", {}, [node("h2", { id: "feedback-title" }), node("button", {
|
|
48
|
+
type: "button",
|
|
49
|
+
"data-close": ""
|
|
50
|
+
})]), node("div", { class: "body" }, [
|
|
51
|
+
node("p", {
|
|
52
|
+
class: "error",
|
|
53
|
+
role: "alert"
|
|
54
|
+
}),
|
|
55
|
+
node("p", {
|
|
56
|
+
class: "status",
|
|
57
|
+
role: "status",
|
|
58
|
+
"aria-live": "polite"
|
|
59
|
+
}),
|
|
60
|
+
node("div", {
|
|
61
|
+
class: "messages",
|
|
62
|
+
role: "log",
|
|
63
|
+
"aria-live": "polite"
|
|
64
|
+
}),
|
|
65
|
+
node("div", { class: "matches" }),
|
|
66
|
+
node("form", {}, [
|
|
67
|
+
node("label", { for: "feedback-kind" }),
|
|
68
|
+
node("select", { id: "feedback-kind" }, [node("option", { value: "feature_request" }), node("option", { value: "bug_report" })]),
|
|
69
|
+
node("label", { for: "feedback-message" }),
|
|
70
|
+
node("textarea", {
|
|
71
|
+
id: "feedback-message",
|
|
72
|
+
maxlength: "4000",
|
|
73
|
+
required: ""
|
|
74
|
+
}),
|
|
75
|
+
node("div", { class: "actions" }, [
|
|
76
|
+
node("button", {
|
|
77
|
+
class: "primary",
|
|
78
|
+
type: "submit",
|
|
79
|
+
"data-send": ""
|
|
80
|
+
}),
|
|
81
|
+
node("button", {
|
|
82
|
+
type: "button",
|
|
83
|
+
"data-submit": "",
|
|
84
|
+
class: "hidden"
|
|
85
|
+
}),
|
|
86
|
+
node("button", {
|
|
87
|
+
type: "button",
|
|
88
|
+
"data-another": "",
|
|
89
|
+
class: "hidden"
|
|
90
|
+
})
|
|
91
|
+
])
|
|
92
|
+
])
|
|
93
|
+
]));
|
|
94
|
+
if (options.presentation === "inline") {
|
|
95
|
+
dialog.open = true;
|
|
96
|
+
dialog.querySelector("[data-close]").hidden = true;
|
|
97
|
+
}
|
|
98
|
+
root.append(style, dialog);
|
|
99
|
+
(options.target ?? document.body).append(host);
|
|
100
|
+
const find = (selector) => dialog.querySelector(selector);
|
|
101
|
+
const input = find("textarea");
|
|
102
|
+
const kind = find("select");
|
|
103
|
+
const send = find("[data-send]");
|
|
104
|
+
const submit = find("[data-submit]");
|
|
105
|
+
const another = find("[data-another]");
|
|
106
|
+
const messages = find(".messages");
|
|
107
|
+
const matches = find(".matches");
|
|
108
|
+
const status = find(".status");
|
|
109
|
+
const error = find(".error");
|
|
110
|
+
find("h2").textContent = labels.title;
|
|
111
|
+
find("[data-close]").textContent = labels.close;
|
|
112
|
+
find("label[for=feedback-kind]").textContent = labels.title;
|
|
113
|
+
find("label[for=feedback-message]").textContent = labels.message;
|
|
114
|
+
kind.options[0].textContent = labels.feature;
|
|
115
|
+
kind.options[1].textContent = labels.bug;
|
|
116
|
+
input.placeholder = labels.placeholder;
|
|
117
|
+
send.textContent = labels.send;
|
|
118
|
+
submit.textContent = labels.submit;
|
|
119
|
+
another.textContent = labels.another;
|
|
120
|
+
return {
|
|
121
|
+
labels,
|
|
122
|
+
host,
|
|
123
|
+
root,
|
|
124
|
+
dialog,
|
|
125
|
+
input,
|
|
126
|
+
kind,
|
|
127
|
+
send,
|
|
128
|
+
submit,
|
|
129
|
+
another,
|
|
130
|
+
messages,
|
|
131
|
+
matches,
|
|
132
|
+
status,
|
|
133
|
+
error
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
var WidgetController = class {
|
|
137
|
+
ui;
|
|
138
|
+
client;
|
|
139
|
+
theme = matchMedia("(prefers-color-scheme: dark)");
|
|
140
|
+
conversation;
|
|
141
|
+
item;
|
|
142
|
+
opened = false;
|
|
143
|
+
destroyed = false;
|
|
144
|
+
pending = false;
|
|
145
|
+
epoch = 0;
|
|
146
|
+
returnFocus = null;
|
|
147
|
+
poll;
|
|
148
|
+
launcher;
|
|
149
|
+
constructor(options) {
|
|
150
|
+
this.options = options;
|
|
151
|
+
this.client = new FeedbackClient(options);
|
|
152
|
+
this.ui = createWidgetView(options);
|
|
153
|
+
this.theme.addEventListener("change", this.applyTheme);
|
|
154
|
+
this.applyTheme();
|
|
155
|
+
this.bindControls();
|
|
156
|
+
this.createLauncher();
|
|
157
|
+
this.opened = options.presentation === "inline";
|
|
158
|
+
}
|
|
159
|
+
applyTheme = () => {
|
|
160
|
+
this.ui.host.dataset.theme = this.options.theme === "auto" || !this.options.theme ? this.theme.matches ? "dark" : "light" : this.options.theme;
|
|
161
|
+
};
|
|
162
|
+
launch = () => this.open();
|
|
163
|
+
createLauncher() {
|
|
164
|
+
if (this.options.presentation === "inline" || this.options.launcher === false) return;
|
|
165
|
+
this.launcher = this.options.launcher;
|
|
166
|
+
if (!this.launcher) {
|
|
167
|
+
this.launcher = document.createElement("button");
|
|
168
|
+
this.launcher.className = "launcher primary";
|
|
169
|
+
this.launcher.textContent = this.ui.labels.launcher;
|
|
170
|
+
this.ui.root.append(this.launcher);
|
|
171
|
+
}
|
|
172
|
+
this.launcher.addEventListener("click", this.launch);
|
|
173
|
+
}
|
|
174
|
+
bindControls() {
|
|
175
|
+
const { dialog, submit, another } = this.ui;
|
|
176
|
+
dialog.querySelector("form").addEventListener("submit", this.sendMessage);
|
|
177
|
+
submit.addEventListener("click", () => void this.run(() => this.submitDraft()));
|
|
178
|
+
another.addEventListener("click", () => this.reset());
|
|
179
|
+
dialog.querySelector("[data-close]").addEventListener("click", () => this.close());
|
|
180
|
+
dialog.addEventListener("cancel", (event) => {
|
|
181
|
+
event.preventDefault();
|
|
182
|
+
this.close();
|
|
183
|
+
});
|
|
184
|
+
dialog.addEventListener("click", (event) => {
|
|
185
|
+
if (event.target !== dialog) return;
|
|
186
|
+
const rect = dialog.getBoundingClientRect();
|
|
187
|
+
if (event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom) this.close();
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
renderMessages(values) {
|
|
191
|
+
this.ui.messages.replaceChildren(...values.map((message) => {
|
|
192
|
+
const paragraph = document.createElement("p");
|
|
193
|
+
paragraph.textContent = message.body;
|
|
194
|
+
paragraph.className = message.role === "user" || message.author === "submitter" ? "user" : "assistant";
|
|
195
|
+
return paragraph;
|
|
196
|
+
}));
|
|
197
|
+
}
|
|
198
|
+
renderMatches(values) {
|
|
199
|
+
this.ui.matches.replaceChildren(...values.map((suggestion) => this.matchCard(suggestion, values)));
|
|
200
|
+
}
|
|
201
|
+
matchCard(suggestion, values) {
|
|
202
|
+
const card = document.createElement("article");
|
|
203
|
+
card.className = "match";
|
|
204
|
+
const title = document.createElement("p");
|
|
205
|
+
title.textContent = suggestion.title;
|
|
206
|
+
const metadata = document.createElement("small");
|
|
207
|
+
metadata.textContent = `${suggestion.status.replaceAll("_", " ")} · ${suggestion.votes}`;
|
|
208
|
+
const vote = document.createElement("button");
|
|
209
|
+
vote.type = "button";
|
|
210
|
+
vote.textContent = suggestion.voted ? this.ui.labels.voted : this.ui.labels.vote;
|
|
211
|
+
vote.setAttribute("aria-pressed", String(suggestion.voted));
|
|
212
|
+
vote.addEventListener("click", () => void this.run(async () => {
|
|
213
|
+
const result = await this.client.vote(suggestion.id, !suggestion.voted);
|
|
214
|
+
suggestion.voted = result.voted;
|
|
215
|
+
suggestion.votes = result.votes;
|
|
216
|
+
this.renderMatches(values);
|
|
217
|
+
}));
|
|
218
|
+
card.append(title, metadata, document.createElement("br"), vote);
|
|
219
|
+
return card;
|
|
220
|
+
}
|
|
221
|
+
controls() {
|
|
222
|
+
const { dialog, input, kind, send, submit, another, labels } = this.ui;
|
|
223
|
+
for (const button of dialog.querySelectorAll(".body button")) button.disabled = this.pending;
|
|
224
|
+
input.disabled = this.pending;
|
|
225
|
+
kind.disabled = this.pending || !!this.conversation || !!this.item;
|
|
226
|
+
send.textContent = this.pending ? labels.loading : this.conversation || this.item ? labels.reply : labels.send;
|
|
227
|
+
submit.classList.toggle("hidden", !this.conversation || !!this.item);
|
|
228
|
+
another.classList.toggle("hidden", !this.item);
|
|
229
|
+
}
|
|
230
|
+
async run(action) {
|
|
231
|
+
if (this.pending || this.destroyed) return;
|
|
232
|
+
const version = this.epoch;
|
|
233
|
+
this.pending = true;
|
|
234
|
+
this.ui.error.textContent = "";
|
|
235
|
+
this.controls();
|
|
236
|
+
try {
|
|
237
|
+
await action();
|
|
238
|
+
} catch (failure) {
|
|
239
|
+
if (version === this.epoch) this.ui.error.textContent = failure instanceof Error ? failure.message : "Feedback could not be sent. Please retry.";
|
|
240
|
+
} finally {
|
|
241
|
+
if (version === this.epoch) {
|
|
242
|
+
this.pending = false;
|
|
243
|
+
this.controls();
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
async refreshItem(id) {
|
|
248
|
+
const version = this.epoch;
|
|
249
|
+
const latest = await this.client.getItem(id);
|
|
250
|
+
if (version !== this.epoch || this.destroyed) return;
|
|
251
|
+
this.item = latest;
|
|
252
|
+
this.ui.status.textContent = `${latest.title} · ${latest.status}`;
|
|
253
|
+
this.renderMessages(latest.messages);
|
|
254
|
+
this.controls();
|
|
255
|
+
}
|
|
256
|
+
polling() {
|
|
257
|
+
if (this.poll) clearInterval(this.poll);
|
|
258
|
+
this.poll = setInterval(() => {
|
|
259
|
+
if (this.opened && this.item && !this.pending) this.run(() => this.refreshItem(this.item.id));
|
|
260
|
+
}, 3e4);
|
|
261
|
+
}
|
|
262
|
+
sendMessage = (event) => {
|
|
263
|
+
event.preventDefault();
|
|
264
|
+
const body = this.ui.input.value.trim();
|
|
265
|
+
if (!body) return;
|
|
266
|
+
this.run(async () => {
|
|
267
|
+
if (this.item) {
|
|
268
|
+
await this.client.reply(this.item.id, body);
|
|
269
|
+
await this.refreshItem(this.item.id);
|
|
270
|
+
} else {
|
|
271
|
+
const result = this.conversation ? await this.client.sendMessage(this.conversation, body) : await this.client.startConversation(body, this.ui.kind.value);
|
|
272
|
+
this.conversation = result.conversation;
|
|
273
|
+
this.renderMessages(this.conversation.messages);
|
|
274
|
+
this.renderMatches(result.similar);
|
|
275
|
+
}
|
|
276
|
+
this.ui.input.value = "";
|
|
277
|
+
});
|
|
278
|
+
};
|
|
279
|
+
async submitDraft() {
|
|
280
|
+
if (!this.conversation) return;
|
|
281
|
+
const receipt = await this.client.submit(this.conversation.id, this.conversation.version);
|
|
282
|
+
this.ui.status.textContent = this.ui.labels.sent;
|
|
283
|
+
this.ui.matches.replaceChildren();
|
|
284
|
+
await this.refreshItem(receipt.id);
|
|
285
|
+
this.polling();
|
|
286
|
+
this.options.onSubmitted?.(receipt);
|
|
287
|
+
}
|
|
288
|
+
open(id) {
|
|
289
|
+
if (this.destroyed) return;
|
|
290
|
+
this.returnFocus = document.activeElement;
|
|
291
|
+
if (!this.opened) if (this.options.presentation === "inline") this.ui.dialog.open = true;
|
|
292
|
+
else this.ui.dialog.showModal();
|
|
293
|
+
this.opened = true;
|
|
294
|
+
this.ui.input.focus();
|
|
295
|
+
if (id) this.run(() => this.refreshItem(id));
|
|
296
|
+
this.polling();
|
|
297
|
+
}
|
|
298
|
+
close() {
|
|
299
|
+
this.opened = false;
|
|
300
|
+
this.ui.dialog.close();
|
|
301
|
+
this.returnFocus?.focus();
|
|
302
|
+
if (this.poll) clearInterval(this.poll);
|
|
303
|
+
}
|
|
304
|
+
reset() {
|
|
305
|
+
this.epoch += 1;
|
|
306
|
+
this.client.reset();
|
|
307
|
+
this.conversation = void 0;
|
|
308
|
+
this.item = void 0;
|
|
309
|
+
this.pending = false;
|
|
310
|
+
this.ui.input.value = "";
|
|
311
|
+
this.ui.messages.replaceChildren();
|
|
312
|
+
this.ui.matches.replaceChildren();
|
|
313
|
+
this.ui.status.textContent = "";
|
|
314
|
+
this.ui.error.textContent = "";
|
|
315
|
+
if (this.poll) clearInterval(this.poll);
|
|
316
|
+
this.controls();
|
|
317
|
+
}
|
|
318
|
+
destroy() {
|
|
319
|
+
if (this.destroyed) return;
|
|
320
|
+
this.close();
|
|
321
|
+
this.reset();
|
|
322
|
+
this.destroyed = true;
|
|
323
|
+
this.client.destroy();
|
|
324
|
+
this.launcher?.removeEventListener("click", this.launch);
|
|
325
|
+
this.theme.removeEventListener("change", this.applyTheme);
|
|
326
|
+
this.ui.host.remove();
|
|
327
|
+
}
|
|
328
|
+
};
|
|
329
|
+
/** Mounts an isolated, keyboard-accessible widget; user content is always text. */
|
|
330
|
+
function mountFeedback(options) {
|
|
331
|
+
return new WidgetController(options);
|
|
332
|
+
}
|
|
333
|
+
//#endregion
|
|
334
|
+
export { mountFeedback };
|
package/package.json
CHANGED
|
@@ -1,6 +1,36 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@monochange/feedback",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "Installable monochange feedback client and accessible website widget",
|
|
6
|
+
"license": "Unlicense",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "https://github.com/monochange/monochange"
|
|
10
|
+
},
|
|
11
|
+
"files": [
|
|
12
|
+
"dist",
|
|
13
|
+
"README.md"
|
|
14
|
+
],
|
|
15
|
+
"exports": {
|
|
16
|
+
".": {
|
|
17
|
+
"types": "./dist/index.d.ts",
|
|
18
|
+
"import": "./dist/index.js"
|
|
19
|
+
},
|
|
20
|
+
"./client": {
|
|
21
|
+
"types": "./dist/client.d.ts",
|
|
22
|
+
"import": "./dist/client.js"
|
|
23
|
+
},
|
|
24
|
+
"./widget": {
|
|
25
|
+
"types": "./dist/widget.d.ts",
|
|
26
|
+
"import": "./dist/widget.js"
|
|
27
|
+
}
|
|
28
|
+
},
|
|
29
|
+
"publishConfig": {
|
|
30
|
+
"access": "public",
|
|
31
|
+
"provenance": true
|
|
32
|
+
},
|
|
33
|
+
"scripts": {
|
|
34
|
+
"build": "pnpm --dir ../.. build:feedback"
|
|
35
|
+
}
|
|
6
36
|
}
|