rushchatbot 1.6.7

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.
Files changed (51) hide show
  1. package/INTEGRATION.md +559 -0
  2. package/index.html +13 -0
  3. package/package/INTEGRATION.md +717 -0
  4. package/package/README.md +717 -0
  5. package/package/package-lock.json +3221 -0
  6. package/package/package.json +101 -0
  7. package/package/src/cli/index.ts +94 -0
  8. package/package/src/client/ChatWidget.tsx +163 -0
  9. package/package/src/client.ts +2 -0
  10. package/package/src/core/RushChatbot.ts +192 -0
  11. package/package/src/index.ts +5 -0
  12. package/package/src/server/guardrails.ts +107 -0
  13. package/package/src/server/index.ts +210 -0
  14. package/package/src/server/matcher.ts +140 -0
  15. package/package/src/shared/types.ts +58 -0
  16. package/package/src/shims-vue.d.ts +5 -0
  17. package/package/src/vanilla/index.ts +302 -0
  18. package/package/src/vanilla.ts +3 -0
  19. package/package/src/vue/ChatWidget.vue +198 -0
  20. package/package/src/vue.ts +3 -0
  21. package/package/src/vue2/ChatWidget.vue +204 -0
  22. package/package/src/vue2.ts +3 -0
  23. package/package/tsconfig.json +19 -0
  24. package/package/vite.config.ts +86 -0
  25. package/package.json +35 -0
  26. package/public/favicon.svg +1 -0
  27. package/public/icons.svg +24 -0
  28. package/server/data/analytics.json +795 -0
  29. package/server/data/chatbot.config.json +26 -0
  30. package/server/data/questions.json +238 -0
  31. package/server/data/questions.tl.json +182 -0
  32. package/server/index.ts +11 -0
  33. package/server/lib/guardrails.ts +107 -0
  34. package/server/lib/matcher.ts +140 -0
  35. package/server/routes/chat.ts +180 -0
  36. package/server/tsconfig.json +11 -0
  37. package/src/App.css +184 -0
  38. package/src/App.tsx +135 -0
  39. package/src/assets/hero.png +0 -0
  40. package/src/assets/react.svg +1 -0
  41. package/src/assets/vite.svg +1 -0
  42. package/src/components/ChatWidget.tsx +417 -0
  43. package/src/components/QuestionTree.tsx +57 -0
  44. package/src/hooks/useChatData.ts +49 -0
  45. package/src/index.css +111 -0
  46. package/src/main.tsx +10 -0
  47. package/src/types/index.ts +40 -0
  48. package/tsconfig.app.json +26 -0
  49. package/tsconfig.json +7 -0
  50. package/tsconfig.node.json +23 -0
  51. package/vite.config.ts +7 -0
