socialcalc-ai 1.0.0 โ†’ 1.0.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.
Files changed (2) hide show
  1. package/README.md +448 -178
  2. package/package.json +1 -1
package/README.md CHANGED
@@ -1,55 +1,243 @@
1
- # SocialCalc AI (`socialcalc-ai`)
1
+ # socialcalc-ai
2
+
3
+ [![npm version](https://img.shields.io/npm/v/socialcalc-ai.svg?color=cb3837&style=flat-square)](https://www.npmjs.com/package/socialcalc-ai)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg?style=flat-square)](https://opensource.org/licenses/MIT)
5
+ [![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue.svg?style=flat-square)](https://www.typescriptlang.org/)
6
+ [![Module: ESM](https://img.shields.io/badge/Module-ESM-success.svg?style=flat-square)](https://nodejs.org/api/esm.html)
2
7
 
3
8
  > **A modernized, modularized, high-performance spreadsheet engine with ES6 module exports, React/Ionic UI components, AI template capabilities, and an extensible plugin system.**
4
9
 
10
+ Derived from Dan Bricklin's proven, industrial-strength **SocialCalc** engine, `socialcalc-ai` has been re-architected for modern web, mobile, and AI-driven applications. It replaces legacy global variables with clean ES modules, provides full TypeScript definitions, adds smooth mobile touch physics, and includes a full suite of modern React/Ionic UI controls.
11
+
12
+ ---
13
+
14
+ ## ๐Ÿ“‘ Table of Contents
15
+
16
+ - [Features](#-features)
17
+ - [Installation](#-installation)
18
+ - [Quick Start in React / Ionic](#-quick-start-in-react--ionic)
19
+ - [Quick Start in Vanilla JavaScript](#-quick-start-in-vanilla-javascript)
20
+ - [Architecture Overview](#-architecture-overview)
21
+ - [UI Components](#-ui-components)
22
+ - [CellEditModal](#1-celleditmodal)
23
+ - [HorizontalScrollBar](#2-horizontalscrollbar)
24
+ - [RowActionPopover](#3-rowactionpopover)
25
+ - [EditableCellsModal](#4-editablecellsmodal)
26
+ - [DemoVideosModal](#5-demovideosmodal)
27
+ - [Plugins & Modules API](#-plugins--modules-api)
28
+ - [Row & Column Headers](#1-row--column-headers-modulesrow-col-headersjs)
29
+ - [Grid Lines](#2-grid-lines-modulesgrid-linesjs)
30
+ - [Smooth Touch Scroll](#3-smooth-touch-scroll-modulestouch-scrolljs)
31
+ - [Horizontal Scroll](#4-horizontal-scroll-moduleshorizontal-scrolljs)
32
+ - [Editable Cells & Template Locks](#5-editable-cells--template-locks-moduleseditable-cellsjs)
33
+ - [Plugin Manager](#6-plugin-manager-modulesplugin-managerjs)
34
+ - [History & Undo/Redo](#7-history-undo--redo-moduleshistoryjs)
35
+ - [Exporters & Sheets](#8-exporters--sheets-modulesexportersjs-modulessheetsjs)
36
+ - [Invoice Utilities](#9-invoice-utilities-modulesinvoicejs)
37
+ - [Event-Driven Architecture](#-event-driven-architecture)
38
+ - [AI & MultiSheet Calc (MSC) Integration](#-ai--multisheet-calc-msc-integration)
39
+ - [TypeScript Support](#-typescript-support)
40
+ - [Browser & Framework Compatibility](#-browser--framework-compatibility)
41
+ - [License & Acknowledgments](#-license--acknowledgments)
42
+
43
+ ---
44
+
45
+ ## โœจ Features
46
+
47
+ - **โšก Modern ES6 Architecture**: Pure ES module exports replacing legacy global namespace pollution. Works with Vite, Next.js, Webpack, Rollup, and ES2020+ runtimes.
48
+ - **๐Ÿ“ฑ Touch & Mobile Optimized**: Smooth momentum physics and inertia swipe scrolling without screen jumping or layout stutter.
49
+ - **๐ŸŽจ Modern React & Ionic UI Suite**:
50
+ - Full-featured **CellEditModal** (Formulas, rich formatting, custom color palettes, borders, and compressed image inserts).
51
+ - Smooth **HorizontalScrollBar** with live column indicators and drag navigation.
52
+ - Interactive **RowActionPopover** for dynamic row insertion and deletion.
53
+ - **EditableCellsModal** to inspect and manage cell locks.
54
+ - **DemoVideosModal** with an interactive formula cheat sheet.
55
+ - **๐Ÿ”Œ Pluggable Architecture**: Dynamically enable, disable, or configure spreadsheet subsystems (headers, gridlines, momentum scroll, locks).
56
+ - **๐Ÿ“ Universal Calculation Engine**: Industrial-grade formula AST evaluator supporting standard math, statistics, string, logic, and financial functions.
57
+ - **๐Ÿค– AI-Ready MultiSheet Calc (MSC)**: Serialize and deserialize full spreadsheet workbooks as structured JSON or MSC strings, ideal for LLM spreadsheet generation pipelines.
58
+ - **๐Ÿ›ก Full TypeScript Definitions**: First-class `index.d.ts` definitions included out of the box.
59
+
5
60
  ---
6
61
 
7
62
  ## ๐Ÿ“ฆ Installation
8
63
 
64
+ Install `socialcalc-ai` via npm:
65
+
9
66
  ```bash
10
67
  npm install socialcalc-ai
11
68
  ```
12
69
 
13
- Or with yarn / pnpm:
70
+ Or using Yarn / pnpm:
71
+
14
72
  ```bash
73
+ # Using Yarn
15
74
  yarn add socialcalc-ai
75
+
76
+ # Using pnpm
16
77
  pnpm add socialcalc-ai
17
78
  ```
18
79
 
80
+ ### Peer Dependencies
81
+
82
+ If you plan to use the pre-built React / Ionic components (`CellEditModal`, `HorizontalScrollBar`, etc.), ensure the peer dependencies are installed:
83
+
84
+ ```bash
85
+ npm install react react-dom @ionic/react ionicons
86
+ ```
87
+
88
+ *(Note: Peer dependencies are optional if you only consume the core calculation engine in headless Node.js or Vanilla JS environments).*
89
+
19
90
  ---
20
91
 
21
- ## ๐Ÿ“Œ Overview
92
+ ## ๐Ÿš€ Quick Start in React / Ionic
22
93
 
23
- This package (`socialcalc-ai`) is a **standalone, framework-agnostic core** with first-class React & Ionic bindings. It takes Dan Bricklin's proven, industrial-strength SocialCalc engine and modernizes it for modern web, mobile, and AI applications:
24
- - **Clean ES6 module structure** replacing legacy globals.
25
- - **Pluggable Architecture**: Dynamically toggle features like Grid Lines, 123/ABCD Row-Col Headers, Touch Scroll with momentum, and Editable Cell Locking.
26
- - **Modern Touch & Mobile Support**: Smooth inertia swipe scrolling without jumping.
27
- - **Modern Ionic / React Components**: High-fidelity modal editors, responsive horizontal scroll controls, context popovers for row operations, and cell mapping inspectors.
28
- - **Universal Spreadsheet Commands**: Full support for SocialCalc formulas, cell formatting, font styling, borders, multi-sheet workbooks, and CSV/MSC serialization.
94
+ Below is a complete, minimal working example showing how to mount the spreadsheet engine and hook up the interactive React UI suite:
29
95
 
30
- > โš ๏ธ **CRITICAL FOR DEVELOPERS & AGENTS**:
31
- > This package is consumed as a shared standalone dependency across multiple downstream apps. Any breaking changes to public APIs, event signatures, or file paths will impact all applications using it. Always preserve backward compatibility.
96
+ ```tsx
97
+ import React, { useEffect, useState } from "react";
98
+ import * as AppGeneral from "socialcalc-ai";
99
+ import {
100
+ CellEditModal,
101
+ HorizontalScrollBar,
102
+ RowActionPopover,
103
+ EditableCellsModal,
104
+ } from "socialcalc-ai";
105
+
106
+ // Optional: Ionic base styles if using Ionic framework
107
+ import "@ionic/react/css/core.css";
108
+
109
+ export const SpreadsheetEditor: React.FC = () => {
110
+ const [cellEditData, setCellEditData] = useState<any>(null);
111
+ const [showEditModal, setShowEditModal] = useState(false);
112
+ const [rowPopoverEvent, setRowPopoverEvent] = useState<{ event: any; rowNum: number } | null>(null);
113
+
114
+ useEffect(() => {
115
+ // 1. Initialize SocialCalc DOM container with initial data (or empty string)
116
+ const initialMSC = "";
117
+ AppGeneral.initializeApp(initialMSC);
118
+
119
+ // 2. Activate desired plugins
120
+ AppGeneral.enableRowColHeaders(); // 1, 2, 3... & A, B, C... headers with resize handles
121
+ AppGeneral.enableGridLines(); // Modern cell border grid
122
+ AppGeneral.enableTouchScroll(); // Smooth mobile inertia scroll
123
+
124
+ // 3. Listen for Cell Edit Modal requests
125
+ const handleCellEdit = (e: any) => {
126
+ setCellEditData(e.detail);
127
+ setShowEditModal(true);
128
+ };
129
+
130
+ // 4. Listen for Row Header clicks (context actions)
131
+ const handleRowClick = (e: any) => {
132
+ setRowPopoverEvent({
133
+ event: e.detail.originalEvent || e.detail,
134
+ rowNum: e.detail.rowNum,
135
+ });
136
+ };
137
+
138
+ window.addEventListener("socialcalc:cell-edit-request", handleCellEdit);
139
+ window.addEventListener("socialcalc:row-header-click", handleRowClick);
140
+
141
+ return () => {
142
+ window.removeEventListener("socialcalc:cell-edit-request", handleCellEdit);
143
+ window.removeEventListener("socialcalc:row-header-click", handleRowClick);
144
+ };
145
+ }, []);
146
+
147
+ return (
148
+ <div style={{ position: "relative", width: "100%", height: "100vh", overflow: "hidden" }}>
149
+ {/* SocialCalc DOM Mounting Target Elements */}
150
+ <div id="container" style={{ width: "100%", height: "calc(100% - 44px)" }}>
151
+ <div id="workbookControl" style={{ display: "none" }}></div>
152
+ <div id="tableeditor" style={{ width: "100%", height: "100%" }}></div>
153
+ <div id="msg"></div>
154
+ </div>
155
+
156
+ {/* Horizontal Viewport Scrollbar */}
157
+ <HorizontalScrollBar />
158
+
159
+ {/* Rich Cell Editor Bottom Sheet */}
160
+ <CellEditModal
161
+ isOpen={showEditModal}
162
+ cellData={cellEditData}
163
+ onClose={() => setShowEditModal(false)}
164
+ />
165
+
166
+ {/* Row Insert / Delete Popover */}
167
+ <RowActionPopover
168
+ isOpen={!!rowPopoverEvent}
169
+ event={rowPopoverEvent?.event}
170
+ selectedRow={rowPopoverEvent?.rowNum}
171
+ onDismiss={() => setRowPopoverEvent(null)}
172
+ />
173
+ </div>
174
+ );
175
+ };
176
+
177
+ export default SpreadsheetEditor;
178
+ ```
179
+
180
+ ---
181
+
182
+ ## ๐ŸŒ Quick Start in Vanilla JavaScript
183
+
184
+ `socialcalc-ai` can be used in plain HTML/JavaScript or non-React web apps without any framework overhead:
185
+
186
+ ```html
187
+ <!DOCTYPE html>
188
+ <html lang="en">
189
+ <head>
190
+ <meta charset="UTF-8" />
191
+ <title>SocialCalc AI Standalone</title>
192
+ </head>
193
+ <body>
194
+ <div id="container">
195
+ <div id="workbookControl" style="display: none;"></div>
196
+ <div id="tableeditor"></div>
197
+ <div id="msg"></div>
198
+ </div>
199
+
200
+ <script type="module">
201
+ import * as SocialCalcApp from "socialcalc-ai";
202
+
203
+ // Initialize spreadsheet
204
+ SocialCalcApp.initializeApp("");
205
+
206
+ // Enable modern features
207
+ SocialCalcApp.enableGridLines();
208
+ SocialCalcApp.enableRowColHeaders();
209
+ SocialCalcApp.enableTouchScroll();
210
+
211
+ // Listen for cell change events
212
+ SocialCalcApp.setupCellChangeListener((coord, value) => {
213
+ console.log(`Cell ${coord} updated:`, value);
214
+ });
215
+ </script>
216
+ </body>
217
+ </html>
218
+ ```
32
219
 
33
220
  ---
34
221
 
35
- ## ๐Ÿ“ Package Architecture
222
+ ## ๐Ÿ“ Architecture Overview
36
223
 
37
224
  ```text
38
- socialcalc/
39
- โ”œโ”€โ”€ index.js # Main entry point: re-exports core, all modules & React components
225
+ socialcalc-ai/
226
+ โ”œโ”€โ”€ index.js # Main entry point: aggregates core, modules & UI
227
+ โ”œโ”€โ”€ index.d.ts # Complete TypeScript typings
40
228
  โ”œโ”€โ”€ package.json # Standalone package definition
41
- โ”œโ”€โ”€ core/ # Core calculation engine & table rendering
42
- โ”‚ โ”œโ”€โ”€ constants.js # SocialCalc constant definitions & default styles
229
+ โ”œโ”€โ”€ core/ # Core calculation engine & DOM table rendering
230
+ โ”‚ โ”œโ”€โ”€ constants.js # Formatting codes, default styles & limits
43
231
  โ”‚ โ”œโ”€โ”€ core.js # Spreadsheet sheet model, cell evaluation, formula AST
44
- โ”‚ โ”œโ”€โ”€ formula.js # Built-in math, logical, string, financial formulas
232
+ โ”‚ โ”œโ”€โ”€ formula.js # Built-in math, logical, string, financial functions
45
233
  โ”‚ โ”œโ”€โ”€ format-number.js # Numeric and date formatting routines
46
234
  โ”‚ โ”œโ”€โ”€ spreadsheet-control.js # Spreadsheet control lifecycle & pane management
47
235
  โ”‚ โ”œโ”€โ”€ table-editor.js # DOM table editor layout & cursor rendering
48
236
  โ”‚ โ””โ”€โ”€ index.js # Assembled core SocialCalc singleton export
49
- โ”œโ”€โ”€ modules/ # Modularized functional features & plugins
237
+ โ”œโ”€โ”€ modules/ # Modular functional features & plugins
50
238
  โ”‚ โ”œโ”€โ”€ plugin-manager.js # Central registry for dynamic SocialCalc plugins
51
- โ”‚ โ”œโ”€โ”€ grid-lines.js # Dynamic cell border grid-lines plugin
52
- โ”‚ โ”œโ”€โ”€ row-col-headers.js # 123 Row & ABCD Col headers with resize handles & row selection
239
+ โ”‚ โ”œโ”€โ”€ grid-lines.js # Cell border grid-lines plugin
240
+ โ”‚ โ”œโ”€โ”€ row-col-headers.js # 123 / ABCD headers with resize handles & row selection
53
241
  โ”‚ โ”œโ”€โ”€ touch-scroll.js # Momentum/inertia mobile touch scroll
54
242
  โ”‚ โ”œโ”€โ”€ horizontal-scroll.js # Viewport tracking & horizontal scrolling subscriptions
55
243
  โ”‚ โ”œโ”€โ”€ editable-cells.js # Cell lock & template permission plugin
@@ -60,12 +248,13 @@ socialcalc/
60
248
  โ”‚ โ”œโ”€โ”€ init.js # Workbook & table editor DOM initialization
61
249
  โ”‚ โ”œโ”€โ”€ prompts.js # Enhanced input dialogs & modal dispatchers
62
250
  โ”‚ โ”œโ”€โ”€ exporters.js # HTML, CSV, MSC export helpers
251
+ โ”‚ โ”œโ”€โ”€ invoice.js # Coordinate mapping & invoice utilities
63
252
  โ”‚ โ”œโ”€โ”€ device.js # Device detection and responsive helpers
64
253
  โ”‚ โ”œโ”€โ”€ logos.js # Brand/logo helper utilities
65
254
  โ”‚ โ”œโ”€โ”€ utils.js # Coordinate conversions, DOM utilities
66
255
  โ”‚ โ””โ”€โ”€ weight.js # Cell weight/scoring utilities
67
256
  โ”œโ”€โ”€ components/ # React & Ionic UI Components
68
- โ”‚ โ”œโ”€โ”€ CellEditModal/ # Rich bottom sheet editor (Text, Formula, Colors, Borders, Images)
257
+ โ”‚ โ”œโ”€โ”€ CellEditModal/ # Rich editor sheet (Formulas, Text, Colors, Borders, Images)
69
258
  โ”‚ โ”œโ”€โ”€ HorizontalScrollBar.tsx # Smooth horizontal navigation bar & track slider
70
259
  โ”‚ โ”œโ”€โ”€ RowActionPopover/ # Context menu for row insertion & deletion
71
260
  โ”‚ โ”œโ”€โ”€ EditableCellsModal/ # Template mapping manager & cell lock editor
@@ -77,192 +266,273 @@ socialcalc/
77
266
 
78
267
  ---
79
268
 
80
- ## ๐Ÿš€ Quick Start in React / Ionic
269
+ ## ๐ŸŽจ UI Components
81
270
 
82
- ### 1. Installation
271
+ ### 1. `CellEditModal`
272
+ A modern, responsive bottom-sheet modal that replaces legacy browser `prompt()` dialogs with a rich spreadsheet formatting bar:
273
+ - **Formula & Text Editor**: Live input bar with syntax validation (e.g. `=SUM(A1:B10)`).
274
+ - **Styling**: Bold, Italic, Alignment (Left, Center, Right).
275
+ - **Curated Palette**: 8 font colors (`FONT_COLORS`) and 7 background colors (`BG_COLORS`).
276
+ - **Cell Borders**: Top, Bottom, Left, Right, and All borders with Solid, Dashed, or Dotted styles.
277
+ - **Image Insertion**: Embed images into cells with automatic client-side compression via `imageCompressor.ts`.
278
+ - **Fallback**: Automatically falls back to native inline input if modal mode is disabled.
83
279
 
84
- ```bash
85
- npm install socialcalc-ai
280
+ ```tsx
281
+ <CellEditModal
282
+ isOpen={isOpen}
283
+ cellData={cellData}
284
+ onClose={() => setIsOpen(false)}
285
+ />
86
286
  ```
87
287
 
88
- ### 2. Initialization in React Component
288
+ ### 2. `HorizontalScrollBar`
289
+ A smooth horizontal track controller designed specifically for wide spreadsheets on mobile and desktop:
290
+ - Step-by-step column advancement buttons (โ—€ / โ–ถ).
291
+ - Responsive drag track with active column indicator (e.g., `Cols: A - J`).
292
+ - Synchronizes bi-directionally with keyboard arrow navigation and touch scrolling.
89
293
 
90
294
  ```tsx
91
- import React, { useEffect, useState } from "react";
92
- import * as AppGeneral from "socialcalc-ai";
93
- import {
94
- CellEditModal,
95
- HorizontalScrollBar,
96
- RowActionPopover,
97
- } from "socialcalc-ai";
98
-
99
- const MySpreadsheet: React.FC = () => {
100
- const [cellEditData, setCellEditData] = useState<any>(null);
101
- const [showModal, setShowModal] = useState(false);
102
-
103
- useEffect(() => {
104
- // 1. Initialize DOM workbook container
105
- const initialMSC = { /* SocialCalc MSC json or save string */ };
106
- AppGeneral.initializeApp(JSON.stringify(initialMSC));
295
+ <HorizontalScrollBar />
296
+ ```
107
297
 
108
- // 2. Enable desired plugins
109
- AppGeneral.enableRowColHeaders(); // 123 / ABCD headers
110
- AppGeneral.enableGridLines(); // Cell grid borders
111
- AppGeneral.enableTouchScroll(); // Smooth touch scrolling
298
+ ### 3. `RowActionPopover`
299
+ A context popup that appears when clicking any row header index:
300
+ - **Insert Row Above**: Inserts an empty row above the selected index.
301
+ - **Insert Row Below**: Inserts an empty row below the selected index.
302
+ - **Delete Row**: Removes the selected row and cascades formula references.
112
303
 
113
- // 3. Listen for Cell Edit Modal request events
114
- const handleCellEdit = (e: any) => {
115
- setCellEditData(e.detail);
116
- setShowModal(true);
117
- };
118
- window.addEventListener("socialcalc:cell-edit-request", handleCellEdit);
304
+ ```tsx
305
+ <RowActionPopover
306
+ isOpen={showPopover}
307
+ event={clickEvent}
308
+ selectedRow={rowNumber}
309
+ onDismiss={() => setShowPopover(false)}
310
+ />
311
+ ```
119
312
 
120
- return () => {
121
- window.removeEventListener("socialcalc:cell-edit-request", handleCellEdit);
122
- };
123
- }, []);
313
+ ### 4. `EditableCellsModal`
314
+ An administrative inspector for template creators:
315
+ - View all locked vs editable cells in the active sheet.
316
+ - Bind application field mappings (e.g., `vendor_name -> B4`) to spreadsheet coordinates.
317
+ - Test template locking permissions.
124
318
 
125
- return (
126
- <div style={{ position: "relative", width: "100%", height: "100vh" }}>
127
- {/* SocialCalc mounting targets */}
128
- <div id="container">
129
- <div id="workbookControl" style={{ display: "none" }}></div>
130
- <div id="tableeditor"></div>
131
- <div id="msg"></div>
132
- </div>
319
+ ```tsx
320
+ <EditableCellsModal
321
+ isOpen={showModal}
322
+ onClose={() => setShowModal(false)}
323
+ />
324
+ ```
133
325
 
134
- {/* Horizontal Scroll Bar */}
135
- <HorizontalScrollBar />
326
+ ### 5. `DemoVideosModal`
327
+ An interactive help and reference modal containing:
328
+ - Built-in formula cheat sheets (`SUM`, `AVERAGE`, `IF`, `VLOOKUP`, `COUNT`, `CONCATENATE`, etc.).
329
+ - Embedded tutorial guides for spreadsheet operators.
136
330
 
137
- {/* Modern Cell Edit Modal */}
138
- <CellEditModal
139
- isOpen={showModal}
140
- cellData={cellEditData}
141
- onClose={() => setShowModal(false)}
142
- />
143
- </div>
144
- );
145
- };
331
+ ```tsx
332
+ <DemoVideosModal
333
+ isOpen={showHelp}
334
+ onClose={() => setShowHelp(false)}
335
+ />
146
336
  ```
147
337
 
148
338
  ---
149
339
 
150
- ## ๐Ÿ›  Features & Plugins Deep Dive
151
-
152
- ### 1. Row and Column Headers (`modules/row-col-headers.js`)
153
- Displays standard spreadsheet row numbers (`1, 2, 3...`) and column letters (`A, B, C...`).
154
- - **Smooth Column Resizing**: Hover or drag right edge of any column header to resize. Live floating tooltip and guideline indicate new column width.
155
- - **Corner Resize Handle**: Tap/click a column header to display a mobile-friendly corner drag handle (`#sc-col-resize-corner-handle`).
156
- - **Row Selection**: Clicking a row header selects the full row and fires `socialcalc:row-header-click`.
157
- - **API**:
158
- ```ts
159
- AppGeneral.enableRowColHeaders();
160
- AppGeneral.disableRowColHeaders();
161
- AppGeneral.toggleRowColHeaders(); // returns boolean
162
- AppGeneral.isRowColHeadersEnabled(); // returns boolean
163
- AppGeneral.executeSheetCommand(cmd); // runs SocialCalc sheet command synchronously
164
- ```
340
+ ## ๐Ÿ”Œ Plugins & Modules API
341
+
342
+ ### 1. Row & Column Headers (`modules/row-col-headers.js`)
343
+ Enables 123 row numbers and ABCD column headers with interactive column resizing:
344
+ ```ts
345
+ // Enable row/col headers
346
+ AppGeneral.enableRowColHeaders();
347
+
348
+ // Disable row/col headers
349
+ AppGeneral.disableRowColHeaders();
350
+
351
+ // Toggle headers dynamically (returns boolean)
352
+ const isEnabled = AppGeneral.toggleRowColHeaders();
353
+
354
+ // Execute raw SocialCalc commands
355
+ AppGeneral.executeSheetCommand("set A1 text hello");
356
+ ```
165
357
 
166
358
  ### 2. Grid Lines (`modules/grid-lines.js`)
167
- Provides clean, modern cell grid lines across all table cells.
168
- - **API**:
169
- ```ts
170
- AppGeneral.enableGridLines(customCss?: string);
171
- AppGeneral.disableGridLines();
172
- AppGeneral.toggleGridLines(); // returns boolean
173
- AppGeneral.isGridLinesEnabled(); // returns boolean
174
- ```
359
+ Adds subtle, high-contrast borders between cells:
360
+ ```ts
361
+ AppGeneral.enableGridLines();
362
+ AppGeneral.disableGridLines();
363
+ AppGeneral.toggleGridLines();
364
+ ```
175
365
 
176
366
  ### 3. Smooth Touch Scroll (`modules/touch-scroll.js`)
177
- Replaces clunky full-page jumping on mobile swipes with smooth continuous panning and physics-based inertia momentum.
178
- - **API**:
179
- ```ts
180
- AppGeneral.enableTouchScroll();
181
- AppGeneral.disableTouchScroll();
182
- AppGeneral.toggleTouchScroll(); // returns boolean
183
- AppGeneral.isTouchScrollEnabled(); // returns boolean
184
- AppGeneral.configureTouchScroll({ momentumFriction: 0.94 });
185
- ```
186
-
187
- ### 4. Cell Edit Modal (`components/CellEditModal/`)
188
- A responsive, high-feature editing sheet replacing legacy browser prompt popups:
189
- - **Text & Numeric Inputs**: Edit formulas (e.g. `=SUM(B4:C4)`), raw values, or labels.
190
- - **Formatting Presets**: Currency, Percent, Date, Time, Integer.
191
- - **Styling**: Bold, Italic, Alignment (Left, Center, Right).
192
- - **Colors**: 8 curated font colors and 7 cell background colors.
193
- - **Borders**: All, Top, Bottom, Left, Right with Solid/Dashed/Dotted styles and custom widths.
194
- - **Image Insertion**: Embed images into cells with automatic client-side compression (`imageCompressor.ts`).
195
- - **Fallback**: Calling `toggleCellEditModal(false)` automatically falls back to native inline input.
196
-
197
- ### 5. Horizontal Scroll Bar (`components/HorizontalScrollBar.tsx`)
198
- A dedicated, smooth horizontal control bar for navigating wide sheets:
199
- - Step buttons for next/prev columns.
200
- - Draggable slider track with live position indicator.
201
- - Automatically syncs with spreadsheet viewport when user scrolls or uses keyboard navigation.
202
-
203
- ### 6. Row Action Popover (`components/RowActionPopover/`)
204
- Context popup that triggers when user taps a row header:
205
- - **Insert Above**: Calls `executeSheetCommand("insertrow A" + rowNum)`.
206
- - **Insert Below**: Calls `executeSheetCommand("insertrow A" + (rowNum + 1))`.
207
- - **Delete Row**: Calls `executeSheetCommand("deleterow A" + rowNum)`.
208
-
209
- ### 7. Editable Cells Mode & Template Mapping (`modules/editable-cells.js`)
210
- Allows template authors to lock the spreadsheet so end-users can only edit designated cells:
211
- - **API**:
212
- ```ts
213
- AppGeneral.enableEditableCellsOnly();
214
- AppGeneral.disableEditableCellsOnly();
215
- AppGeneral.toggleEditableCellsOnly();
216
- AppGeneral.setAppMapping(mappingObj);
217
- ```
218
-
219
- ### 8. Plugin Manager (`modules/plugin-manager.js`)
220
- Allows developers to register custom plugins with lifecycle hooks:
221
- - **API**:
222
- ```ts
223
- AppGeneral.registerPlugin("myPlugin", {
224
- metadata: { displayName: "My Plugin", description: "Custom feature" },
225
- enable: () => { ... },
226
- disable: () => { ... },
227
- isEnabled: () => true,
228
- toggle: () => { ... },
229
- });
230
- ```
231
-
232
- ### 9. Cell Change & Status Listeners (`modules/listeners.js`)
233
- Safely intercepts cell updates and spreadsheet status cycles:
234
- - **API**:
235
- ```ts
236
- const unsubscribe = AppGeneral.setupCellChangeListener((coord: string) => {
237
- console.log("Cell modified:", coord);
238
- });
239
- ```
240
- - **Forwarding Safety**: Intercepts `SocialCalc.EditorSheetStatusCallback` while preserving all 4 internal parameters (`recalcdata, status, arg, editor`), avoiding undefined context dereference during render routines.
367
+ Adds mobile touch inertia scrolling:
368
+ ```ts
369
+ AppGeneral.enableTouchScroll();
370
+ AppGeneral.configureTouchScroll({
371
+ momentumFriction: 0.94, // adjust friction
372
+ velocityMultiplier: 1.2
373
+ });
374
+ AppGeneral.disableTouchScroll();
375
+ ```
376
+
377
+ ### 4. Horizontal Scroll (`modules/horizontal-scroll.js`)
378
+ Programmatic viewport scrolling:
379
+ ```ts
380
+ // Scroll horizontally by a relative number of columns
381
+ AppGeneral.scrollHorizontalBy(3);
382
+
383
+ // Scroll to a specific target column index (1-based)
384
+ AppGeneral.scrollToColumn(5); // Scrolls to column E
385
+
386
+ // Subscribe to horizontal scroll events
387
+ const unsubscribe = AppGeneral.subscribeHorizontalScroll((info) => {
388
+ console.log("Current first col:", info.currentFirstCol);
389
+ });
390
+ ```
391
+
392
+ ### 5. Editable Cells & Template Locks (`modules/editable-cells.js`)
393
+ Restricts user editing to designated cells while protecting formula and header cells:
394
+ ```ts
395
+ // Enable template protection mode
396
+ AppGeneral.enableEditableCellsOnly();
397
+
398
+ // Define allowed mapping
399
+ AppGeneral.setAppMapping({
400
+ sheet1: {
401
+ customerName: "B3",
402
+ itemsTotal: "D15"
403
+ }
404
+ });
405
+
406
+ // Check if a specific cell coordinate is editable
407
+ const canEdit = AppGeneral.isCellEditable(editor, "B3"); // true
408
+ const isLocked = AppGeneral.isCellEditable(editor, "A1"); // false
409
+ ```
410
+
411
+ ### 6. Plugin Manager (`modules/plugin-manager.js`)
412
+ Allows registration of custom lifecycle plugins:
413
+ ```ts
414
+ AppGeneral.registerPlugin("myCustomPlugin", {
415
+ metadata: {
416
+ displayName: "Audit Logger",
417
+ description: "Logs cell updates to an external service"
418
+ },
419
+ enable: () => console.log("Plugin activated"),
420
+ disable: () => console.log("Plugin deactivated"),
421
+ isEnabled: () => true
422
+ });
423
+ ```
424
+
425
+ ### 7. History (Undo / Redo) (`modules/history.js`)
426
+ ```ts
427
+ AppGeneral.undo();
428
+ AppGeneral.redo();
429
+ ```
430
+
431
+ ### 8. Exporters & Sheets (`modules/exporters.js`, `modules/sheets.js`)
432
+ ```ts
433
+ // Export sheet as CSV string
434
+ const csvData = AppGeneral.getCSVContent();
435
+
436
+ // Export sheet as HTML string
437
+ const htmlContent = AppGeneral.getCurrentHTMLContent();
438
+
439
+ // Get full spreadsheet data (save format / MSC)
440
+ const mscData = AppGeneral.getSpreadsheetContent();
441
+
442
+ // Multi-sheet operations
443
+ AppGeneral.switchSheet("Sheet2");
444
+ AppGeneral.addNewSheet("Expenses");
445
+ AppGeneral.deleteSheet("Sheet3");
446
+ AppGeneral.renameSheet("Sheet1", "Overview");
447
+ ```
448
+
449
+ ### 9. Invoice Utilities (`modules/invoice.js`)
450
+ ```ts
451
+ import { getInvoiceCoordinates } from "socialcalc-ai";
452
+
453
+ const coords = getInvoiceCoordinates();
454
+ // Returns standard coordinates for billTo, from, invoiceDetails, items, totals
455
+ ```
241
456
 
242
457
  ---
243
458
 
244
- ## ๐Ÿ“ก Events Dispatched by SocialCalc
459
+ ## ๐Ÿ“ก Event-Driven Architecture
245
460
 
246
- | Event Name | `detail` Payload | Description |
461
+ `socialcalc-ai` broadcasts standard DOM CustomEvents on the `window` object. This allows any framework (React, Vue, Svelte, Angular, Vanilla JS) to react to spreadsheet changes:
462
+
463
+ | Event Name | `event.detail` Structure | Purpose |
247
464
  | :--- | :--- | :--- |
248
- | `socialcalc:cell-edit-request` | `{ coord, text, okfn, cleanup }` | Dispatched when a cell is clicked/tapped (consumed by `CellEditModal`). |
249
- | `socialcalc:row-header-click` | `{ rowNum, clientX, clientY }` | Dispatched when a row number is clicked (consumed by `RowActionPopover`). |
250
- | `socialcalc:cell-change` | `{ coord, value }` | Dispatched when any cell value is successfully modified. |
251
- | `socialcalc:horizontal-scroll`| `{ currentFirstCol, currentColName, totalCols }` | Dispatched when sheet column scrolls. |
252
- | `socialcalc:plugin-change` | `{ pluginName, state, allStates }` | Dispatched when any plugin is enabled/disabled. |
465
+ | `socialcalc:cell-edit-request` | `{ coord: string, text: string, okfn: Function, cleanup: Function }` | Fired when a cell is clicked/tapped. Consumed by `CellEditModal`. |
466
+ | `socialcalc:row-header-click` | `{ rowNum: number, originalEvent: MouseEvent }` | Fired when a row number index is clicked. Consumed by `RowActionPopover`. |
467
+ | `socialcalc:cell-change` | `{ coord: string, value: string }` | Fired after a cell's value or formula is committed and recalculated. |
468
+ | `socialcalc:horizontal-scroll`| `{ currentFirstCol: number, currentColName: string, totalCols: number }` | Fired whenever the horizontal viewport column changes. |
469
+ | `socialcalc:plugin-change` | `{ pluginName: string, state: boolean, allStates: Record<string, boolean> }` | Fired whenever a plugin is registered, enabled, or disabled. |
470
+
471
+ ### Event Listener Example:
472
+
473
+ ```ts
474
+ window.addEventListener("socialcalc:cell-change", (e: CustomEvent) => {
475
+ const { coord, value } = e.detail;
476
+ console.log(`Cell ${coord} changed to: ${value}`);
477
+ });
478
+ ```
253
479
 
254
480
  ---
255
481
 
256
- ## ๐Ÿงช Testing & Verification
482
+ ## ๐Ÿค– AI & MultiSheet Calc (MSC) Integration
257
483
 
258
- Run tests anytime you modify the package:
259
- ```bash
260
- # Run Vitest test suite
261
- npm test -- --run
484
+ `socialcalc-ai` is built for automated and LLM-driven spreadsheet workflows:
485
+
486
+ ### Generating Spreadsheets via LLMs
487
+ AI agents can generate spreadsheet structures in SocialCalc MSC format (MultiSheet Calc). An MSC document defines multiple named sheets with cell formulas, formats, and values:
488
+
489
+ ```json
490
+ {
491
+ "sheets": {
492
+ "Summary": {
493
+ "content": "cell:A1:t:Quarterly Revenue\ncell:A3:t:Q1\ncell:B3:v:12500\ncell:A4:t:Q2\ncell:B4:v:14200\ncell:A5:t:Total\ncell:B5:v#:=SUM(B3:B4)"
494
+ }
495
+ }
496
+ }
497
+ ```
498
+
499
+ Load this directly into `socialcalc-ai`:
262
500
 
263
- # Run TypeScript compilation & Vite build
264
- npm run build
501
+ ```ts
502
+ import * as AppGeneral from "socialcalc-ai";
503
+
504
+ AppGeneral.loadWorkbookData(aiGeneratedMscJson);
505
+ ```
506
+
507
+ ---
265
508
 
266
- # Verify SocialCalc core modularization in Node
267
- node test-socialcalc.js
509
+ ## ๐Ÿ›ก TypeScript Support
510
+
511
+ `socialcalc-ai` ships with full type definitions in `index.d.ts`:
512
+
513
+ ```ts
514
+ import * as AppGeneral from "socialcalc-ai";
515
+ import {
516
+ CellEditModal,
517
+ CellEditModalProps,
518
+ HorizontalScrollBarProps,
519
+ RowActionPopoverProps
520
+ } from "socialcalc-ai";
268
521
  ```
522
+
523
+ ---
524
+
525
+ ## ๐Ÿ’ป Browser & Framework Compatibility
526
+
527
+ - **Browsers**: Chrome, Edge, Safari, Firefox (Desktop & Mobile).
528
+ - **Frameworks**: React 18+, Ionic React 7+, Next.js (Client Component), Vite, Plain JavaScript.
529
+ - **Runtimes**: Node.js 18+ (for headless calculation & CSV/MSC transformation).
530
+
531
+ ---
532
+
533
+ ## ๐Ÿ“œ License & Acknowledgments
534
+
535
+ - **Original SocialCalc Engine**: Created by Dan Bricklin (co-creator of VisiCalc) and Socialtext.
536
+ - **Modernized `socialcalc-ai` Package**: Maintained and modernized for ES6 modules, React/Ionic UI components, touch physics, and AI workflows by **Anirudh Sharma** under the **MIT License**.
537
+
538
+ Feel free to open issues and pull requests to help enhance the modern spreadsheet engine!
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "socialcalc-ai",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "description": "Modernized, modular spreadsheet calculation engine and React/Ionic UI suite with AI formula and template capabilities.",
5
5
  "type": "module",
6
6
  "main": "index.js",