@open330/kiwimu 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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 jiunbae
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,230 @@
1
+ <div align="center">
2
+
3
+ <img src="assets/logos/logo_2_minimalist_icon_transparent.png" alt="Kiwi Mu" width="120">
4
+
5
+ # Kiwi Mu
6
+
7
+ **나만의 학습 위키를 만드세요**
8
+
9
+ 전공책, PDF, 웹 콘텐츠를 넣으면 — LLM이 챕터/개념별로 분석하여 상호 링크된 학습 위키를 자동 생성합니다.
10
+
11
+ [![Bun](https://img.shields.io/badge/Bun-1.0+-fbf0df?style=flat-square&logo=bun&logoColor=black)](https://bun.sh)
12
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.0+-3178C6?style=flat-square&logo=typescript&logoColor=white)](https://typescriptlang.org)
13
+ [![License](https://img.shields.io/badge/License-MIT-green?style=flat-square)](LICENSE)
14
+
15
+ </div>
16
+
17
+ ---
18
+
19
+ ## Quickstart for Agents
20
+
21
+ <div><img src="https://quickstart-for-agents.vercel.app/api/header.svg?theme=claude-code&logo=kiwimu&title=Set+up+a+learning+wiki+from+any+textbook+or+URL&lang=Agents&font=mono&mascot=hat" width="100%" /></div>
22
+
23
+ ```
24
+ git clone https://github.com/Open330/kiwimu.git && cd kiwimu && bun install
25
+ mkdir my-wiki && cd my-wiki
26
+ bunx kiwimu init
27
+ bunx kiwimu add "<YOUR_URL_OR_PDF>"
28
+ bunx kiwimu serve
29
+ ```
30
+
31
+ <div><img src="https://quickstart-for-agents.vercel.app/api/footer.svg?theme=claude-code&text=copy+this+prompt+%C2%B7+paste+into+your+agent+%C2%B7+get+a+learning+wiki&font=mono" width="100%" /></div>
32
+
33
+ ---
34
+
35
+ ## Why Kiwi Mu?
36
+
37
+ 교과서 한 권을 읽으면 수십 개의 개념이 서로 연결됩니다.
38
+ Kiwi Mu는 LLM을 활용해 이 연결을 **자동으로** 만들어, 지식을 빠르게 탐색할 수 있는 위키로 변환합니다.
39
+
40
+ - **LLM 기반 문서 분석** — 챕터/섹션 구조를 보존한 원본 페이지 + 핵심 개념별 자동 생성 페이지
41
+ - **원본/개념 분리** — 📖 원본 문서와 📝 개념 문서를 시각적으로 구분
42
+ - **자동 상호 링크** — 원본↔개념 간 유기적 cross-link + 외부 참고 자료 (Wikipedia 등)
43
+ - **지식 그래프** — D3.js 인터랙티브 그래프 (원본: 파란색, 개념: 초록색)
44
+ - **웹 UI** — 브라우저에서 문서 추가, 설정 변경, 빌드 실행
45
+ - **다양한 파일 지원** — URL, PDF, DOCX, PPTX, PPT, DOC, KEY
46
+ - **다중 LLM 프로바이더** — Google Gemini, Azure OpenAI, OpenAI, Anthropic
47
+ - **토큰 사용량 추적** — API 호출 수, 토큰, 예상 비용을 웹에서 확인
48
+ - **원클릭 배포** — GitHub Pages / Vercel
49
+
50
+ ## Quick Start
51
+
52
+ ### 설치
53
+
54
+ ```bash
55
+ git clone https://github.com/Open330/kiwimu.git
56
+ cd kiwimu && bun install
57
+ ```
58
+
59
+ ### 프로젝트 생성 (Interactive CLI)
60
+
61
+ ```bash
62
+ mkdir my-wiki && cd my-wiki
63
+ bunx kiwimu init
64
+ ```
65
+
66
+ Interactive 프롬프트가 실행됩니다:
67
+
68
+ ```
69
+ 🥝 Kiwi Mu — 새 학습 위키 만들기
70
+
71
+ ◆ 위키 이름
72
+ │ Radio Astronomy Wiki
73
+
74
+ ◆ LLM 프로바이더
75
+ │ ● Google Gemini (무료 API key: aistudio.google.com)
76
+ │ ○ Azure OpenAI
77
+ │ ○ OpenAI
78
+ │ ○ Anthropic Claude
79
+
80
+ ◆ 모델명
81
+ │ gemini-2.0-flash-lite
82
+
83
+ ◆ API Key
84
+ │ ••••••••••••
85
+
86
+ 🥝 'Radio Astronomy Wiki' 위키가 생성되었습니다!
87
+ ```
88
+
89
+ 이름을 바로 지정할 수도 있습니다:
90
+
91
+ ```bash
92
+ bunx kiwimu init "My Study Wiki"
93
+ ```
94
+
95
+ ### 문서 추가
96
+
97
+ ```bash
98
+ # URL 추가
99
+ bunx kiwimu add "https://www.cv.nrao.edu/~sransom/web/Ch1.html"
100
+
101
+ # PDF 추가
102
+ bunx kiwimu add textbook.pdf
103
+ ```
104
+
105
+ LLM이 문서를 분석하여:
106
+ 1. 📖 **원본 페이지** — 원래 챕터/섹션 구조 보존
107
+ 2. 📝 **개념 페이지** — 핵심 용어·정의·법칙 자동 생성
108
+ 3. 🔗 **Cross-link** — 원본↔개념 간 유기적 연결
109
+
110
+ ### 빌드 및 서버
111
+
112
+ ```bash
113
+ # 정적 사이트 빌드
114
+ bunx kiwimu build
115
+
116
+ # 로컬 서버 실행 (웹에서 문서 추가 가능)
117
+ bunx kiwimu serve
118
+ # → http://localhost:8000
119
+
120
+ # 포트 변경
121
+ bunx kiwimu serve -p 3000
122
+
123
+ # 네트워크에 공개 (0.0.0.0)
124
+ bunx kiwimu serve --host 0.0.0.0
125
+ ```
126
+
127
+ ### 웹 UI에서 문서 추가
128
+
129
+ `kiwimu serve` 실행 후 http://localhost:8000 에서:
130
+ - **🔗 URL 탭** — URL 입력 후 추가
131
+ - **📄 파일 업로드 탭** — PDF, DOCX, PPTX 등 드래그앤드롭 업로드
132
+ - 진행 상태 실시간 표시, 완료 시 자동 새로고침
133
+
134
+ ### 관리 페이지
135
+
136
+ http://localhost:8000/admin 에서:
137
+ - 위키 이름 변경
138
+ - LLM 프로바이더/모델/API Key 설정
139
+ - 토큰 사용량 및 예상 비용 확인
140
+ - 등록된 소스 목록
141
+ - 수동 빌드 실행
142
+
143
+ ### 배포
144
+
145
+ ```bash
146
+ # GitHub Pages (기본)
147
+ bunx kiwimu deploy
148
+
149
+ # Vercel
150
+ bunx kiwimu deploy --target vercel
151
+ ```
152
+
153
+ ## Commands
154
+
155
+ | 명령 | 설명 |
156
+ |------|------|
157
+ | `kiwimu init [name]` | 새 위키 프로젝트 생성 (interactive CLI) |
158
+ | `kiwimu add <source>` | URL 또는 파일 추가 (LLM 분석 + 링크 생성) |
159
+ | `kiwimu build` | 정적 위키 사이트 빌드 |
160
+ | `kiwimu serve [-p port] [--host host]` | 웹 서버 실행 (문서 추가/관리 가능) |
161
+ | `kiwimu deploy` | GitHub Pages / Vercel에 배포 |
162
+ | `kiwimu status` | 현재 위키 상태 표시 |
163
+
164
+ ## Supported File Formats
165
+
166
+ | 형식 | 방법 |
167
+ |------|------|
168
+ | URL (HTTP/HTTPS) | Cheerio 웹 크롤링 |
169
+ | PDF | pdf-parse |
170
+ | DOCX | mammoth |
171
+ | PPTX | ZIP/XML 파싱 |
172
+ | DOC / PPT / RTF | macOS textutil |
173
+ | KEY (Keynote) | 텍스트 추출 (제한적) |
174
+
175
+ ## Supported LLM Providers
176
+
177
+ | 프로바이더 | 추천 모델 | 비고 |
178
+ |-----------|----------|------|
179
+ | **Google Gemini** | `gemini-2.0-flash-lite` | [무료 API key](https://aistudio.google.com/) |
180
+ | Azure OpenAI | `gpt-5-nano` | Azure 구독 필요 |
181
+ | OpenAI | `gpt-4o-mini` | API key 필요 |
182
+ | Anthropic | `claude-sonnet-4-20250514` | API key 필요 |
183
+
184
+ ## Architecture
185
+
186
+ ```
187
+ 소스 (URL / PDF / DOCX / PPTX)
188
+
189
+ [ Ingest ] ── Cheerio / pdf-parse / mammoth / jszip
190
+
191
+ [ Phase 1 ] ── LLM: 원본 구조 추출 (📖 원본 페이지)
192
+
193
+ [ Phase 2 ] ── LLM: 개념 추출 (📝 개념 페이지)
194
+
195
+ [ Phase 3 ] ── [[wiki link]] 해석 + 원본↔개념 cross-link
196
+
197
+ [ Build ] ── 정적 HTML 생성 (탭 사이드바, KaTeX, 지식 그래프)
198
+
199
+ [ Deploy ] ── GitHub Pages / Vercel
200
+ ```
201
+
202
+ ```
203
+ project-dir/
204
+ ├── kiwi.toml # 프로젝트 + LLM 설정
205
+ ├── kiwi.db # SQLite (문서, 링크, 사용량)
206
+ ├── uploads/ # 업로드된 파일
207
+ └── _site/ # 빌드 결과
208
+ ├── index.html # 홈 (문서 추가 UI + 사용량 대시보드)
209
+ ├── graph.html # 지식 그래프
210
+ ├── wiki/ # 각 문서 페이지
211
+ ├── static/ # CSS, JS, 로고
212
+ └── search-index.json
213
+ ```
214
+
215
+ ## Tech Stack
216
+
217
+ - **Bun** — 런타임, 패키지 매니저, 빌트인 SQLite
218
+ - **TypeScript** — 타입 안전한 파이프라인
219
+ - **@clack/prompts** — Interactive CLI
220
+ - **Cheerio** — 웹 페이지 파싱
221
+ - **Mammoth** — DOCX 파싱
222
+ - **JSZip** — PPTX 파싱
223
+ - **Marked** — Markdown → HTML
224
+ - **D3.js** — 지식 그래프
225
+ - **KaTeX** — 수학 수식 렌더링
226
+ - **gh-pages** — GitHub Pages 배포
227
+
228
+ ## License
229
+
230
+ MIT
package/package.json ADDED
@@ -0,0 +1,62 @@
1
+ {
2
+ "name": "@open330/kiwimu",
3
+ "version": "0.3.0",
4
+ "description": "Turn textbooks, PDFs, and web content into your own interlinked learning wiki powered by LLM",
5
+ "type": "module",
6
+ "bin": {
7
+ "kiwimu": "./src/index.ts"
8
+ },
9
+ "files": [
10
+ "src/**/*",
11
+ "assets/**/*",
12
+ "README.md",
13
+ "LICENSE"
14
+ ],
15
+ "keywords": [
16
+ "wiki",
17
+ "learning",
18
+ "study",
19
+ "textbook",
20
+ "pdf",
21
+ "llm",
22
+ "gemini",
23
+ "knowledge-graph",
24
+ "education",
25
+ "bun"
26
+ ],
27
+ "author": "jiunbae",
28
+ "license": "MIT",
29
+ "repository": {
30
+ "type": "git",
31
+ "url": "https://github.com/Open330/kiwimu.git"
32
+ },
33
+ "homepage": "https://github.com/Open330/kiwimu",
34
+ "engines": {
35
+ "bun": ">=1.0.0"
36
+ },
37
+ "scripts": {
38
+ "dev": "bun run src/index.ts",
39
+ "test": "bun test"
40
+ },
41
+ "dependencies": {
42
+ "@clack/prompts": "^1.1.0",
43
+ "cheerio": "^1.0.0",
44
+ "commander": "^12.1.0",
45
+ "gh-pages": "^6.3.0",
46
+ "jszip": "^3.10.1",
47
+ "mammoth": "^1.12.0",
48
+ "marked": "^15.0.0",
49
+ "pdf-parse": "1.1.1",
50
+ "smol-toml": "^1.3.1",
51
+ "turndown": "^7.2.0"
52
+ },
53
+ "optionalDependencies": {
54
+ "@anthropic-ai/sdk": "^0.79.0",
55
+ "openai": "^6.31.0"
56
+ },
57
+ "devDependencies": {
58
+ "@types/bun": "latest",
59
+ "@types/pdf-parse": "^1.1.5",
60
+ "@types/turndown": "^5.0.5"
61
+ }
62
+ }
@@ -0,0 +1,128 @@
1
+ import { mkdirSync, rmSync, cpSync, existsSync } from "fs";
2
+ import { join, dirname } from "path";
3
+ import { marked } from "marked";
4
+ import type { KiwiConfig } from "../config";
5
+ import type { Store } from "../store";
6
+ import { buildGraphData } from "../pipeline/graph";
7
+ import { renderPage, renderIndex, renderGraph } from "./templates";
8
+
9
+ // Fix internal wiki links: /wiki/slug → /wiki/slug.html
10
+ function fixWikiLinks(html: string): string {
11
+ return html.replace(/href="\/wiki\/([^"]+?)"/g, (match, slug) => {
12
+ if (slug.endsWith(".html")) return match;
13
+ return `href="/wiki/${slug}.html"`;
14
+ });
15
+ }
16
+
17
+ // Separate external reference links from body content
18
+ function extractExternalRefs(html: string): { body: string; externalRefs: string } {
19
+ const marker = '<h2 id="external-references">External References</h2>';
20
+ const idx = html.indexOf(marker);
21
+ if (idx === -1) return { body: html, externalRefs: "" };
22
+
23
+ const body = html.slice(0, idx);
24
+ const refSection = html.slice(idx + marker.length);
25
+ return { body, externalRefs: refSection };
26
+ }
27
+
28
+ function generateToc(markdown: string): string {
29
+ const headings: Array<{ level: number; text: string; id: string }> = [];
30
+ const headingRegex = /^(#{2,4})\s+(.+)$/gm;
31
+ let match;
32
+ while ((match = headingRegex.exec(markdown)) !== null) {
33
+ const text = match[2].trim();
34
+ if (text === "External References") continue;
35
+ const id = text.toLowerCase().replace(/[^\w\s-]/g, "").replace(/\s+/g, "-");
36
+ headings.push({ level: match[1].length, text, id });
37
+ }
38
+ if (!headings.length) return "";
39
+
40
+ return `<div class="toc"><ul>${headings
41
+ .map((h) => `<li style="margin-left:${(h.level - 2) * 16}px"><a href="#${h.id}">${h.text}</a></li>`)
42
+ .join("")}</ul></div>`;
43
+ }
44
+
45
+ export async function buildSite(store: Store, config: KiwiConfig, projectRoot: string): Promise<number> {
46
+ const outputDir = join(projectRoot, config.build.output_dir);
47
+ const wikiDir = join(outputDir, "wiki");
48
+ const staticDir = join(outputDir, "static");
49
+
50
+ if (existsSync(outputDir)) rmSync(outputDir, { recursive: true });
51
+ mkdirSync(wikiDir, { recursive: true });
52
+ mkdirSync(staticDir, { recursive: true });
53
+
54
+ const assetsDir = join(dirname(import.meta.path), "static");
55
+ if (existsSync(assetsDir)) {
56
+ cpSync(assetsDir, staticDir, { recursive: true });
57
+ }
58
+
59
+ // Copy logo
60
+ const logoSrc = join(projectRoot, "..", "assets", "logos", "logo_2_minimalist_icon_transparent.png");
61
+ const logoSrc2 = join(projectRoot, "assets", "logos", "logo_2_minimalist_icon_transparent.png");
62
+ const logoFile = existsSync(logoSrc) ? logoSrc : existsSync(logoSrc2) ? logoSrc2 : null;
63
+ if (logoFile) {
64
+ cpSync(logoFile, join(staticDir, "logo.png"));
65
+ }
66
+
67
+ const pages = store.listPages();
68
+ const sourcePages = store.listSourcePages();
69
+ const conceptPages = store.listConceptPages();
70
+ const wikiName = config.project.name;
71
+
72
+ for (const page of pages) {
73
+ let htmlContent = await marked(page.content);
74
+ htmlContent = fixWikiLinks(htmlContent);
75
+
76
+ const { body, externalRefs } = extractExternalRefs(htmlContent);
77
+ const toc = generateToc(page.content);
78
+ const backlinks = store.getBacklinks(page.id).map((bl) => ({
79
+ slug: bl.slug,
80
+ title: bl.title,
81
+ pageType: bl.page_type,
82
+ }));
83
+
84
+ const html = renderPage({
85
+ wikiName,
86
+ pageTitle: page.title,
87
+ pageSlug: page.slug,
88
+ pageType: page.page_type,
89
+ content: body,
90
+ externalRefs,
91
+ toc,
92
+ backlinks,
93
+ sourcePages: sourcePages.map((p) => ({ slug: p.slug, title: p.title })),
94
+ conceptPages: conceptPages.map((p) => ({ slug: p.slug, title: p.title })),
95
+ });
96
+
97
+ await Bun.write(join(wikiDir, `${page.slug}.html`), html);
98
+ }
99
+
100
+ const indexHtml = renderIndex({
101
+ wikiName,
102
+ sourcePages: sourcePages.map((p) => ({ slug: p.slug, title: p.title })),
103
+ conceptPages: conceptPages.map((p) => ({ slug: p.slug, title: p.title })),
104
+ sourceCount: store.listSources().length,
105
+ });
106
+ await Bun.write(join(outputDir, "index.html"), indexHtml);
107
+
108
+ const graphData = buildGraphData(store);
109
+ await Bun.write(join(outputDir, "graph-data.json"), JSON.stringify(graphData));
110
+ await Bun.write(
111
+ join(outputDir, "graph.html"),
112
+ renderGraph({
113
+ wikiName,
114
+ sourcePages: sourcePages.map((p) => ({ slug: p.slug, title: p.title })),
115
+ conceptPages: conceptPages.map((p) => ({ slug: p.slug, title: p.title })),
116
+ })
117
+ );
118
+
119
+ const searchData = pages.map((p) => ({
120
+ slug: p.slug,
121
+ title: p.title,
122
+ preview: p.content.slice(0, 200),
123
+ type: p.page_type,
124
+ }));
125
+ await Bun.write(join(outputDir, "search-index.json"), JSON.stringify(searchData));
126
+
127
+ return pages.length;
128
+ }
@@ -0,0 +1,114 @@
1
+ // Knowledge graph visualization using D3.js force-directed layout
2
+ document.addEventListener("DOMContentLoaded", async () => {
3
+ const container = document.getElementById("graph-container");
4
+ if (!container) return;
5
+
6
+ const resp = await fetch("/graph-data.json");
7
+ const data = await resp.json();
8
+
9
+ if (!data.nodes.length) {
10
+ container.innerHTML = '<p style="padding:40px;color:#6c757d;">문서를 추가하면 지식 그래프가 표시됩니다.</p>';
11
+ return;
12
+ }
13
+
14
+ const colors = {
15
+ source: "#2196f3",
16
+ sourceHover: "#1565c0",
17
+ concept: "#4caf50",
18
+ conceptHover: "#2e7d32",
19
+ };
20
+
21
+ const width = container.clientWidth;
22
+ const height = container.clientHeight;
23
+
24
+ const svg = d3.select(container)
25
+ .append("svg")
26
+ .attr("viewBox", [0, 0, width, height]);
27
+
28
+ const g = svg.append("g");
29
+ svg.call(d3.zoom()
30
+ .scaleExtent([0.3, 4])
31
+ .on("zoom", (event) => g.attr("transform", event.transform)));
32
+
33
+ const simulation = d3.forceSimulation(data.nodes)
34
+ .force("link", d3.forceLink(data.links).id(d => d.id).distance(100))
35
+ .force("charge", d3.forceManyBody().strength(-300))
36
+ .force("center", d3.forceCenter(width / 2, height / 2))
37
+ .force("collision", d3.forceCollide().radius(30));
38
+
39
+ const link = g.append("g")
40
+ .selectAll("line")
41
+ .data(data.links)
42
+ .join("line")
43
+ .attr("stroke", "#dee2e6")
44
+ .attr("stroke-width", 1.5)
45
+ .attr("stroke-opacity", 0.6);
46
+
47
+ const node = g.append("g")
48
+ .selectAll("g")
49
+ .data(data.nodes)
50
+ .join("g")
51
+ .style("cursor", "pointer")
52
+ .call(d3.drag()
53
+ .on("start", dragstarted)
54
+ .on("drag", dragged)
55
+ .on("end", dragended));
56
+
57
+ node.append("circle")
58
+ .attr("r", d => Math.max(6, Math.min(20, 4 + d.degree * 2)))
59
+ .attr("fill", d => d.type === "source" ? colors.source : colors.concept)
60
+ .attr("stroke", "#fff")
61
+ .attr("stroke-width", 2);
62
+
63
+ node.append("text")
64
+ .text(d => d.title)
65
+ .attr("dx", d => Math.max(8, 6 + d.degree * 2) + 4)
66
+ .attr("dy", 4)
67
+ .attr("font-size", "12px")
68
+ .attr("fill", "#212529");
69
+
70
+ node.on("click", (event, d) => {
71
+ window.location.href = `/wiki/${d.id}.html`;
72
+ });
73
+
74
+ node.on("mouseenter", function(event, d) {
75
+ const hoverColor = d.type === "source" ? colors.sourceHover : colors.conceptHover;
76
+ const baseColor = d.type === "source" ? colors.source : colors.concept;
77
+ d3.select(this).select("circle").attr("fill", hoverColor);
78
+ link.attr("stroke", l =>
79
+ l.source.id === d.id || l.target.id === d.id ? baseColor : "#dee2e6"
80
+ ).attr("stroke-width", l =>
81
+ l.source.id === d.id || l.target.id === d.id ? 2.5 : 1.5
82
+ );
83
+ }).on("mouseleave", function(event, d) {
84
+ const baseColor = d.type === "source" ? colors.source : colors.concept;
85
+ d3.select(this).select("circle").attr("fill", baseColor);
86
+ link.attr("stroke", "#dee2e6").attr("stroke-width", 1.5);
87
+ });
88
+
89
+ simulation.on("tick", () => {
90
+ link
91
+ .attr("x1", d => d.source.x)
92
+ .attr("y1", d => d.source.y)
93
+ .attr("x2", d => d.target.x)
94
+ .attr("y2", d => d.target.y);
95
+ node.attr("transform", d => `translate(${d.x},${d.y})`);
96
+ });
97
+
98
+ function dragstarted(event) {
99
+ if (!event.active) simulation.alphaTarget(0.3).restart();
100
+ event.subject.fx = event.subject.x;
101
+ event.subject.fy = event.subject.y;
102
+ }
103
+
104
+ function dragged(event) {
105
+ event.subject.fx = event.x;
106
+ event.subject.fy = event.y;
107
+ }
108
+
109
+ function dragended(event) {
110
+ if (!event.active) simulation.alphaTarget(0);
111
+ event.subject.fx = null;
112
+ event.subject.fy = null;
113
+ }
114
+ });
@@ -0,0 +1,66 @@
1
+ // Client-side fuzzy search
2
+ document.addEventListener("DOMContentLoaded", async () => {
3
+ const input = document.getElementById("search-input");
4
+ const dropdown = document.getElementById("search-results");
5
+ if (!input || !dropdown) return;
6
+
7
+ let searchData = [];
8
+ try {
9
+ const resp = await fetch("/search-index.json");
10
+ searchData = await resp.json();
11
+ } catch (e) {
12
+ return;
13
+ }
14
+
15
+ function fuzzyMatch(query, text) {
16
+ query = query.toLowerCase();
17
+ text = text.toLowerCase();
18
+ if (text.includes(query)) return true;
19
+ let qi = 0;
20
+ for (let i = 0; i < text.length && qi < query.length; i++) {
21
+ if (text[i] === query[qi]) qi++;
22
+ }
23
+ return qi === query.length;
24
+ }
25
+
26
+ function search(query) {
27
+ if (!query.trim()) return [];
28
+ return searchData
29
+ .filter(item => fuzzyMatch(query, item.title) || fuzzyMatch(query, item.preview))
30
+ .slice(0, 8);
31
+ }
32
+
33
+ input.addEventListener("input", () => {
34
+ const results = search(input.value);
35
+ if (results.length === 0) {
36
+ dropdown.classList.remove("active");
37
+ dropdown.innerHTML = "";
38
+ return;
39
+ }
40
+ dropdown.innerHTML = results.map(r =>
41
+ `<a href="/wiki/${r.slug}.html">
42
+ <strong>${r.title}</strong>
43
+ <div style="font-size:12px;color:#6c757d;margin-top:2px;">${r.preview.slice(0, 80)}...</div>
44
+ </a>`
45
+ ).join("");
46
+ dropdown.classList.add("active");
47
+ });
48
+
49
+ input.addEventListener("blur", () => {
50
+ setTimeout(() => dropdown.classList.remove("active"), 200);
51
+ });
52
+
53
+ input.addEventListener("focus", () => {
54
+ if (input.value.trim() && dropdown.innerHTML) {
55
+ dropdown.classList.add("active");
56
+ }
57
+ });
58
+
59
+ // Keyboard navigation
60
+ input.addEventListener("keydown", (e) => {
61
+ if (e.key === "Escape") {
62
+ dropdown.classList.remove("active");
63
+ input.blur();
64
+ }
65
+ });
66
+ });