@@ -0,0 +1,140 @@
1
+ import Fuse from 'fuse.js'
2
+
3
+ export interface Question {
4
+ id: string
5
+ question: string
6
+ answer: string
7
+ subquestions: Question[]
8
+ }
9
+
10
+ // Common stop words to ignore during keyword extraction
11
+ const STOP_WORDS = new Set([
12
+ 'a', 'an', 'the', 'is', 'are', 'was', 'were', 'be', 'been', 'being',
13
+ 'have', 'has', 'had', 'do', 'does', 'did', 'will', 'would', 'could',
14
+ 'should', 'may', 'might', 'shall', 'can', 'need', 'dare', 'ought',
15
+ 'i', 'me', 'my', 'we', 'our', 'you', 'your', 'he', 'she', 'it', 'they',
16
+ 'what', 'where', 'when', 'who', 'how', 'why', 'which',
17
+ 'in', 'on', 'at', 'to', 'for', 'of', 'with', 'about', 'by', 'from',
18
+ 'and', 'or', 'but', 'if', 'so', 'yet', 'nor',
19
+ 'this', 'that', 'these', 'those', 'there', 'here',
20
+ 'tell', 'give', 'show', 'know', 'want', 'like', 'get', 'find', 'look'
21
+ ])
22
+
23
+ // Synonym map — only domain-specific terms, not generic words
24
+ const SYNONYMS: Record<string, string[]> = {
25
+ website: ['site', 'web', 'url', 'online', 'portal', 'link'],
26
+ email: ['mail', 'e-mail'],
27
+ address: ['location', 'situated'],
28
+ fee: ['cost', 'price', 'charge', 'dues', 'rate', 'much'],
29
+ membership: ['member', 'join', 'enroll', 'apply'],
30
+ contact: ['reach', 'call', 'phone', 'inquire'],
31
+ benefit: ['advantage', 'perk', 'privilege'],
32
+ program: ['course', 'seminar', 'workshop', 'training'],
33
+ academy: ['school', 'learning', 'education'],
34
+ award: ['recognition', 'prize', 'honor', 'trophy'],
35
+ event: ['conference', 'summit', 'forum', 'gathering'],
36
+ publication: ['journal', 'digest', 'magazine'],
37
+ mission: ['goal', 'purpose', 'objective'],
38
+ founded: ['established', 'started', 'created', 'history', 'origin'],
39
+ hours: ['schedule', 'open', 'available'],
40
+ nominate: ['nomination', 'recommend', 'propose'],
41
+ contribute: ['write', 'author', 'publish'],
42
+ }
43
+
44
+ function extractKeywords(text: string): string[] {
45
+ return text
46
+ .toLowerCase()
47
+ .replace(/[^a-z0-9\s]/g, ' ')
48
+ .split(/\s+/)
49
+ .filter(w => w.length > 1 && !STOP_WORDS.has(w))
50
+ }
51
+
52
+ function expandWithSynonyms(keywords: string[]): string[] {
53
+ const expanded = new Set(keywords)
54
+ for (const [canonical, synonymList] of Object.entries(SYNONYMS)) {
55
+ for (const kw of keywords) {
56
+ if (synonymList.includes(kw) || kw === canonical) {
57
+ expanded.add(canonical)
58
+ synonymList.forEach(s => expanded.add(s))
59
+ }
60
+ }
61
+ }
62
+ return Array.from(expanded)
63
+ }
64
+
65
+ function keywordScore(rawKeywords: string[], expandedKeywords: string[], question: Question): { score: number; matched: string[] } {
66
+ const target = `${question.question} ${question.answer}`.toLowerCase()
67
+ const targetWords = new Set(target.replace(/[^a-z0-9\s]/g, ' ').split(/\s+/))
68
+
69
+ // Check raw keywords first for direct matches
70
+ const rawMatched = rawKeywords.filter(kw => targetWords.has(kw))
71
+
72
+ // Check expanded keywords but only count them if the canonical term hits
73
+ const expandedMatched = expandedKeywords.filter(kw => targetWords.has(kw))
74
+
75
+ // Deduplicate and use the larger matched set
76
+ const matched = Array.from(new Set([...rawMatched, ...expandedMatched]))
77
+
78
+ // Score based on raw keywords so expansion doesn't inflate the score
79
+ const score = rawMatched.length > 0
80
+ ? rawMatched.length / Math.max(rawKeywords.length, 1)
81
+ : expandedMatched.length > 0 ? 0.3 : 0 // small boost if only synonyms matched
82
+
83
+ return { score, matched }
84
+ }
85
+
86
+ function flattenQuestions(questions: Question[]): Question[] {
87
+ return questions.reduce<Question[]>((acc, q) => {
88
+ acc.push(q)
89
+ if (q.subquestions?.length) acc.push(...flattenQuestions(q.subquestions))
90
+ return acc
91
+ }, [])
92
+ }
93
+
94
+ export interface MatchResult {
95
+ question: Question
96
+ matchedKeywords: string[]
97
+ score: number
98
+ }
99
+
100
+ export function findMatch(
101
+ query: string,
102
+ questions: Question[],
103
+ threshold: number
104
+ ): MatchResult | null {
105
+ const flat = flattenQuestions(questions)
106
+
107
+ const rawKeywords = extractKeywords(query)
108
+ const expandedKeywords = expandWithSynonyms(rawKeywords)
109
+
110
+ const fuse = new Fuse(flat, {
111
+ keys: [
112
+ { name: 'question', weight: 0.7 },
113
+ { name: 'answer', weight: 0.3 }
114
+ ],
115
+ threshold: 0.2,
116
+ includeScore: true,
117
+ minMatchCharLength: 3,
118
+ ignoreLocation: true,
119
+ })
120
+
121
+ const fuseResults = fuse.search(query)
122
+
123
+ const candidates = flat.map(q => {
124
+ const fuseResult = fuseResults.find(r => r.item.id === q.id)
125
+ const fuseScore = fuseResult ? 1 - (fuseResult.score ?? 1) : 0
126
+ const { score: kwScore, matched } = keywordScore(rawKeywords, expandedKeywords, q)
127
+
128
+ // Require at least one keyword match AND a reasonable combined score
129
+ if (kwScore === 0) return { q, combined: 0, matchedKeywords: [] }
130
+
131
+ const combined = fuseScore * 0.4 + kwScore * 0.6
132
+ return { q, combined, matchedKeywords: matched }
133
+ })
134
+
135
+ const best = candidates
136
+ .filter(c => c.combined > 0.3)
137
+ .sort((a, b) => b.combined - a.combined)[0]
138
+
139
+ return best ? { question: best.q, matchedKeywords: best.matchedKeywords, score: best.combined } : null
140
+ }
@@ -0,0 +1,180 @@
1
+ import { Router, Request, Response } from 'express'
2
+ import axios from 'axios'
3
+ import fs from 'fs'
4
+ import path from 'path'
5
+ import { findMatch, MatchResult, Question } from '../lib/matcher'
6
+ import { checkGuardrails, validateInput } from '../lib/guardrails'
7
+
8
+ const router = Router()
9
+
10
+ const CONFIG_PATH = path.join(__dirname, '../data/chatbot.config.json')
11
+ const ANALYTICS_PATH = path.join(__dirname, '../data/analytics.json')
12
+
13
+ type AnalyticsEntry = { sessionId: string; questionId: string; timestamp: string; type: 'click' | 'match' | 'n8n' | 'error' }
14
+
15
+ function getConfig() {
16
+ return JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8'))
17
+ }
18
+
19
+ function getQuestions(lang: 'en' | 'tl' = 'en'): Question[] {
20
+ const file = lang === 'tl' ? 'questions.tl.json' : 'questions.json'
21
+ return JSON.parse(fs.readFileSync(path.join(__dirname, `../data/${file}`), 'utf-8'))
22
+ }
23
+
24
+ function getAnalytics(): AnalyticsEntry[] {
25
+ if (!fs.existsSync(ANALYTICS_PATH)) return []
26
+ return JSON.parse(fs.readFileSync(ANALYTICS_PATH, 'utf-8'))
27
+ }
28
+
29
+ function saveAnalytics(entry: AnalyticsEntry) {
30
+ try {
31
+ const analytics = getAnalytics()
32
+ analytics.push(entry)
33
+ fs.writeFileSync(ANALYTICS_PATH, JSON.stringify(analytics, null, 2))
34
+ } catch (e) {
35
+ console.error('[analytics error]', e)
36
+ }
37
+ }
38
+
39
+ function parseN8nResponse(data: unknown): { paragraphs: string[] } | { answer: string } {
40
+ if (Array.isArray(data) && data.length > 0) {
41
+ const first = data[0]
42
+ if (Array.isArray(first?.paragraphs) && first.paragraphs.length > 0)
43
+ return { paragraphs: first.paragraphs.map(String) }
44
+ if (typeof first === 'string') return { answer: first }
45
+ if (first?.output) return { answer: String(first.output) }
46
+ if (first?.text) return { answer: String(first.text) }
47
+ if (first?.answer) return { answer: String(first.answer) }
48
+ if (first?.message) return { answer: String(first.message) }
49
+ }
50
+ if (typeof data === 'object' && data !== null) {
51
+ const obj = data as Record<string, unknown>
52
+ if (Array.isArray(obj.paragraphs)) return { paragraphs: obj.paragraphs.map(String) }
53
+ if (obj.output) return { answer: String(obj.output) }
54
+ if (obj.answer) return { answer: String(obj.answer) }
55
+ if (obj.text) return { answer: String(obj.text) }
56
+ if (obj.message) return { answer: String(obj.message) }
57
+ }
58
+ if (typeof data === 'string') return { answer: data }
59
+ return { answer: JSON.stringify(data) }
60
+ }
61
+
62
+ function getSid(req: Request): string {
63
+ return String(req.body?.sessionId ?? req.headers['x-session-id'] ?? 'unknown')
64
+ }
65
+
66
+ // Pre-question click tracking
67
+ router.post('/click', (req: Request, res: Response) => {
68
+ const { questionId } = req.body
69
+ const sid = getSid(req)
70
+ if (!questionId || typeof questionId !== 'string') {
71
+ return res.status(400).json({ error: 'questionId is required' })
72
+ }
73
+ saveAnalytics({ sessionId: sid, questionId, timestamp: new Date().toISOString(), type: 'click' })
74
+ res.json({ ok: true })
75
+ })
76
+
77
+ // GET /query — forward query param directly to n8n (for browser testing)
78
+ router.get('/query', async (req: Request, res: Response) => {
79
+ const config = getConfig()
80
+ const query = String(req.query.query ?? '').trim()
81
+ const sid = String(req.query.sessionId ?? req.headers['x-session-id'] ?? 'unknown')
82
+
83
+ if (!query) return res.status(400).json({ error: 'query param is required' })
84
+
85
+ try {
86
+ const { webhookUrl, timeoutMs } = config.n8n
87
+ const { data } = await axios.post(
88
+ webhookUrl,
89
+ { query, sessionId: sid },
90
+ { timeout: timeoutMs, headers: { 'Content-Type': 'application/json', 'x-session-id': sid } }
91
+ )
92
+ return res.json({ ...parseN8nResponse(data), source: 'n8n' })
93
+ } catch (err: unknown) {
94
+ const message = err instanceof Error ? err.message : String(err)
95
+ console.error('[query GET error]', message)
96
+ return res.status(500).json({ error: message })
97
+ }
98
+ })
99
+
100
+ router.post('/query', async (req: Request, res: Response) => {
101
+ const sid = getSid(req)
102
+ const config = getConfig()
103
+
104
+ try {
105
+ const { query } = req.body
106
+ if (!query || typeof query !== 'string' || !query.trim()) {
107
+ return res.status(400).json({ error: 'query is required' })
108
+ }
109
+
110
+ // Step 1 — validate input
111
+ const validation = validateInput(query.trim())
112
+ if (!validation.valid) {
113
+ saveAnalytics({ sessionId: sid, questionId: 'invalid_input', timestamp: new Date().toISOString(), type: 'error' })
114
+ return res.json({ answer: validation.response, source: 'validation' })
115
+ }
116
+
117
+ // Step 2 — guardrails
118
+ const guardrail = checkGuardrails(query.trim())
119
+ if (guardrail.flagged) {
120
+ saveAnalytics({ sessionId: sid, questionId: 'guardrail', timestamp: new Date().toISOString(), type: 'error' })
121
+ return res.json({ answer: guardrail.response, source: 'guardrail' })
122
+ }
123
+
124
+ // Step 3 — match EN then TL
125
+ let result: MatchResult | null = findMatch(query.trim(), getQuestions('en'), config.chat.matchThreshold)
126
+ if (!result) result = findMatch(query.trim(), getQuestions('tl'), config.chat.matchThreshold)
127
+
128
+ if (result) {
129
+ saveAnalytics({ sessionId: sid, questionId: result.question.id, timestamp: new Date().toISOString(), type: 'match' })
130
+ return res.json({
131
+ answer: result.question.answer,
132
+ source: 'config',
133
+ matchedQuestion: result.question.question,
134
+ matchedKeywords: result.matchedKeywords,
135
+ score: Math.round(result.score * 100)
136
+ })
137
+ }
138
+
139
+ // Step 4 — n8n fallback
140
+ const { webhookUrl, timeoutMs } = config.n8n
141
+ if (!webhookUrl || webhookUrl.includes('your-n8n.com')) {
142
+ saveAnalytics({ sessionId: sid, questionId: 'n8n_not_configured', timestamp: new Date().toISOString(), type: 'error' })
143
+ return res.json({ answer: config.chat.fallbackMessage, source: 'error' })
144
+ }
145
+
146
+ saveAnalytics({ sessionId: sid, questionId: 'n8n', timestamp: new Date().toISOString(), type: 'n8n' })
147
+ const { data } = await axios.post(
148
+ webhookUrl,
149
+ { query: query.trim(), sessionId: sid },
150
+ { timeout: timeoutMs, headers: { 'Content-Type': 'application/json', 'x-session-id': sid } }
151
+ )
152
+ return res.json({ ...parseN8nResponse(data), source: 'n8n' })
153
+
154
+ } catch (err: unknown) {
155
+ const message = err instanceof Error ? err.message : String(err)
156
+ console.error('[query error]', message)
157
+ saveAnalytics({ sessionId: sid, questionId: 'error', timestamp: new Date().toISOString(), type: 'error' })
158
+ return res.status(500).json({ answer: config.chat.fallbackMessage, source: 'error' })
159
+ }
160
+ })
161
+
162
+ // Get questions tree
163
+ router.get('/questions', (_req: Request, res: Response) => {
164
+ const { chat } = getConfig()
165
+ const lang = chat.language ?? 'en'
166
+ res.json(getQuestions(lang === 'tl' ? 'tl' : 'en'))
167
+ })
168
+
169
+ // Get config — branding + chat only, never expose n8n credentials
170
+ router.get('/config', (_req: Request, res: Response) => {
171
+ const { branding, chat } = getConfig()
172
+ res.json({ branding, chat })
173
+ })
174
+
175
+ // Analytics
176
+ router.get('/analytics', (_req: Request, res: Response) => {
177
+ res.json(getAnalytics())
178
+ })
179
+
180
+ export default router
@@ -0,0 +1,11 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2020",
4
+ "module": "commonjs",
5
+ "rootDir": ".",
6
+ "outDir": "./dist",
7
+ "strict": true,
8
+ "esModuleInterop": true,
9
+ "resolveJsonModule": true
10
+ }
11
+ }
package/src/App.css ADDED
@@ -0,0 +1,184 @@
1
+ .counter {
2
+ font-size: 16px;
3
+ padding: 5px 10px;
4
+ border-radius: 5px;
5
+ color: var(--accent);
6
+ background: var(--accent-bg);
7
+ border: 2px solid transparent;
8
+ transition: border-color 0.3s;
9
+ margin-bottom: 24px;
10
+
11
+ &:hover {
12
+ border-color: var(--accent-border);
13
+ }
14
+ &:focus-visible {
15
+ outline: 2px solid var(--accent);
16
+ outline-offset: 2px;
17
+ }
18
+ }
19
+
20
+ .hero {
21
+ position: relative;
22
+
23
+ .base,
24
+ .framework,
25
+ .vite {
26
+ inset-inline: 0;
27
+ margin: 0 auto;
28
+ }
29
+
30
+ .base {
31
+ width: 170px;
32
+ position: relative;
33
+ z-index: 0;
34
+ }
35
+
36
+ .framework,
37
+ .vite {
38
+ position: absolute;
39
+ }
40
+
41
+ .framework {
42
+ z-index: 1;
43
+ top: 34px;
44
+ height: 28px;
45
+ transform: perspective(2000px) rotateZ(300deg) rotateX(44deg) rotateY(39deg)
46
+ scale(1.4);
47
+ }
48
+
49
+ .vite {
50
+ z-index: 0;
51
+ top: 107px;
52
+ height: 26px;
53
+ width: auto;
54
+ transform: perspective(2000px) rotateZ(300deg) rotateX(40deg) rotateY(39deg)
55
+ scale(0.8);
56
+ }
57
+ }
58
+
59
+ #center {
60
+ display: flex;
61
+ flex-direction: column;
62
+ gap: 25px;
63
+ place-content: center;
64
+ place-items: center;
65
+ flex-grow: 1;
66
+
67
+ @media (max-width: 1024px) {
68
+ padding: 32px 20px 24px;
69
+ gap: 18px;
70
+ }
71
+ }
72
+
73
+ #next-steps {
74
+ display: flex;
75
+ border-top: 1px solid var(--border);
76
+ text-align: left;
77
+
78
+ & > div {
79
+ flex: 1 1 0;
80
+ padding: 32px;
81
+ @media (max-width: 1024px) {
82
+ padding: 24px 20px;
83
+ }
84
+ }
85
+
86
+ .icon {
87
+ margin-bottom: 16px;
88
+ width: 22px;
89
+ height: 22px;
90
+ }
91
+
92
+ @media (max-width: 1024px) {
93
+ flex-direction: column;
94
+ text-align: center;
95
+ }
96
+ }
97
+
98
+ #docs {
99
+ border-right: 1px solid var(--border);
100
+
101
+ @media (max-width: 1024px) {
102
+ border-right: none;
103
+ border-bottom: 1px solid var(--border);
104
+ }
105
+ }
106
+
107
+ #next-steps ul {
108
+ list-style: none;
109
+ padding: 0;
110
+ display: flex;
111
+ gap: 8px;
112
+ margin: 32px 0 0;
113
+
114
+ .logo {
115
+ height: 18px;
116
+ }
117
+
118
+ a {
119
+ color: var(--text-h);
120
+ font-size: 16px;
121
+ border-radius: 6px;
122
+ background: var(--social-bg);
123
+ display: flex;
124
+ padding: 6px 12px;
125
+ align-items: center;
126
+ gap: 8px;
127
+ text-decoration: none;
128
+ transition: box-shadow 0.3s;
129
+
130
+ &:hover {
131
+ box-shadow: var(--shadow);
132
+ }
133
+ .button-icon {
134
+ height: 18px;
135
+ width: 18px;
136
+ }
137
+ }
138
+
139
+ @media (max-width: 1024px) {
140
+ margin-top: 20px;
141
+ flex-wrap: wrap;
142
+ justify-content: center;
143
+
144
+ li {
145
+ flex: 1 1 calc(50% - 8px);
146
+ }
147
+
148
+ a {
149
+ width: 100%;
150
+ justify-content: center;
151
+ box-sizing: border-box;
152
+ }
153
+ }
154
+ }
155
+
156
+ #spacer {
157
+ height: 88px;
158
+ border-top: 1px solid var(--border);
159
+ @media (max-width: 1024px) {
160
+ height: 48px;
161
+ }
162
+ }
163
+
164
+ .ticks {
165
+ position: relative;
166
+ width: 100%;
167
+
168
+ &::before,
169
+ &::after {
170
+ content: '';
171
+ position: absolute;
172
+ top: -4.5px;
173
+ border: 5px solid transparent;
174
+ }
175
+
176
+ &::before {
177
+ left: 0;
178
+ border-left-color: var(--border);
179
+ }
180
+ &::after {
181
+ right: 0;
182
+ border-right-color: var(--border);
183
+ }
184
+ }
package/src/App.tsx ADDED
@@ -0,0 +1,135 @@
1
+ import { useState, useRef, useEffect } from 'react'
2
+ import ChatWidget from './components/ChatWidget'
3
+
4
+ export default function App() {
5
+ const [open, setOpen] = useState(false)
6
+ const [pos, setPos] = useState({ x: window.innerWidth - 80, y: window.innerHeight - 80 })
7
+ const dragging = useRef(false)
8
+ const dragOffset = useRef({ x: 0, y: 0 })
9
+ const hasDragged = useRef(false)
10
+ const btnRef = useRef<HTMLButtonElement>(null)
11
+
12
+ const dragStart = useRef({ x: 0, y: 0 })
13
+
14
+ useEffect(() => {
15
+ function onMouseMove(e: MouseEvent) {
16
+ if (!dragging.current) return
17
+ const dx = e.clientX - dragStart.current.x
18
+ const dy = e.clientY - dragStart.current.y
19
+ if (!hasDragged.current && Math.sqrt(dx * dx + dy * dy) > 5) hasDragged.current = true
20
+ setPos({
21
+ x: Math.min(Math.max(e.clientX - dragOffset.current.x, 28), window.innerWidth - 28),
22
+ y: Math.min(Math.max(e.clientY - dragOffset.current.y, 28), window.innerHeight - 28),
23
+ })
24
+ }
25
+ function onMouseUp() { dragging.current = false }
26
+ function onTouchMove(e: TouchEvent) {
27
+ if (!dragging.current) return
28
+ const t = e.touches[0]
29
+ const dx = t.clientX - dragStart.current.x
30
+ const dy = t.clientY - dragStart.current.y
31
+ if (!hasDragged.current && Math.sqrt(dx * dx + dy * dy) > 5) hasDragged.current = true
32
+ setPos({
33
+ x: Math.min(Math.max(t.clientX - dragOffset.current.x, 28), window.innerWidth - 28),
34
+ y: Math.min(Math.max(t.clientY - dragOffset.current.y, 28), window.innerHeight - 28),
35
+ })
36
+ }
37
+ function onTouchEnd() { dragging.current = false }
38
+
39
+ window.addEventListener('mousemove', onMouseMove)
40
+ window.addEventListener('mouseup', onMouseUp)
41
+ window.addEventListener('touchmove', onTouchMove, { passive: true })
42
+ window.addEventListener('touchend', onTouchEnd)
43
+ return () => {
44
+ window.removeEventListener('mousemove', onMouseMove)
45
+ window.removeEventListener('mouseup', onMouseUp)
46
+ window.removeEventListener('touchmove', onTouchMove)
47
+ window.removeEventListener('touchend', onTouchEnd)
48
+ }
49
+ }, [])
50
+
51
+ function onMouseDown(e: React.MouseEvent) {
52
+ hasDragged.current = false
53
+ dragging.current = true
54
+ dragStart.current = { x: e.clientX, y: e.clientY }
55
+ dragOffset.current = { x: e.clientX - pos.x, y: e.clientY - pos.y }
56
+ }
57
+
58
+ function onTouchStart(e: React.TouchEvent) {
59
+ hasDragged.current = false
60
+ dragging.current = true
61
+ const t = e.touches[0]
62
+ dragStart.current = { x: t.clientX, y: t.clientY }
63
+ dragOffset.current = { x: t.clientX - pos.x, y: t.clientY - pos.y }
64
+ }
65
+
66
+ function handleClick() {
67
+ if (!hasDragged.current) setOpen(o => !o)
68
+ }
69
+
70
+ // Chat box appears above the button, clamped to viewport
71
+ const boxWidth = 380
72
+ const boxHeight = 580
73
+ const boxLeft = Math.min(Math.max(pos.x - boxWidth / 2, 8), window.innerWidth - boxWidth - 8)
74
+ const boxTop = Math.max(pos.y - boxHeight - 16, 8)
75
+
76
+ return (
77
+ <div style={{ minHeight: '100vh', background: '#f9fafb' }}>
78
+ {open && (
79
+ <div style={{
80
+ position: 'fixed',
81
+ left: boxLeft,
82
+ top: boxTop,
83
+ zIndex: 1000,
84
+ animation: 'chatSlideUp 0.2s ease-out',
85
+ }}>
86
+ <style>{`
87
+ @keyframes chatSlideUp {
88
+ from { opacity: 0; transform: translateY(16px); }
89
+ to { opacity: 1; transform: translateY(0); }
90
+ }
91
+ `}</style>
92
+ <ChatWidget onClose={() => setOpen(false)} />
93
+ </div>
94
+ )}
95
+
96
+ <button
97
+ ref={btnRef}
98
+ onMouseDown={onMouseDown}
99
+ onTouchStart={onTouchStart}
100
+ onClick={handleClick}
101
+ style={{
102
+ position: 'fixed',
103
+ left: pos.x - 28,
104
+ top: pos.y - 28,
105
+ zIndex: 1001,
106
+ width: 56,
107
+ height: 56,
108
+ borderRadius: '50%',
109
+ border: 'none',
110
+ background: '#4F46E5',
111
+ color: '#fff',
112
+ cursor: 'grab',
113
+ boxShadow: '0 4px 16px rgba(79,70,229,0.4)',
114
+ display: 'flex',
115
+ alignItems: 'center',
116
+ justifyContent: 'center',
117
+ fontSize: 24,
118
+ userSelect: 'none',
119
+ }}
120
+ aria-label={open ? 'Close chat' : 'Open chat'}
121
+ >
122
+ {open ? (
123
+ <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
124
+ <line x1="18" y1="6" x2="6" y2="18" />
125
+ <line x1="6" y1="6" x2="18" y2="18" />
126
+ </svg>
127
+ ) : (
128
+ <svg width="26" height="26" viewBox="0 0 24 24" fill="currentColor">
129
+ <path d="M20 2H4C2.9 2 2 2.9 2 4v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 12H6l-2 2V4h16v10z"/>
130
+ </svg>
131
+ )}
132
+ </button>
133
+ </div>
134
+ )
135
+ }
Binary file
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>