feat: wire up real-time collaboration and document sharing

- CalcEditor: accept ytext + awareness props for Y.js collaborative editing
  with remote cursors via yCollab
- App: integrate share button, CollabIndicator, route handling for /s/{token}
- App: create cloud documents on share, resolve share tokens on open
- Share button visible when authenticated, opens ShareDialog

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-03-19 17:48:31 -04:00
parent 808fe07117
commit e9fd8b7c9b
3 changed files with 232 additions and 51 deletions

View File

@@ -3,9 +3,10 @@
*
* Workspace layout: header → tab bar → editor + results panel.
* Multi-document support via document store with localStorage persistence.
* Supports real-time collaboration via Y.js when authenticated.
*/
import { useCallback, useState, useRef, useEffect } from 'react'
import { useCallback, useState, useRef, useEffect, useMemo } from 'react'
import type { EditorView } from '@codemirror/view'
import { CalcEditor } from './editor/CalcEditor.tsx'
import { useEngine } from './engine/useEngine.ts'
@@ -28,8 +29,16 @@ import { useFontSize } from './hooks/useFontSize.ts'
import { MobileResultsTray } from './components/MobileResultsTray.tsx'
import { UserMenu } from './components/UserMenu.tsx'
import { SecuritySettings } from './components/SecuritySettings.tsx'
import { CollabIndicator } from './components/CollabIndicator.tsx'
import { useAuth } from './auth/AuthProvider.tsx'
import { AuthModal } from './auth/AuthModal.tsx'
import { ShareDialog } from './sharing/ShareDialog.tsx'
import { useShareToken } from './sharing/useShareToken.ts'
import { useCloudSync } from './sync/useCloudSync.ts'
import { useYDoc } from './collab/useYDoc.ts'
import { useWebSocketProvider } from './collab/useWebSocketProvider.ts'
import { getUserColor, getDisplayName } from './collab/awareness.ts'
import { useRoute, navigate } from './router/useRoute.ts'
import './styles/app.css'
function App() {
@@ -40,9 +49,13 @@ function App() {
const fontSizeCtx = useFontSize()
const auth = useAuth()
const store = useDocumentStore()
const cloudSync = useCloudSync()
const route = useRoute()
const { resolveShareToken } = useShareToken()
const [showAuthModal, setShowAuthModal] = useState(false)
const [showSecuritySettings, setShowSecuritySettings] = useState(false)
const [showShareDialog, setShowShareDialog] = useState(false)
const [editorView, setEditorView] = useState<EditorView | null>(null)
const resultsPanelRef = useRef<HTMLDivElement>(null)
@@ -51,6 +64,10 @@ function App() {
const [resultsAlign, setResultsAlign] = useState<Alignment>('right')
const [formatPreview, setFormatPreview] = useState(true)
// Cloud document tracking
const [cloudDocId, setCloudDocId] = useState<string | null>(null)
const [sharedDocTitle, setSharedDocTitle] = useState<string | null>(null)
// Sidebar state
const [sidebarState, setSidebarState] = useState(loadSidebarState)
const setSidebarVisible = useCallback((v: boolean) => {
@@ -71,29 +88,85 @@ function App() {
const [dividerX, setDividerX] = useState<number | null>(null)
const isDragging = useRef(false)
// --- Collaboration setup ---
const collabDocId = cloudDocId ?? (route.type === 'shared' ? route.token : null)
const { ytext, ready: ydocReady, initContent } = useYDoc(collabDocId)
const userName = useMemo(() => getDisplayName(auth.user?.email), [auth.user?.email])
const userColor = useMemo(() => getUserColor(auth.user?.id ?? 'anon'), [auth.user?.id])
const { awareness, connected, peerCount } = useWebSocketProvider({
ydoc: collabDocId ? (ytext as any)?.doc ?? null : null,
roomName: collabDocId ? `doc:${collabDocId}` : null,
token: auth.session?.access_token ?? null,
userName,
userColor,
})
const isCollaborating = !!collabDocId && !!ytext && ydocReady
// Initialize Y.Doc with current content when starting collaboration
useEffect(() => {
if (isCollaborating && store.activeDoc) {
initContent(store.activeDoc.content)
}
}, [isCollaborating]) // eslint-disable-line react-hooks/exhaustive-deps
// --- Handle shared document route ---
useEffect(() => {
if (route.type !== 'shared') return
resolveShareToken(route.token).then(info => {
if (info) {
setCloudDocId(info.id)
setSharedDocTitle(info.title)
}
})
}, [route]) // eslint-disable-line react-hooks/exhaustive-deps
// --- Share current document ---
const handleShare = useCallback(async () => {
if (!auth.isAuthenticated || !store.activeDoc) {
setShowAuthModal(true)
return
}
// Create cloud document if not exists
if (!cloudDocId) {
const cloudDoc = await cloudSync.createCloudDocument(store.activeDoc.title)
if (cloudDoc) {
setCloudDocId(cloudDoc.id)
}
}
setShowShareDialog(true)
}, [auth.isAuthenticated, store.activeDoc, cloudDocId, cloudSync])
const handleDocChange = useCallback(
(lines: string[]) => {
engine.evalSheet(lines)
// Persist content
const content = lines.join('\n')
if (store.activeDoc && content !== store.activeDoc.content) {
store.updateContent(store.activeTabId, content)
setModifiedIds(prev => {
const next = new Set(prev)
next.add(store.activeTabId)
return next
})
// Clear modified dot after save debounce
setTimeout(() => {
// Persist content (only in non-shared mode)
if (route.type !== 'shared') {
const content = lines.join('\n')
if (store.activeDoc && content !== store.activeDoc.content) {
store.updateContent(store.activeTabId, content)
setModifiedIds(prev => {
const next = new Set(prev)
next.delete(store.activeTabId)
next.add(store.activeTabId)
return next
})
}, 500)
// Clear modified dot after save debounce
setTimeout(() => {
setModifiedIds(prev => {
const next = new Set(prev)
next.delete(store.activeTabId)
return next
})
}, 500)
}
}
},
[engine.evalSheet, store.activeTabId, store.activeDoc, store.updateContent],
[engine.evalSheet, store.activeTabId, store.activeDoc, store.updateContent, route.type],
)
// Switch tabs
@@ -101,20 +174,23 @@ function App() {
if (id === store.activeTabId) return
store.setActiveTab(id)
setEditorKey(id)
}, [store.activeTabId, store.setActiveTab])
setCloudDocId(null) // Reset collab when switching tabs
if (route.type === 'shared') navigate('/')
}, [store.activeTabId, store.setActiveTab, route.type])
// New document
const handleNewTab = useCallback(() => {
const doc = store.createDocument()
setEditorKey(doc.id)
}, [store.createDocument])
setCloudDocId(null)
if (route.type === 'shared') navigate('/')
}, [store.createDocument, route.type])
// Close tab
const handleTabClose = useCallback((id: string) => {
store.closeTab(id)
// If we closed the active tab, editorKey needs updating
if (id === store.activeTabId) {
// State will update, trigger effect below
setCloudDocId(null)
}
}, [store.closeTab, store.activeTabId])
@@ -253,6 +329,8 @@ function App() {
? { flex: 1 }
: {}
const docTitle = sharedDocTitle ?? store.activeDoc?.title ?? 'Untitled'
return (
<div className="calcpad-app">
<OfflineBanner isOnline={isOnline} />
@@ -287,6 +365,24 @@ function App() {
min={fontSizeCtx.MIN_SIZE}
max={fontSizeCtx.MAX_SIZE}
/>
{isCollaborating && (
<CollabIndicator connected={connected} peerCount={peerCount} />
)}
{auth.isAuthenticated && (
<button
className="header-share-btn"
onClick={handleShare}
title="Share document"
>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<circle cx="18" cy="5" r="3" />
<circle cx="6" cy="12" r="3" />
<circle cx="18" cy="19" r="3" />
<line x1="8.59" y1="13.51" x2="15.42" y2="17.49" />
<line x1="15.41" y1="6.51" x2="8.59" y2="10.49" />
</svg>
</button>
)}
<ThemePicker
theme={themeCtx.theme}
resolvedTheme={themeCtx.resolvedTheme}
@@ -351,6 +447,8 @@ function App() {
debounceMs={50}
onViewReady={setEditorView}
formatPreview={formatPreview}
ytext={isCollaborating ? ytext : null}
awareness={isCollaborating ? awareness : null}
/>
</div>
<div
@@ -398,6 +496,16 @@ function App() {
{showSecuritySettings && (
<SecuritySettings onClose={() => setShowSecuritySettings(false)} />
)}
{showShareDialog && cloudDocId && (
<ShareDialog
documentId={cloudDocId}
documentTitle={docTitle}
currentShareToken={null}
currentSharePermission={null}
onClose={() => setShowShareDialog(false)}
/>
)}
</div>
)
}