@stephansama/starlight-giscus 0.9.1

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025-present, Bugo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,9 @@
1
+ # starlight-giscus
2
+
3
+ This Starlight plugin ties your documentation to GitHub discussions, givin' you a handy way to comment and react.
4
+
5
+ ## Getting Started
6
+
7
+ Want to get started immediately? Check out the [getting started guide](https://dragomano.github.io/starlight-giscus/getting-started/) or check out the [configuration](https://dragomano.github.io/starlight-giscus/configuration/) to see the available options.
8
+
9
+ [Starlight Plugins by Example](https://hideoo.dev/notebooks/starlight-plugins-by-example)
@@ -0,0 +1,111 @@
1
+ ---
2
+ import config from 'virtual:starlight-giscus-config';
3
+ const { entry, lang } = Astro.locals.starlightRoute;
4
+ const {
5
+ element,
6
+ repo,
7
+ repoId,
8
+ category,
9
+ categoryId,
10
+ mapping,
11
+ reactions,
12
+ inputPosition,
13
+ theme,
14
+ lazy
15
+ } = config;
16
+ const preparedTheme = typeof theme === 'object' ? theme : { auto: theme };
17
+ const giscus = entry.data.giscus ?? true;
18
+ ---
19
+ {
20
+ giscus && (
21
+ <giscus-comments data-theme={JSON.stringify(preparedTheme)} data-element={element}>
22
+ <div class="comments">
23
+ <script is:inline define:vars={{ preparedTheme }}>
24
+ (function () {
25
+ const palette = localStorage.getItem('starlight-theme') || 'preferred_color_scheme';
26
+ const initial = palette === 'dark'
27
+ ? (preparedTheme.dark || 'dark')
28
+ : (palette === 'light'
29
+ ? (preparedTheme.light || 'light')
30
+ : (preparedTheme.auto || 'preferred_color_scheme'));
31
+ const next = document.currentScript && document.currentScript.nextElementSibling;
32
+ if (next) next.setAttribute('data-theme', initial);
33
+ })();
34
+ </script>
35
+ <script
36
+ is:inline
37
+ src="https://giscus.app/client.js"
38
+ data-repo={repo}
39
+ data-repo-id={repoId}
40
+ data-category={category}
41
+ data-category-id={categoryId}
42
+ data-mapping={mapping}
43
+ data-strict="1"
44
+ data-reactions-enabled={+reactions}
45
+ data-emit-metadata="0"
46
+ data-input-position={inputPosition}
47
+ data-theme={preparedTheme.auto}
48
+ data-lang={lang}
49
+ data-loading={lazy ? 'lazy' : null}
50
+ crossorigin="anonymous"
51
+ async
52
+ >
53
+ </script>
54
+ </div>
55
+ </giscus-comments>
56
+
57
+ <script>
58
+ class GiscusComments extends HTMLElement {
59
+ constructor() {
60
+ super();
61
+
62
+ const theme = JSON.parse(this.dataset.theme!)
63
+ const element = this.dataset.element || 'starlight-theme-select'
64
+ const darkTheme = theme.dark || 'dark';
65
+ const lightTheme = theme.light || 'light';
66
+ const preferredTheme = theme.auto || 'preferred_color_scheme';
67
+
68
+ const getThemeValue = (fallback = 'preferred_color_scheme') => {
69
+ const palette = localStorage.getItem('starlight-theme') || fallback
70
+
71
+ return palette === 'dark'
72
+ ? darkTheme
73
+ : (palette === 'light' ? lightTheme : preferredTheme)
74
+ }
75
+
76
+ function setGiscusTheme() {
77
+ const frame: HTMLIFrameElement = document.querySelector('iframe.giscus-frame')!
78
+ const theme = getThemeValue();
79
+
80
+ frame.contentWindow?.postMessage(
81
+ {
82
+ giscus: {
83
+ setConfig: {
84
+ theme: theme
85
+ }
86
+ }
87
+ },
88
+ '*'
89
+ )
90
+ }
91
+
92
+ function handleGiscusMessage(event: MessageEvent) {
93
+ if (event.origin !== 'https://giscus.app') return;
94
+ if (!(typeof event.data === 'object' && event.data.giscus)) return;
95
+ setGiscusTheme();
96
+ }
97
+
98
+ window.addEventListener('message', handleGiscusMessage);
99
+
100
+ document.addEventListener('DOMContentLoaded', function() {
101
+ const ref: Element = document.querySelector(element)!
102
+
103
+ ref.addEventListener('change', setGiscusTheme)
104
+ })
105
+ }
106
+ }
107
+
108
+ customElements.define('giscus-comments', GiscusComments);
109
+ </script>
110
+ )
111
+ }
package/index.ts ADDED
@@ -0,0 +1,124 @@
1
+ import type { StarlightPlugin } from '@astrojs/starlight/types';
2
+ import { AstroError } from 'astro/errors';
3
+ import { vitePluginStarlightGiscusConfig } from './libs/vite';
4
+ import { overrideStarlightComponent } from './libs/starlight';
5
+
6
+ export interface StarlightGiscusThemeObject {
7
+ light?: string;
8
+ dark?: string;
9
+ auto?: string;
10
+ }
11
+
12
+ export type StarlightGiscusTheme = string | StarlightGiscusThemeObject;
13
+
14
+ export interface StarlightGiscusUserConfig {
15
+ element?: string;
16
+ repo: string;
17
+ repoId: string;
18
+ category: string;
19
+ categoryId: string;
20
+ mapping?: string;
21
+ reactions?: boolean;
22
+ inputPosition?: string;
23
+ theme?: StarlightGiscusTheme;
24
+ lazy?: boolean;
25
+ }
26
+
27
+ export interface StarlightGiscusConfig {
28
+ element: string;
29
+ repo: string;
30
+ repoId: string;
31
+ category: string;
32
+ categoryId: string;
33
+ mapping: string;
34
+ reactions: boolean;
35
+ inputPosition: string;
36
+ theme: string | StarlightGiscusThemeObject;
37
+ lazy: boolean;
38
+ }
39
+
40
+ function validateAndNormalizeConfig(
41
+ options: StarlightGiscusUserConfig
42
+ ): StarlightGiscusConfig {
43
+ // Validate required fields
44
+ const requiredFields: (keyof StarlightGiscusUserConfig)[] = [
45
+ 'repo',
46
+ 'repoId',
47
+ 'category',
48
+ 'categoryId',
49
+ ];
50
+
51
+ for (const field of requiredFields) {
52
+ if (!options[field]) {
53
+ throw new AstroError(
54
+ `The provided plugin configuration is invalid. Missing required field: ${field}`
55
+ );
56
+ }
57
+ }
58
+
59
+ // Normalize theme
60
+ let normalizedTheme: StarlightGiscusConfig['theme'];
61
+ if (typeof options.theme === 'object' && options.theme !== null) {
62
+ normalizedTheme = {
63
+ light: options.theme.light ?? 'light',
64
+ dark: options.theme.dark ?? 'dark',
65
+ auto: options.theme.auto ?? 'preferred_color_scheme',
66
+ };
67
+ } else {
68
+ normalizedTheme = options.theme ?? 'preferred_color_scheme';
69
+ }
70
+
71
+ // Return config with defaults
72
+ return {
73
+ element: options.element ?? 'starlight-theme-select',
74
+ repo: options.repo,
75
+ repoId: options.repoId,
76
+ category: options.category,
77
+ categoryId: options.categoryId,
78
+ mapping: options.mapping ?? 'pathname',
79
+ reactions: options.reactions ?? true,
80
+ inputPosition: options.inputPosition ?? 'bottom',
81
+ theme: normalizedTheme,
82
+ lazy: options.lazy ?? false,
83
+ };
84
+ }
85
+
86
+ export { validateAndNormalizeConfig };
87
+
88
+ export default function starlightGiscus(
89
+ options: StarlightGiscusUserConfig
90
+ ): StarlightPlugin {
91
+ const config = validateAndNormalizeConfig(options);
92
+
93
+ return {
94
+ name: 'starlight-giscus',
95
+ hooks: {
96
+ 'config:setup'({ logger, config: starlightConfig, updateConfig, addIntegration }) {
97
+ updateConfig({
98
+ components: {
99
+ ...starlightConfig.components,
100
+ ...overrideStarlightComponent(
101
+ starlightConfig.components,
102
+ logger,
103
+ 'Pagination',
104
+ 'Pagination'
105
+ ),
106
+ },
107
+ });
108
+
109
+ addIntegration({
110
+ name: 'starlight-giscus-integration',
111
+ hooks: {
112
+ 'astro:config:setup': ({ updateConfig }) => {
113
+ updateConfig({
114
+ vite: {
115
+ plugins: [vitePluginStarlightGiscusConfig(config)],
116
+ },
117
+ });
118
+ },
119
+ },
120
+ });
121
+ },
122
+ },
123
+ };
124
+ }
@@ -0,0 +1,24 @@
1
+ import type { StarlightUserConfig } from '@astrojs/starlight/types';
2
+ import type { AstroIntegrationLogger } from 'astro';
3
+
4
+ export function overrideStarlightComponent(
5
+ components: StarlightUserConfig['components'],
6
+ logger: AstroIntegrationLogger,
7
+ override: keyof NonNullable<StarlightUserConfig['components']>,
8
+ component: string
9
+ ) {
10
+ if (components?.[override]) {
11
+ logger.warn(
12
+ `It looks like you already have a \`${String(override)}\` component override in your Starlight configuration.`
13
+ );
14
+ logger.warn(
15
+ `To use \`starlight-giscus\`, either remove your override or update it to render the content from \`starlight-giscus/components/${component}.astro\`.`
16
+ );
17
+
18
+ return {};
19
+ }
20
+
21
+ return {
22
+ [override]: `starlight-giscus/overrides/${String(override)}.astro`,
23
+ };
24
+ }
package/libs/vite.ts ADDED
@@ -0,0 +1,38 @@
1
+ import type { ViteUserConfig } from 'astro';
2
+ import type { StarlightGiscusConfig } from '..';
3
+
4
+ export function vitePluginStarlightGiscusConfig(
5
+ starlightGiscusConfig: StarlightGiscusConfig
6
+ ): VitePlugin {
7
+ const modules = {
8
+ 'virtual:starlight-giscus-config': `export default ${JSON.stringify(
9
+ starlightGiscusConfig
10
+ )}`,
11
+ };
12
+
13
+ const moduleResolutionMap = Object.fromEntries(
14
+ (Object.keys(modules) as (keyof typeof modules)[]).map((key) => [
15
+ resolveVirtualModuleId(key),
16
+ key,
17
+ ])
18
+ );
19
+
20
+ return {
21
+ name: 'vite-plugin-starlight-giscus',
22
+ load(id) {
23
+ const moduleId = moduleResolutionMap[id];
24
+ return moduleId ? modules[moduleId] : undefined;
25
+ },
26
+ resolveId(id) {
27
+ return id in modules ? resolveVirtualModuleId(id) : undefined;
28
+ },
29
+ };
30
+ }
31
+
32
+ function resolveVirtualModuleId<TModuleId extends string>(
33
+ id: TModuleId
34
+ ): `\0${TModuleId}` {
35
+ return `\0${id}`;
36
+ }
37
+
38
+ type VitePlugin = NonNullable<ViteUserConfig['plugins']>[number];
@@ -0,0 +1,7 @@
1
+ ---
2
+ import Default from '@astrojs/starlight/components/Pagination.astro';
3
+ import Comments from '../components/Comments.astro';
4
+ ---
5
+
6
+ <Comments />
7
+ <Default />
package/package.json ADDED
@@ -0,0 +1,55 @@
1
+ {
2
+ "name": "@stephansama/starlight-giscus",
3
+ "version": "0.9.1",
4
+ "license": "MIT",
5
+ "description": "A Starlight plugin for adding Giscus comments to your documentation.",
6
+ "keywords": [
7
+ "starlight",
8
+ "starlight-plugin",
9
+ "giscus",
10
+ "discussions",
11
+ "github-discussions",
12
+ "reactions",
13
+ "comments"
14
+ ],
15
+ "author": "Bugo",
16
+ "type": "module",
17
+ "types": "./index.ts",
18
+ "exports": {
19
+ ".": "./index.ts",
20
+ "./components/Comments.astro": "./components/Comments.astro",
21
+ "./overrides/Pagination.astro": "./overrides/Pagination.astro",
22
+ "./package.json": "./package.json"
23
+ },
24
+ "devDependencies": {
25
+ "@vitest/coverage-v8": "^4.0.18",
26
+ "@vitest/ui": "^4.0.18",
27
+ "tsc-files": "^1.1.4",
28
+ "vite": "^7.3.1",
29
+ "vitest": "^4.0.18"
30
+ },
31
+ "peerDependencies": {
32
+ "@astrojs/starlight": ">=0.37.0"
33
+ },
34
+ "engines": {
35
+ "node": ">=20.0.0"
36
+ },
37
+ "publishConfig": {
38
+ "access": "public"
39
+ },
40
+ "sideEffects": false,
41
+ "homepage": "https://github.com/dragomano/starlight-giscus",
42
+ "repository": {
43
+ "type": "git",
44
+ "url": "https://github.com/dragomano/starlight-giscus.git",
45
+ "directory": "packages/starlight-giscus"
46
+ },
47
+ "bugs": "https://github.com/dragomano/starlight-giscus/issues",
48
+ "scripts": {
49
+ "test": "vitest run",
50
+ "test:watch": "vitest",
51
+ "test:ui": "vitest --ui",
52
+ "test:coverage": "vitest run --coverage",
53
+ "typecheck": "tsc-files --noEmit index.ts libs/starlight.ts libs/vite.ts tests/*.test.ts"
54
+ }
55
+ }
package/virtual.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ declare module "virtual:starlight-giscus-config" {
2
+ const StarlightGiscusConfig: import("./index").StarlightGiscusConfig;
3
+ export default StarlightGiscusConfig;
4
+ }