-
Notifications
You must be signed in to change notification settings - Fork 25
/
giscus.ts
416 lines (358 loc) · 10.3 KB
/
giscus.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
import { html, css, LitElement, PropertyDeclaration } from 'lit';
import { customElement, property } from 'lit/decorators.js';
import { createRef, ref, Ref } from 'lit/directives/ref.js';
import {
Repo,
Mapping,
BooleanString,
InputPosition,
Theme,
AvailableLanguage,
Loading,
} from './types';
export * from './types';
function safeCustomElement(tagName: string): ReturnType<typeof customElement> {
// Prevents re-registering an element.
return customElements.get(tagName) ? (v) => v : customElement(tagName);
}
/**
* Widget element for giscus.
*/
@safeCustomElement('giscus-widget')
export class GiscusWidget extends LitElement {
private GISCUS_SESSION_KEY = 'giscus-session';
private GISCUS_DEFAULT_HOST = 'https://giscus.app';
private ERROR_SUGGESTION = `Please consider reporting this error at https://github.com/giscus/giscus/issues/new.`;
private __session = '';
private _iframeRef: Ref<HTMLIFrameElement> = createRef();
private messageEventHandler = this.handleMessageEvent.bind(this);
private hasLoaded = false;
get iframeRef() {
return this._iframeRef?.value;
}
static styles = css`
:host,
iframe {
width: 100%;
border: none;
min-height: 150px;
color-scheme: light dark;
}
iframe.loading {
opacity: 0;
}
`;
/**
* Host of the giscus server.
*/
@property({ reflect: true })
host: string = this.GISCUS_DEFAULT_HOST;
get _host() {
// Ensure that the host is always a valid URL even if the attribute
// has been set to an invalid value.
try {
new URL(this.host);
return this.host;
} catch {
return this.GISCUS_DEFAULT_HOST;
}
}
/**
* Repo where the discussion is stored.
*/
@property({ reflect: true })
repo!: Repo;
/**
* ID of the repo where the discussion is stored.
*/
@property({ reflect: true })
repoId?: string;
/**
* Category where the discussion will be searched.
*/
@property({ reflect: true })
category?: string;
/**
* ID of the category where new discussions will be created.
*/
@property({ reflect: true })
categoryId?: string;
/**
* Mapping between the parent page and the discussion.
*/
@property({ reflect: true })
mapping?: Mapping;
/**
* Search term to use when searching for the discussion.
*/
@property({ reflect: true })
term?: string;
/**
* Use strict title matching.
*/
@property({ reflect: true })
strict: BooleanString = '0';
/**
* Enable reactions to the main post of the discussion.
*/
@property({ reflect: true })
reactionsEnabled: BooleanString = '1';
/**
* Emit the discussion metadata periodically to the parent page.
*/
@property({ reflect: true })
emitMetadata: BooleanString = '0';
/**
* Placement of the comment box (`top` or `bottom`).
*/
@property({ reflect: true })
inputPosition: InputPosition = 'bottom';
/**
* Theme that giscus will be displayed in.
*/
@property({ reflect: true })
theme: Theme = 'light';
/**
* Language that giscus will be displayed in.
*/
@property({ reflect: true })
lang: AvailableLanguage = 'en';
/**
* Whether the iframe should be loaded lazily or eagerly.
*/
@property({ reflect: true })
loading: Loading = 'eager';
constructor() {
super();
this.setupSession();
window.addEventListener('message', this.messageEventHandler);
}
disconnectedCallback() {
super.disconnectedCallback();
window.removeEventListener('message', this.messageEventHandler);
}
private _formatError(message: string) {
return `[giscus] An error occurred. Error message: "${message}".`;
}
private setupSession() {
const origin = location.href;
const url = new URL(origin);
const savedSession = localStorage.getItem(this.GISCUS_SESSION_KEY);
const urlSession = url.searchParams.get('giscus') ?? '';
this.__session = '';
if (urlSession) {
localStorage.setItem(this.GISCUS_SESSION_KEY, JSON.stringify(urlSession));
this.__session = urlSession;
url.searchParams.delete('giscus');
url.hash = '';
history.replaceState(undefined, document.title, url.toString());
return;
}
if (savedSession) {
try {
this.__session = JSON.parse(savedSession) as string;
} catch (e) {
localStorage.removeItem(this.GISCUS_SESSION_KEY);
console.warn(
`${this._formatError(
(e as Record<string, string>)?.message
)} Session has been cleared.`
);
}
}
}
private signOut() {
localStorage.removeItem(this.GISCUS_SESSION_KEY);
this.__session = '';
this.update(new Map());
}
private handleMessageEvent(event: MessageEvent<GiscusMessage>) {
if (event.origin !== this._host) return;
const { data } = event;
if (!(typeof data === 'object' && data.giscus)) return;
if (this.iframeRef && data.giscus.resizeHeight) {
this.iframeRef.style.height = `${data.giscus.resizeHeight}px`;
}
if (data.giscus.signOut) {
console.info(`[giscus] User has logged out. Session has been cleared.`);
this.signOut();
return;
}
if (!data.giscus.error) return;
const message: string = data.giscus.error;
if (
message.includes('Bad credentials') ||
message.includes('Invalid state value') ||
message.includes('State has expired')
) {
// Might be because token is expired or other causes
if (localStorage.getItem(this.GISCUS_SESSION_KEY) !== null) {
console.warn(`${this._formatError(message)} Session has been cleared.`);
this.signOut();
return;
}
console.error(
`${this._formatError(message)} No session is stored initially. ${
this.ERROR_SUGGESTION
}`
);
}
if (message.includes('Discussion not found')) {
console.warn(
`[giscus] ${message}. A new discussion will be created if a comment/reaction is submitted.`
);
return;
}
console.error(`${this._formatError(message)} ${this.ERROR_SUGGESTION}`);
}
private sendMessage<T>(message: T) {
if (!this.iframeRef?.contentWindow || !this.hasLoaded) return;
this.iframeRef.contentWindow.postMessage({ giscus: message }, this._host);
}
private updateConfig() {
const setConfig: ISetConfigMessage = {
setConfig: {
repo: this.repo,
repoId: this.repoId,
category: this.category,
categoryId: this.categoryId,
term: this.getTerm(),
number: +this.getNumber(),
strict: this.strict === '1',
reactionsEnabled: this.reactionsEnabled === '1',
emitMetadata: this.emitMetadata === '1',
inputPosition: this.inputPosition,
theme: this.theme,
lang: this.lang,
},
};
this.sendMessage(setConfig);
}
firstUpdated() {
this.iframeRef?.addEventListener('load', () => {
this.iframeRef?.classList.remove('loading');
this.hasLoaded = true;
// Make sure to update the config in case the iframe is loaded lazily.
this.updateConfig();
});
}
requestUpdate(
name?: PropertyKey,
oldValue?: unknown,
options?: PropertyDeclaration<unknown, unknown>
): void {
// Only rerender (update) on initial load or if the host changes.
if (!this.hasUpdated || name === 'host') {
super.requestUpdate(name, oldValue, options);
return;
}
// After loaded, just update the config without rerendering.
this.updateConfig();
}
private getMetaContent(property: string, og = false) {
const ogSelector = og ? `meta[property='og:${property}'],` : '';
const element = document.querySelector<HTMLMetaElement>(
ogSelector + `meta[name='${property}']`
);
return element ? element.content : '';
}
private _getCleanedUrl() {
const url = new URL(location.href);
url.searchParams.delete('giscus');
url.hash = '';
return url;
}
private getTerm() {
switch (this.mapping) {
case 'url':
return this._getCleanedUrl().toString();
case 'title':
return document.title;
case 'og:title':
return this.getMetaContent('title', true);
case 'specific':
return this.term ?? '';
case 'number':
return '';
case 'pathname':
default:
return location.pathname.length < 2
? 'index'
: location.pathname.substring(1).replace(/\.\w+$/, '');
}
}
private getNumber() {
return this.mapping === 'number' ? (this.term ?? '') : '';
}
private getIframeSrc() {
const url = this._getCleanedUrl().toString();
const origin = `${url}${this.id ? '#' + this.id : ''}`;
const description = this.getMetaContent('description', true);
const backLink = this.getMetaContent('giscus:backlink') || url;
const params: Record<string, string> = {
origin,
session: this.__session,
repo: this.repo,
repoId: this.repoId ?? '',
category: this.category ?? '',
categoryId: this.categoryId ?? '',
term: this.getTerm(),
number: this.getNumber(),
strict: this.strict,
reactionsEnabled: this.reactionsEnabled,
emitMetadata: this.emitMetadata,
inputPosition: this.inputPosition,
theme: this.theme,
description,
backLink,
};
const host = this._host;
const locale = this.lang ? `/${this.lang}` : '';
const searchParams = new URLSearchParams(params);
return `${host}${locale}/widget?${searchParams.toString()}`;
}
render() {
return html`
<iframe
title="Comments"
scrolling="no"
class="loading"
${ref(this._iframeRef)}
src=${this.getIframeSrc()}
loading=${this.loading}
allow="clipboard-write"
part="iframe"
></iframe>
`;
}
}
declare global {
interface HTMLElementTagNameMap {
'giscus-widget': GiscusWidget;
}
}
export interface ISetConfigMessage {
setConfig: {
theme?: Theme;
repo?: Repo;
repoId?: string;
category?: string;
categoryId?: string;
term?: string;
description?: string;
backLink?: string;
number?: number;
strict?: boolean;
reactionsEnabled?: boolean;
emitMetadata?: boolean;
inputPosition?: InputPosition;
lang?: AvailableLanguage;
};
}
export interface GiscusMessage {
giscus?: Partial<{
resizeHeight: number;
signOut: boolean;
error: string;
}>;
}