call-control-sdk 1.0.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/README.md ADDED
@@ -0,0 +1,156 @@
1
+ # React Call Control SDK
2
+
3
+ A React-based call control SDK with Material-UI components, providing a draggable control panel for call management.
4
+
5
+ ## Features
6
+
7
+ - 🎯 **Complete Call Control**: Hold, Mute, Status management, and End Call functionality
8
+ - 🖱️ **Draggable Interface**: Movable control panel that persists position
9
+ - 💾 **State Persistence**: All control states saved in localStorage
10
+ - ⏱️ **Live Call Timer**: Real-time call duration tracking
11
+ - 🎨 **Material-UI Design**: Beautiful, responsive design with MUI components
12
+ - 📱 **Touch Support**: Works on both desktop and mobile devices
13
+ - 🔧 **TypeScript Support**: Full type safety and IntelliSense
14
+ - 🎪 **Singleton Pattern**: Shared state management across components
15
+
16
+ ## Installation
17
+
18
+ ```bash
19
+ npm install react-call-control-sdk
20
+ ```
21
+
22
+ ## Peer Dependencies
23
+
24
+ Make sure you have these installed in your host application:
25
+
26
+ ```bash
27
+ npm install react react-dom @mui/material @mui/icons-material @emotion/react @emotion/styled
28
+ ```
29
+
30
+ ## Quick Start
31
+
32
+ ### 1. Initialize the SDK
33
+
34
+ ```typescript
35
+ import { initCallSDK } from 'react-call-control-sdk';
36
+
37
+ // Initialize at the top level of your app
38
+ initCallSDK('YOUR_API_KEY');
39
+ ```
40
+
41
+ ### 2. Use the CallControlPanel
42
+
43
+ ```typescript
44
+ import React from 'react';
45
+ import { CallControlPanel } from 'react-call-control-sdk';
46
+
47
+ function App() {
48
+ const handleDataChange = ({ mobileNumber, callReferenceId, agentLoginId }) => {
49
+ console.log('Call data updated:', { mobileNumber, callReferenceId, agentLoginId });
50
+ };
51
+
52
+ return (
53
+ <div>
54
+ <h1>My Application</h1>
55
+ <CallControlPanel onDataChange={handleDataChange} />
56
+ </div>
57
+ );
58
+ }
59
+ ```
60
+
61
+ ### 3. Update Call Data (Optional)
62
+
63
+ ```typescript
64
+ import { updateCallData } from 'react-call-control-sdk';
65
+
66
+ // Update call information
67
+ updateCallData({
68
+ mobileNumber: '+1-555-123-4567',
69
+ callReferenceId: 'CALL-2024-001',
70
+ agentLoginId: 'AGENT-123'
71
+ });
72
+ ```
73
+
74
+ ## API Reference
75
+
76
+ ### `initCallSDK(sdkApiKey: string)`
77
+
78
+ Initializes the SDK with an API key. Must be called before using any components.
79
+
80
+ **Parameters:**
81
+ - `sdkApiKey` (string): Your API key for SDK authentication
82
+
83
+ **Throws:** Error if API key is missing or invalid
84
+
85
+ ### `CallControlPanel`
86
+
87
+ The main draggable control panel component.
88
+
89
+ **Props:**
90
+ - `onDataChange?` (function): Callback fired when call data changes
91
+ - Parameters: `{ mobileNumber: string, callReferenceId: string, agentLoginId: string }`
92
+
93
+ ### `updateCallData(data: Partial<CallData>)`
94
+
95
+ Updates the call data that will be passed to the `onDataChange` callback.
96
+
97
+ **Parameters:**
98
+ - `data.mobileNumber?` (string): Mobile phone number
99
+ - `data.callReferenceId?` (string): Call reference ID
100
+ - `data.agentLoginId?` (string): Agent login ID
101
+
102
+ ## Control Features
103
+
104
+ ### Status Management
105
+ - **Idle**: Default state, no active call
106
+ - **Ready**: Agent is ready to take calls
107
+ - **Break**: Agent is on break
108
+
109
+ ### Call Controls
110
+ - **Hold/Resume**: Toggle call hold state
111
+ - **Mute/Unmute**: Toggle microphone
112
+ - **End Call**: Terminate active call
113
+ - **More Menu**: Access status change options
114
+
115
+ ### Persistent State
116
+ All control states are automatically saved to localStorage:
117
+ - Hold/mute states
118
+ - Agent status
119
+ - Panel position
120
+ - Call timer state
121
+
122
+ ## Styling & Theming
123
+
124
+ The SDK uses Material-UI components and respects your app's MUI theme. Ensure you wrap your app with a `ThemeProvider`:
125
+
126
+ ```typescript
127
+ import { ThemeProvider, createTheme } from '@mui/material/styles';
128
+ import CssBaseline from '@mui/material/CssBaseline';
129
+
130
+ const theme = createTheme({
131
+ palette: {
132
+ mode: 'light',
133
+ primary: { main: '#1976d2' }
134
+ }
135
+ });
136
+
137
+ function App() {
138
+ return (
139
+ <ThemeProvider theme={theme}>
140
+ <CssBaseline />
141
+ {/* Your app content */}
142
+ </ThemeProvider>
143
+ );
144
+ }
145
+ ```
146
+
147
+ ## Browser Support
148
+
149
+ - Chrome 60+
150
+ - Firefox 60+
151
+ - Safari 12+
152
+ - Edge 79+
153
+
154
+ ## License
155
+
156
+ MIT © [Your Name]
@@ -0,0 +1,23 @@
1
+ import js from '@eslint/js'
2
+ import globals from 'globals'
3
+ import reactHooks from 'eslint-plugin-react-hooks'
4
+ import reactRefresh from 'eslint-plugin-react-refresh'
5
+ import tseslint from 'typescript-eslint'
6
+ import { globalIgnores } from 'eslint/config'
7
+
8
+ export default tseslint.config([
9
+ globalIgnores(['dist']),
10
+ {
11
+ files: ['**/*.{ts,tsx}'],
12
+ extends: [
13
+ js.configs.recommended,
14
+ tseslint.configs.recommended,
15
+ reactHooks.configs['recommended-latest'],
16
+ reactRefresh.configs.vite,
17
+ ],
18
+ languageOptions: {
19
+ ecmaVersion: 2020,
20
+ globals: globals.browser,
21
+ },
22
+ },
23
+ ])
package/index.html ADDED
@@ -0,0 +1,13 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <link rel="icon" type="image/svg+xml" href="/vite.svg" />
6
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7
+ <title>Call Control SDK</title>
8
+ </head>
9
+ <body>
10
+ <div id="root"></div>
11
+ <script type="module" src="/src/main.tsx"></script>
12
+ </body>
13
+ </html>
package/package.json ADDED
@@ -0,0 +1,40 @@
1
+ {
2
+ "name": "call-control-sdk",
3
+ "description": "Call Control SDK",
4
+ "version": "1.0.0",
5
+ "type": "module",
6
+ "author": "Achala",
7
+ "license": "MIT",
8
+ "scripts": {
9
+ "dev": "vite",
10
+ "start": "vite",
11
+ "build": "tsc -b && vite build",
12
+ "build:lib": "tsc --project tsconfig.lib.json && vite build --mode lib",
13
+ "lint": "eslint .",
14
+ "format": "prettier --write .",
15
+ "preview": "vite preview",
16
+ "prepublishOnly": "npm run build:lib"
17
+ },
18
+ "dependencies": {
19
+ "@emotion/react": "^11.14.0",
20
+ "@emotion/styled": "^11.14.1",
21
+ "@mui/icons-material": "^7.3.1",
22
+ "@mui/material": "^7.3.1",
23
+ "react": "^19.1.1",
24
+ "react-dom": "^19.1.1"
25
+ },
26
+ "devDependencies": {
27
+ "@eslint/js": "^9.33.0",
28
+ "@types/node": "^24.2.1",
29
+ "@types/react": "^19.1.10",
30
+ "@types/react-dom": "^19.1.7",
31
+ "@vitejs/plugin-react-swc": "^4.0.0",
32
+ "eslint": "^9.33.0",
33
+ "eslint-plugin-react-hooks": "^5.2.0",
34
+ "eslint-plugin-react-refresh": "^0.4.20",
35
+ "globals": "^16.3.0",
36
+ "typescript": "~5.8.3",
37
+ "typescript-eslint": "^8.39.1",
38
+ "vite": "^7.1.2"
39
+ }
40
+ }
@@ -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="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
package/src/App.tsx ADDED
@@ -0,0 +1,47 @@
1
+ import { useEffect } from "react";
2
+ import { Box } from "@mui/material";
3
+ import { CallControlPanel, initCallSDK, updateCallData } from "./lib";
4
+
5
+ function App() {
6
+ useEffect(() => {
7
+ // Initialize the SDK with a test API key
8
+ try {
9
+ initCallSDK("test-api-key-12345");
10
+ console.log("SDK initialized successfully");
11
+
12
+ // Simulate some call data
13
+ updateCallData({
14
+ mobileNumber: "+1-234-567-8900",
15
+ callReferenceId: "CALL-REF-001",
16
+ agentLoginId: "AGENT-123",
17
+ });
18
+ } catch (error) {
19
+ console.error("SDK initialization failed:", error);
20
+ }
21
+ }, []);
22
+
23
+ const handleDataChange = (data: {
24
+ mobileNumber: string;
25
+ callReferenceId: string;
26
+ agentLoginId: string;
27
+ }) => {
28
+ console.log("Call data changed:", data);
29
+ };
30
+
31
+ return (
32
+ <Box>
33
+ <h1
34
+ style={{
35
+ color: "#1976d2",
36
+ marginBottom: "20px",
37
+ }}
38
+ >
39
+ Call Control SDK Demo
40
+ </h1>
41
+
42
+ <CallControlPanel onDataChange={handleDataChange} />
43
+ </Box>
44
+ );
45
+ }
46
+
47
+ export default App;
package/src/index.css ADDED
@@ -0,0 +1,23 @@
1
+ :root {
2
+ font-family: system-ui, Avenir, Helvetica, Arial, sans-serif;
3
+ line-height: 1.5;
4
+ font-weight: 400;
5
+ width: 100%;
6
+ color-scheme: light dark;
7
+ color: rgba(255, 255, 255, 0.87);
8
+ background-color: #f3f3f3;
9
+
10
+ font-synthesis: none;
11
+ text-rendering: optimizeLegibility;
12
+ -webkit-font-smoothing: antialiased;
13
+ -moz-osx-font-smoothing: grayscale;
14
+ }
15
+
16
+
17
+ body {
18
+ margin: 0;
19
+ display: flex;
20
+ width: 100%;
21
+ min-height: 100vh;
22
+ }
23
+
@@ -0,0 +1,422 @@
1
+ import React, { useEffect, useState, useCallback } from "react";
2
+ import {
3
+ Paper,
4
+ IconButton,
5
+ Typography,
6
+ Menu,
7
+ MenuItem,
8
+ Box,
9
+ Tooltip,
10
+ Fade,
11
+ useTheme,
12
+ Button,
13
+ } from "@mui/material";
14
+ import {
15
+ PauseCircle,
16
+ PlayCircle,
17
+ Mic,
18
+ MicOff,
19
+ MoreVert,
20
+ CallEnd,
21
+ KeyboardArrowDown,
22
+ Cached,
23
+ FreeBreakfast,
24
+ AirlineSeatIndividualSuite,
25
+ TransferWithinAStation,
26
+ Groups,
27
+ Phone,
28
+ DragIndicator,
29
+ SpatialAudioOff,
30
+ } from "@mui/icons-material";
31
+ import { useSDKState } from "../hooks/useSDKState";
32
+ import { useDraggable } from "../hooks/useDraggable";
33
+ import { sdkStateManager } from "../sdk-state";
34
+ import type { CallControlPanelProps, CallStatus } from "../types";
35
+
36
+ export function CallControlPanel({ onDataChange }: CallControlPanelProps) {
37
+ const theme = useTheme();
38
+ const state = useSDKState();
39
+ const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
40
+ const [moreOptionsAnchorEl, setMoreOptionsAnchorEl] =
41
+ useState<null | HTMLElement>(null);
42
+ const [callDuration, setCallDuration] = useState(0);
43
+
44
+ const { position, isDragging, dragRef, handleMouseDown, handleTouchStart } =
45
+ useDraggable(state.position, (newPosition) =>
46
+ sdkStateManager.setPosition(newPosition)
47
+ );
48
+
49
+ // Call duration timer
50
+ useEffect(() => {
51
+ let interval: NodeJS.Timeout;
52
+
53
+ if (state.callStartTime) {
54
+ interval = setInterval(() => {
55
+ const elapsed = Math.floor((Date.now() - state.callStartTime!) / 1000);
56
+ setCallDuration(elapsed);
57
+ }, 1000);
58
+ } else {
59
+ setCallDuration(0);
60
+ }
61
+
62
+ return () => {
63
+ if (interval) clearInterval(interval);
64
+ };
65
+ }, [state.callStartTime]);
66
+
67
+ // Notify parent of data changes
68
+ useEffect(() => {
69
+ if (onDataChange) {
70
+ onDataChange(state.callData);
71
+ }
72
+ }, [state.callData, onDataChange]);
73
+
74
+ const formatDuration = useCallback((seconds: number): string => {
75
+ const mins = Math.floor(seconds / 60);
76
+ const secs = seconds % 60;
77
+ return `${mins.toString().padStart(2, "0")}:${secs
78
+ .toString()
79
+ .padStart(2, "0")}`;
80
+ }, []);
81
+
82
+ const getStatusColor = useCallback((status: CallStatus) => {
83
+ switch (status) {
84
+ case "ready":
85
+ return "success";
86
+ case "break":
87
+ return "warning";
88
+ case "idle":
89
+ return "default";
90
+ default:
91
+ return "default";
92
+ }
93
+ }, []);
94
+
95
+ const handleHoldToggle = () => {
96
+ sdkStateManager.setHolding(!state.isHolding);
97
+ };
98
+
99
+ const handleMuteToggle = () => {
100
+ sdkStateManager.setMuted(!state.isMuted);
101
+ };
102
+
103
+ const handleStatusChange = (newStatus: CallStatus) => {
104
+ sdkStateManager.setStatus(newStatus);
105
+ setAnchorEl(null);
106
+ };
107
+
108
+ const handleEndCall = () => {
109
+ sdkStateManager.endCall();
110
+ };
111
+
112
+ const handleStartCall = () => {
113
+ sdkStateManager.startCall();
114
+ };
115
+
116
+ const handleMoreClick = (event: React.MouseEvent<HTMLElement>) => {
117
+ setAnchorEl(event.currentTarget);
118
+ };
119
+ const handleMoreOptions = (event: React.MouseEvent<HTMLElement>) => {
120
+ setMoreOptionsAnchorEl(event.currentTarget);
121
+ };
122
+ const handleMoreClose = () => {
123
+ setAnchorEl(null);
124
+ };
125
+
126
+ const handleMoreOptionsClose = () => {
127
+ setMoreOptionsAnchorEl(null);
128
+ };
129
+
130
+ // if (!state.isInitialized) {
131
+ // return (
132
+ // <Paper
133
+ // elevation={2}
134
+ // sx={{
135
+ // position: "fixed",
136
+ // top: "50%",
137
+ // left: "50%",
138
+ // transform: "translate(-50%, -50%)",
139
+ // p: 2,
140
+ // borderRadius: 2,
141
+ // bgcolor: "error.light",
142
+ // color: "error.contrastText",
143
+ // zIndex: 9999,
144
+ // }}
145
+ // >
146
+ // <Typography variant="h6" gutterBottom>
147
+ // SDK Error
148
+ // </Typography>
149
+ // <Typography variant="body2">
150
+ // Call SDK not initialized. Please call initCallSDK() first.
151
+ // </Typography>
152
+ // </Paper>
153
+ // );
154
+ // }
155
+
156
+ return (
157
+ <>
158
+ <Fade in={true} timeout={300}>
159
+ <Paper
160
+ ref={dragRef}
161
+ elevation={isDragging ? 2 : 1}
162
+ sx={{
163
+ position: "fixed",
164
+ left: position.x,
165
+ top: position.y,
166
+ p: 1,
167
+ borderRadius: 3,
168
+ bgcolor: "background.paper",
169
+ cursor: isDragging ? "grabbing" : "grab",
170
+ transition: theme.transitions.create(["box-shadow", "transform"], {
171
+ duration: theme.transitions.duration.short,
172
+ }),
173
+ transform: isDragging ? "scale(1.01)" : "scale(1)",
174
+ minWidth: 320,
175
+ userSelect: "none",
176
+ }}
177
+ onMouseDown={handleMouseDown}
178
+ onTouchStart={handleTouchStart}
179
+ >
180
+ <Box
181
+ sx={{
182
+ display: "flex",
183
+ alignItems: "center",
184
+ }}
185
+ >
186
+ {/* Status and Timer Row */}
187
+ <Box
188
+ sx={{
189
+ display: "flex",
190
+ justifyContent: "space-between",
191
+ alignItems: "center",
192
+ }}
193
+ >
194
+ <Typography
195
+ variant="h6"
196
+ sx={{
197
+ color: state.callStartTime
198
+ ? "success.main"
199
+ : "text.secondary",
200
+ marginRight: "8px",
201
+ display: "flex",
202
+ justifyContent: "space-between",
203
+ alignItems: "center",
204
+ }}
205
+ >
206
+ <DragIndicator
207
+ sx={{
208
+ marginRight: "10px",
209
+ }}
210
+ />{" "}
211
+ {formatDuration(callDuration)}
212
+ </Typography>
213
+
214
+ <Tooltip title="Status">
215
+ <Button
216
+ sx={{
217
+ backgroundColor: getStatusColor(state.status),
218
+ fontWeight: "bold",
219
+ borderRadius: "16px",
220
+ display: "flex",
221
+ alignItems: "center",
222
+ justifyContent: "space-between",
223
+ marginRight: "8px",
224
+ }}
225
+ onClick={(e) => {
226
+ e.stopPropagation();
227
+ handleMoreClick(e);
228
+ }}
229
+ variant="outlined"
230
+ >
231
+ <Typography
232
+ width={50}
233
+ variant="body2"
234
+ sx={{
235
+ fontWeight: "bold",
236
+ }}
237
+ >
238
+ {state.status.toUpperCase()}
239
+ </Typography>
240
+
241
+ <KeyboardArrowDown />
242
+ </Button>
243
+ </Tooltip>
244
+ </Box>
245
+
246
+ {/* Control Buttons */}
247
+ <Box
248
+ sx={{
249
+ display: "flex",
250
+ gap: 1,
251
+ justifyContent: "center",
252
+ alignItems: "center",
253
+ }}
254
+ >
255
+ <Tooltip title={"Redial"}>
256
+ <IconButton
257
+ onClick={(e) => {
258
+ e.stopPropagation();
259
+ }}
260
+ color={"default"}
261
+ sx={{
262
+ bgcolor: "action.hover",
263
+ "&:hover": {
264
+ bgcolor: "warning",
265
+ },
266
+ }}
267
+ >
268
+ <Cached />
269
+ </IconButton>
270
+ </Tooltip>
271
+ {/* Hold Button */}
272
+ <Tooltip title={state.isHolding ? "Resume" : "Hold"}>
273
+ <IconButton
274
+ onClick={(e) => {
275
+ e.stopPropagation();
276
+ handleHoldToggle();
277
+ }}
278
+ color={state.isHolding ? "warning" : "default"}
279
+ sx={{
280
+ bgcolor: state.isHolding ? "warning.info" : "action.hover",
281
+ }}
282
+ >
283
+ {state.isHolding ? <PlayCircle /> : <PauseCircle />}
284
+ </IconButton>
285
+ </Tooltip>
286
+
287
+ {/* Mute Button */}
288
+ <Tooltip title={state.isMuted ? "Unmute" : "Mute"}>
289
+ <IconButton
290
+ onClick={(e) => {
291
+ e.stopPropagation();
292
+ handleMuteToggle();
293
+ }}
294
+ color={state.isMuted ? "error" : "default"}
295
+ sx={{
296
+ bgcolor: state.isMuted ? "error.info" : "action.hover",
297
+ }}
298
+ >
299
+ {state.isMuted ? <MicOff /> : <Mic />}
300
+ </IconButton>
301
+ </Tooltip>
302
+
303
+ {/* More Menu Button */}
304
+ <Tooltip title="More Options">
305
+ <IconButton
306
+ onClick={(e) => {
307
+ e.stopPropagation();
308
+ handleMoreOptions(e);
309
+ }}
310
+ sx={{
311
+ bgcolor: "action.hover",
312
+ "&:hover": { bgcolor: "action.selected" },
313
+ }}
314
+ >
315
+ <MoreVert />
316
+ </IconButton>
317
+ </Tooltip>
318
+
319
+ {/* End Call Button */}
320
+ <Tooltip title={state.callStartTime ? "End Call" : "Start Call"}>
321
+ <IconButton
322
+ onClick={(e) => {
323
+ e.stopPropagation();
324
+ (state.callStartTime ? handleEndCall : handleStartCall)();
325
+ }}
326
+ color="error"
327
+ sx={{
328
+ bgcolor: state.callStartTime
329
+ ? "error.main"
330
+ : "success.light",
331
+ color: "white",
332
+ "&:hover": {
333
+ bgcolor: state.callStartTime
334
+ ? "error.light"
335
+ : "success.dark",
336
+ },
337
+ }}
338
+ >
339
+ <CallEnd />
340
+ </IconButton>
341
+ </Tooltip>
342
+ </Box>
343
+ </Box>
344
+ </Paper>
345
+ </Fade>
346
+
347
+ {/* More Options Menu */}
348
+ <Menu
349
+ anchorEl={anchorEl}
350
+ open={Boolean(anchorEl)}
351
+ onClose={handleMoreClose}
352
+ onClick={(e) => e.stopPropagation()}
353
+ >
354
+ <MenuItem
355
+ onClick={() => handleStatusChange("ready")}
356
+ sx={{
357
+ backgroundColor: state.status === "ready" ? "#0038f01c" : "initial",
358
+ }}
359
+ >
360
+ <Box
361
+ sx={{
362
+ display: "flex",
363
+ alignItems: "center",
364
+ gap: 1,
365
+ }}
366
+ >
367
+ <Phone color="success" />
368
+ <Typography>Ready</Typography>
369
+ </Box>
370
+ </MenuItem>
371
+ <MenuItem
372
+ onClick={() => handleStatusChange("break")}
373
+ sx={{
374
+ backgroundColor: state.status === "break" ? "#0038f01c" : "initial",
375
+ }}
376
+ >
377
+ <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
378
+ <FreeBreakfast color="error" />
379
+ <Typography>Break</Typography>
380
+ </Box>
381
+ </MenuItem>
382
+ <MenuItem
383
+ onClick={() => handleStatusChange("idle")}
384
+ sx={{
385
+ backgroundColor: state.status === "idle" ? "#0038f01c" : "initial",
386
+ }}
387
+ >
388
+ <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
389
+ <AirlineSeatIndividualSuite color="warning" />
390
+ <Typography>Idle</Typography>
391
+ </Box>
392
+ </MenuItem>
393
+ </Menu>
394
+
395
+ <Menu
396
+ anchorEl={moreOptionsAnchorEl}
397
+ open={Boolean(moreOptionsAnchorEl)}
398
+ onClose={handleMoreOptionsClose}
399
+ onClick={(e) => e.stopPropagation()}
400
+ >
401
+ <MenuItem onClick={() => setMoreOptionsAnchorEl(null)}>
402
+ <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
403
+ <TransferWithinAStation color="secondary" />
404
+ <Typography>Call Transfer</Typography>
405
+ </Box>
406
+ </MenuItem>
407
+ <MenuItem onClick={() => setMoreOptionsAnchorEl(null)}>
408
+ <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
409
+ <Groups color="secondary" />
410
+ <Typography>Conference Call</Typography>
411
+ </Box>
412
+ </MenuItem>
413
+ <MenuItem onClick={() => setMoreOptionsAnchorEl(null)}>
414
+ <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
415
+ <SpatialAudioOff color="secondary" />
416
+ <Typography>Queue Waiting</Typography>
417
+ </Box>
418
+ </MenuItem>
419
+ </Menu>
420
+ </>
421
+ );
422
+ }
@@ -0,0 +1,128 @@
1
+ import {
2
+ useState,
3
+ useRef,
4
+ useCallback,
5
+ type MouseEvent,
6
+ type TouchEvent,
7
+ } from "react";
8
+
9
+ interface Position {
10
+ x: number;
11
+ y: number;
12
+ }
13
+
14
+ interface UseDraggableReturn {
15
+ position: Position;
16
+ isDragging: boolean;
17
+ dragRef: React.RefObject<HTMLDivElement | null>;
18
+ handleMouseDown: (e: MouseEvent<HTMLDivElement>) => void;
19
+ handleTouchStart: (e: TouchEvent<HTMLDivElement>) => void;
20
+ }
21
+
22
+ export function useDraggable(
23
+ initialPosition: Position,
24
+ onPositionChange?: (position: Position) => void
25
+ ): UseDraggableReturn {
26
+ const [position, setPosition] = useState<Position>(initialPosition);
27
+ const [isDragging, setIsDragging] = useState(false);
28
+ const dragRef = useRef<HTMLDivElement>(null);
29
+ const dragStart = useRef<Position>({ x: 0, y: 0 });
30
+ const elementStart = useRef<Position>({ x: 0, y: 0 });
31
+
32
+ const updatePosition = useCallback(
33
+ (newPosition: Position) => {
34
+ // Constrain position to viewport bounds
35
+ const element = dragRef.current;
36
+ if (!element) return;
37
+
38
+ const rect = element.getBoundingClientRect();
39
+ const viewportWidth = window.innerWidth;
40
+ const viewportHeight = window.innerHeight;
41
+
42
+ const constrainedPosition = {
43
+ x: Math.max(0, Math.min(newPosition.x, viewportWidth - rect.width)),
44
+ y: Math.max(0, Math.min(newPosition.y, viewportHeight - rect.height)),
45
+ };
46
+
47
+ setPosition(constrainedPosition);
48
+ onPositionChange?.(constrainedPosition);
49
+ },
50
+ [onPositionChange]
51
+ );
52
+
53
+ const handleStart = useCallback(
54
+ (clientX: number, clientY: number) => {
55
+ setIsDragging(true);
56
+ dragStart.current = { x: clientX, y: clientY };
57
+ elementStart.current = position;
58
+
59
+ const handleMove = (moveClientX: number, moveClientY: number) => {
60
+ const deltaX = moveClientX - dragStart.current.x;
61
+ const deltaY = moveClientY - dragStart.current.y;
62
+
63
+ const newPosition = {
64
+ x: elementStart.current.x + deltaX,
65
+ y: elementStart.current.y + deltaY,
66
+ };
67
+
68
+ updatePosition(newPosition);
69
+ };
70
+
71
+ const handleMouseMove = (e: globalThis.MouseEvent) => {
72
+ e.preventDefault();
73
+ handleMove(e.clientX, e.clientY);
74
+ };
75
+
76
+ const handleTouchMove = (e: globalThis.TouchEvent) => {
77
+ e.preventDefault();
78
+ const touch = e.touches[0];
79
+ if (touch) {
80
+ handleMove(touch.clientX, touch.clientY);
81
+ }
82
+ };
83
+
84
+ const handleEnd = () => {
85
+ setIsDragging(false);
86
+ document.removeEventListener("mousemove", handleMouseMove);
87
+ document.removeEventListener("mouseup", handleEnd);
88
+ document.removeEventListener("touchmove", handleTouchMove);
89
+ document.removeEventListener("touchend", handleEnd);
90
+ };
91
+
92
+ document.addEventListener("mousemove", handleMouseMove);
93
+ document.addEventListener("mouseup", handleEnd);
94
+ document.addEventListener("touchmove", handleTouchMove, {
95
+ passive: false,
96
+ });
97
+ document.addEventListener("touchend", handleEnd);
98
+ },
99
+ [position, updatePosition]
100
+ );
101
+
102
+ const handleMouseDown = useCallback(
103
+ (e: MouseEvent<HTMLDivElement>) => {
104
+ e.preventDefault();
105
+ handleStart(e.clientX, e.clientY);
106
+ },
107
+ [handleStart]
108
+ );
109
+
110
+ const handleTouchStart = useCallback(
111
+ (e: TouchEvent<HTMLDivElement>) => {
112
+ e.preventDefault();
113
+ const touch = e.touches[0];
114
+ if (touch) {
115
+ handleStart(touch.clientX, touch.clientY);
116
+ }
117
+ },
118
+ [handleStart]
119
+ );
120
+
121
+ return {
122
+ position,
123
+ isDragging,
124
+ dragRef,
125
+ handleMouseDown,
126
+ handleTouchStart,
127
+ };
128
+ }
@@ -0,0 +1,17 @@
1
+ import { useState, useEffect } from "react";
2
+ import { sdkStateManager } from "../sdk-state";
3
+ import type { SDKState } from "../types";
4
+
5
+ export function useSDKState(): SDKState {
6
+ const [state, setState] = useState<SDKState>(sdkStateManager.getState());
7
+
8
+ useEffect(() => {
9
+ const unsubscribe = sdkStateManager.subscribe(() => {
10
+ setState(sdkStateManager.getState());
11
+ });
12
+
13
+ return unsubscribe;
14
+ }, []);
15
+
16
+ return state;
17
+ }
@@ -0,0 +1,25 @@
1
+ import { sdkStateManager } from './sdk-state';
2
+
3
+ export { CallControlPanel } from './components/CallControlPanel';
4
+ export type { CallControlPanelProps, CallData, CallStatus } from './types';
5
+
6
+ /**
7
+ * Initialize the Call Control SDK with an API key
8
+ * @param sdkApiKey - The API key for SDK authentication
9
+ * @throws {Error} When API key is missing or invalid
10
+ */
11
+ export function initCallSDK(sdkApiKey: string): void {
12
+ sdkStateManager.initialize(sdkApiKey);
13
+ }
14
+
15
+ /**
16
+ * Update call data (used by host application)
17
+ * @param data - Partial call data to update
18
+ */
19
+ export function updateCallData(data: {
20
+ mobileNumber?: string;
21
+ callReferenceId?: string;
22
+ agentLoginId?: string;
23
+ }): void {
24
+ sdkStateManager.updateCallData(data);
25
+ }
@@ -0,0 +1,140 @@
1
+ import type { SDKState, CallData, CallStatus } from "./types";
2
+
3
+ class SDKStateManager {
4
+ private state: SDKState;
5
+ private listeners: Array<() => void> = [];
6
+ private readonly STORAGE_KEY = "call-control-sdk-state";
7
+
8
+ constructor() {
9
+ this.state = this.getInitialState();
10
+ this.loadFromStorage();
11
+ }
12
+
13
+ private getInitialState(): SDKState {
14
+ return {
15
+ apiKey: null,
16
+ isInitialized: false,
17
+ isHolding: false,
18
+ isMuted: false,
19
+ status: "idle",
20
+ callStartTime: null,
21
+ position: { x: 50, y: 50 },
22
+ callData: {
23
+ mobileNumber: "",
24
+ callReferenceId: "",
25
+ agentLoginId: "",
26
+ },
27
+ };
28
+ }
29
+
30
+ private loadFromStorage(): void {
31
+ try {
32
+ const stored = localStorage.getItem(this.STORAGE_KEY);
33
+ if (stored) {
34
+ const parsedState = JSON.parse(stored);
35
+ // Only restore persistent data, not initialization state
36
+ this.state = {
37
+ ...this.state,
38
+ isHolding: parsedState.isHolding || false,
39
+ isMuted: parsedState.isMuted || false,
40
+ status: parsedState.status || "idle",
41
+ position: parsedState.position || { x: 50, y: 50 },
42
+ callStartTime: parsedState.callStartTime || null,
43
+ };
44
+ }
45
+ } catch (error) {
46
+ console.warn("Failed to load SDK state from localStorage:", error);
47
+ }
48
+ }
49
+
50
+ private saveToStorage(): void {
51
+ try {
52
+ const persistentState = {
53
+ isHolding: this.state.isHolding,
54
+ isMuted: this.state.isMuted,
55
+ status: this.state.status,
56
+ position: this.state.position,
57
+ callStartTime: this.state.callStartTime,
58
+ };
59
+ localStorage.setItem(this.STORAGE_KEY, JSON.stringify(persistentState));
60
+ } catch (error) {
61
+ console.warn("Failed to save SDK state to localStorage:", error);
62
+ }
63
+ }
64
+
65
+ private notifyListeners(): void {
66
+ this.listeners.forEach((listener) => listener());
67
+ }
68
+
69
+ public initialize(apiKey: string): void {
70
+ if (!apiKey || typeof apiKey !== "string" || apiKey.trim().length === 0) {
71
+ throw new Error("API key not available");
72
+ }
73
+
74
+ this.state.apiKey = apiKey;
75
+ this.state.isInitialized = true;
76
+ this.notifyListeners();
77
+ }
78
+
79
+ public getState(): SDKState {
80
+ return { ...this.state };
81
+ }
82
+
83
+ public subscribe(listener: () => void): () => void {
84
+ this.listeners.push(listener);
85
+ return () => {
86
+ const index = this.listeners.indexOf(listener);
87
+ if (index > -1) {
88
+ this.listeners.splice(index, 1);
89
+ }
90
+ };
91
+ }
92
+
93
+ public setHolding(isHolding: boolean): void {
94
+ this.state.isHolding = isHolding;
95
+ this.saveToStorage();
96
+ this.notifyListeners();
97
+ }
98
+
99
+ public setMuted(isMuted: boolean): void {
100
+ this.state.isMuted = isMuted;
101
+ this.saveToStorage();
102
+ this.notifyListeners();
103
+ }
104
+
105
+ public setStatus(status: CallStatus): void {
106
+ this.state.status = status;
107
+ this.saveToStorage();
108
+ this.notifyListeners();
109
+ }
110
+
111
+ public setPosition(position: { x: number; y: number }): void {
112
+ this.state.position = position;
113
+ this.saveToStorage();
114
+ this.notifyListeners();
115
+ }
116
+
117
+ public startCall(): void {
118
+ this.state.callStartTime = Date.now();
119
+ this.state.status = "ready";
120
+ this.saveToStorage();
121
+ this.notifyListeners();
122
+ }
123
+
124
+ public endCall(): void {
125
+ this.state.callStartTime = null;
126
+ this.state.status = "idle";
127
+ this.state.isHolding = false;
128
+ this.state.isMuted = false;
129
+ this.saveToStorage();
130
+ this.notifyListeners();
131
+ }
132
+
133
+ public updateCallData(data: Partial<CallData>): void {
134
+ this.state.callData = { ...this.state.callData, ...data };
135
+ this.notifyListeners();
136
+ }
137
+ }
138
+
139
+ // Singleton instance
140
+ export const sdkStateManager = new SDKStateManager();
@@ -0,0 +1,22 @@
1
+ export interface CallData {
2
+ mobileNumber: string;
3
+ callReferenceId: string;
4
+ agentLoginId: string;
5
+ }
6
+
7
+ export interface CallControlPanelProps {
8
+ onDataChange?: (data: CallData) => void;
9
+ }
10
+
11
+ export type CallStatus = 'idle' | 'ready' | 'break';
12
+
13
+ export interface SDKState {
14
+ apiKey: string | null;
15
+ isInitialized: boolean;
16
+ isHolding: boolean;
17
+ isMuted: boolean;
18
+ status: CallStatus;
19
+ callStartTime: number | null;
20
+ position: { x: number; y: number };
21
+ callData: CallData;
22
+ }
package/src/main.tsx ADDED
@@ -0,0 +1,10 @@
1
+ import { StrictMode } from 'react'
2
+ import { createRoot } from 'react-dom/client'
3
+ import './index.css'
4
+ import App from './App.tsx'
5
+
6
+ createRoot(document.getElementById('root')!).render(
7
+ <StrictMode>
8
+ <App />
9
+ </StrictMode>,
10
+ )
@@ -0,0 +1 @@
1
+ /// <reference types="vite/client" />
@@ -0,0 +1,27 @@
1
+ {
2
+ "compilerOptions": {
3
+ "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
4
+ "target": "ES2022",
5
+ "useDefineForClassFields": true,
6
+ "lib": ["ES2022", "DOM", "DOM.Iterable"],
7
+ "module": "ESNext",
8
+ "skipLibCheck": true,
9
+
10
+ /* Bundler mode */
11
+ "moduleResolution": "bundler",
12
+ "allowImportingTsExtensions": true,
13
+ "verbatimModuleSyntax": true,
14
+ "moduleDetection": "force",
15
+ "noEmit": true,
16
+ "jsx": "react-jsx",
17
+
18
+ /* Linting */
19
+ "strict": true,
20
+ "noUnusedLocals": true,
21
+ "noUnusedParameters": true,
22
+ "erasableSyntaxOnly": true,
23
+ "noFallthroughCasesInSwitch": true,
24
+ "noUncheckedSideEffectImports": true
25
+ },
26
+ "include": ["src"]
27
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "files": [],
3
+ "references": [
4
+ { "path": "./tsconfig.app.json" },
5
+ { "path": "./tsconfig.node.json" }
6
+ ]
7
+ }
@@ -0,0 +1,23 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2020",
4
+ "useDefineForClassFields": true,
5
+ "lib": ["ES2020", "DOM", "DOM.Iterable"],
6
+ "module": "ESNext",
7
+ "skipLibCheck": true,
8
+ "moduleResolution": "bundler",
9
+ "allowImportingTsExtensions": true,
10
+ "resolveJsonModule": true,
11
+ "isolatedModules": true,
12
+ "noEmit": true,
13
+ "jsx": "react-jsx",
14
+ "strict": true,
15
+ "noUnusedLocals": true,
16
+ "noUnusedParameters": true,
17
+ "noFallthroughCasesInSwitch": true,
18
+ "declaration": true,
19
+ "outDir": "./dist"
20
+ },
21
+ "include": ["src/lib/**/*"],
22
+ "exclude": ["src/main.tsx", "src/App.tsx", "**/*.test.*"]
23
+ }
@@ -0,0 +1,25 @@
1
+ {
2
+ "compilerOptions": {
3
+ "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
4
+ "target": "ES2023",
5
+ "lib": ["ES2023"],
6
+ "module": "ESNext",
7
+ "skipLibCheck": true,
8
+
9
+ /* Bundler mode */
10
+ "moduleResolution": "bundler",
11
+ "allowImportingTsExtensions": true,
12
+ "verbatimModuleSyntax": true,
13
+ "moduleDetection": "force",
14
+ "noEmit": true,
15
+
16
+ /* Linting */
17
+ "strict": true,
18
+ "noUnusedLocals": true,
19
+ "noUnusedParameters": true,
20
+ "erasableSyntaxOnly": true,
21
+ "noFallthroughCasesInSwitch": true,
22
+ "noUncheckedSideEffectImports": true
23
+ },
24
+ "include": ["vite.config.ts"]
25
+ }
package/vite.config.ts ADDED
@@ -0,0 +1,47 @@
1
+ import { defineConfig } from "vite";
2
+ import react from "@vitejs/plugin-react-swc";
3
+ import { resolve } from "path";
4
+ // https://vite.dev/config/
5
+ export default defineConfig(({ mode }) => {
6
+ if (mode === "lib") {
7
+ return {
8
+ plugins: [react()],
9
+ build: {
10
+ lib: {
11
+ entry: resolve(__dirname, "src/lib/index.ts"),
12
+ name: "ReactCallControlSDK",
13
+ formats: ["es", "umd"],
14
+ fileName: (format) => `index.${format}.js`,
15
+ },
16
+ rollupOptions: {
17
+ external: [
18
+ "react",
19
+ "react-dom",
20
+ "react/jsx-runtime",
21
+ "react/jsx-dev-runtime",
22
+ "@mui/material",
23
+ "@mui/icons-material",
24
+ "@emotion/react",
25
+ "@emotion/styled",
26
+ ],
27
+ output: {
28
+ globals: {
29
+ react: "React",
30
+ "react-dom": "ReactDOM",
31
+ "react/jsx-runtime": "React",
32
+ "react/jsx-dev-runtime": "React",
33
+ "@mui/material": "MaterialUI",
34
+ "@mui/icons-material": "MaterialUIIcons",
35
+ "@emotion/react": "EmotionReact",
36
+ "@emotion/styled": "EmotionStyled",
37
+ },
38
+ },
39
+ },
40
+ },
41
+ };
42
+ }
43
+
44
+ return {
45
+ plugins: [react()],
46
+ };
47
+ });