import export
This commit is contained in:
parent
eb023a40d0
commit
84ef53ae05
5 changed files with 315 additions and 6 deletions
|
@ -1,5 +1,6 @@
|
|||
import { useState } from 'react'
|
||||
import { useState, useRef } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { importChecklistFromJSON } from '../hooks/useLocalStorage'
|
||||
|
||||
interface CreateChecklistProps {
|
||||
className?: string
|
||||
|
@ -8,6 +9,8 @@ interface CreateChecklistProps {
|
|||
export default function CreateChecklist({ className = '' }: CreateChecklistProps) {
|
||||
const [checklistName, setChecklistName] = useState('')
|
||||
const [isCreating, setIsCreating] = useState(false)
|
||||
const [isImporting, setIsImporting] = useState(false)
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
const navigate = useNavigate()
|
||||
|
||||
const createChecklist = async () => {
|
||||
|
@ -46,22 +49,48 @@ export default function CreateChecklist({ className = '' }: CreateChecklistProps
|
|||
}
|
||||
}
|
||||
|
||||
const handleImportChecklist = async (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = event.target.files?.[0]
|
||||
if (!file) return
|
||||
|
||||
setIsImporting(true)
|
||||
try {
|
||||
const newUuid = await importChecklistFromJSON(file)
|
||||
navigate(`/${newUuid}`)
|
||||
} catch (error) {
|
||||
console.error('Error importing checklist:', error)
|
||||
alert('Failed to import checklist. Please check the file format.')
|
||||
} finally {
|
||||
setIsImporting(false)
|
||||
// Reset the file input
|
||||
if (fileInputRef.current) {
|
||||
fileInputRef.current.value = ''
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const triggerFileInput = () => {
|
||||
fileInputRef.current?.click()
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 p-8 ${className}`}>
|
||||
<h2 className="text-2xl font-bold text-gray-900 dark:text-white mb-6">Create New Checklist</h2>
|
||||
<div className="flex flex-col sm:flex-row gap-4">
|
||||
|
||||
{/* Create new checklist section */}
|
||||
<div className="flex flex-col sm:flex-row gap-4 mb-6">
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Enter checklist name..."
|
||||
value={checklistName}
|
||||
onChange={(e) => setChecklistName(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
disabled={isCreating}
|
||||
disabled={isCreating || isImporting}
|
||||
className="flex-1 px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:bg-gray-100 dark:disabled:bg-gray-700 disabled:text-gray-500 dark:disabled:text-gray-400 bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-500 dark:placeholder-gray-400"
|
||||
/>
|
||||
<button
|
||||
onClick={createChecklist}
|
||||
disabled={isCreating || !checklistName.trim()}
|
||||
disabled={isCreating || isImporting || !checklistName.trim()}
|
||||
className="
|
||||
px-8 py-3 bg-blue-600 dark:bg-blue-500 text-white font-medium rounded-lg hover:bg-blue-700 dark:hover:bg-blue-600
|
||||
focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 dark:focus:ring-offset-gray-800 disabled:opacity-50
|
||||
|
@ -71,6 +100,36 @@ export default function CreateChecklist({ className = '' }: CreateChecklistProps
|
|||
{isCreating ? 'Creating...' : 'Create'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Import section */}
|
||||
<div className="border-t border-gray-200 dark:border-gray-700 pt-6">
|
||||
<h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">Import Checklist</h3>
|
||||
<div className="flex flex-col sm:flex-row gap-4">
|
||||
<div className="flex-1">
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400 mb-2">
|
||||
Import a previously exported checklist JSON file
|
||||
</p>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept=".json"
|
||||
onChange={handleImportChecklist}
|
||||
className="hidden"
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
onClick={triggerFileInput}
|
||||
disabled={isCreating || isImporting}
|
||||
className="
|
||||
px-8 py-3 bg-green-600 dark:bg-green-500 text-white font-medium rounded-lg hover:bg-green-700 dark:hover:bg-green-600
|
||||
focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2 dark:focus:ring-offset-gray-800 disabled:opacity-50
|
||||
disabled:cursor-not-allowed transition-colors duration-200
|
||||
"
|
||||
>
|
||||
{isImporting ? '📥 Importing...' : '📥 Import JSON'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
|
@ -1,5 +1,5 @@
|
|||
import { Link } from 'react-router-dom'
|
||||
import { loadSavedChecklists } from '../hooks/useLocalStorage'
|
||||
import { loadSavedChecklists, exportChecklistToJSON } from '../hooks/useLocalStorage'
|
||||
import { useState } from 'react'
|
||||
|
||||
interface SavedChecklistsProps {
|
||||
|
@ -8,12 +8,25 @@ interface SavedChecklistsProps {
|
|||
|
||||
export default function SavedChecklists({ className = '' }: SavedChecklistsProps) {
|
||||
const [savedChecklists, setSavedChecklists] = useState<{ uuid: string; name: string; lastOpened?: string }[]>(loadSavedChecklists())
|
||||
const [exportingChecklist, setExportingChecklist] = useState<string | null>(null)
|
||||
|
||||
const handleForgetCheckList = (uuid: string): void => {
|
||||
const updatedChecklists = savedChecklists.filter((checklist: { uuid: string }) => checklist.uuid !== uuid)
|
||||
localStorage.setItem('gocheck-saved-checklists', JSON.stringify(updatedChecklists))
|
||||
setSavedChecklists(updatedChecklists)
|
||||
}
|
||||
|
||||
const handleExportChecklist = async (uuid: string, name: string): Promise<void> => {
|
||||
setExportingChecklist(uuid)
|
||||
try {
|
||||
await exportChecklistToJSON(uuid, name)
|
||||
} catch (error) {
|
||||
alert('Failed to export checklist')
|
||||
} finally {
|
||||
setExportingChecklist(null)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (savedChecklists.length === 0) {
|
||||
return (
|
||||
|
@ -67,6 +80,14 @@ export default function SavedChecklists({ className = '' }: SavedChecklistsProps
|
|||
>
|
||||
📤 Share
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleExportChecklist(checklist.uuid, checklist.name)}
|
||||
disabled={exportingChecklist === checklist.uuid}
|
||||
className="px-4 py-2 bg-purple-600 dark:bg-purple-500 text-white font-medium rounded-lg hover:bg-purple-700 dark:hover:bg-purple-600 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:ring-offset-2 dark:focus:ring-offset-gray-800 transition-colors duration-200 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
title="Export checklist to JSON"
|
||||
>
|
||||
{exportingChecklist === checklist.uuid ? '📥 Exporting...' : '📥 Export'}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleForgetCheckList(checklist.uuid)}
|
||||
className="px-4 py-2 bg-red-600 dark:bg-red-500 text-white font-medium rounded-lg hover:bg-red-700 dark:hover:bg-red-600 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2 dark:focus:ring-offset-gray-800 transition-colors duration-200"
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
import type { SavedChecklist } from '../types'
|
||||
import type { SavedChecklist, ChecklistItem } from '../types'
|
||||
|
||||
const STORAGE_KEY = 'gocheck-saved-checklists'
|
||||
|
||||
|
@ -43,3 +43,162 @@ export const loadSavedChecklists = (): SavedChecklist[] => {
|
|||
}
|
||||
return []
|
||||
}
|
||||
|
||||
export const exportChecklistToJSON = async (uuid: string, name: string): Promise<void> => {
|
||||
try {
|
||||
const response = await fetch(`/api/checklists/${uuid}/items`)
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to fetch checklist data')
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
if (!data.success || !data.items) {
|
||||
throw new Error('Invalid response format')
|
||||
}
|
||||
|
||||
const exportData = {
|
||||
name: name,
|
||||
uuid: uuid,
|
||||
exportedAt: new Date().toISOString(),
|
||||
items: data.items as ChecklistItem[]
|
||||
}
|
||||
|
||||
const jsonString = JSON.stringify(exportData, null, 2)
|
||||
const blob = new Blob([jsonString], { type: 'application/json' })
|
||||
const url = URL.createObjectURL(blob)
|
||||
|
||||
const link = document.createElement('a')
|
||||
link.href = url
|
||||
link.download = `${name.replace(/[^a-z0-9]/gi, '_').toLowerCase()}_${uuid}.json`
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
document.body.removeChild(link)
|
||||
URL.revokeObjectURL(url)
|
||||
} catch (error) {
|
||||
console.error('Error exporting checklist:', error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
interface ImportData {
|
||||
name: string
|
||||
uuid?: string
|
||||
exportedAt?: string
|
||||
items: ChecklistItem[]
|
||||
}
|
||||
|
||||
export const importChecklistFromJSON = async (file: File): Promise<string> => {
|
||||
try {
|
||||
// Read the file
|
||||
const text = await file.text()
|
||||
const importData: ImportData = JSON.parse(text)
|
||||
|
||||
// Validate the import data
|
||||
if (!importData.name || !importData.items || !Array.isArray(importData.items)) {
|
||||
throw new Error('Invalid import file format')
|
||||
}
|
||||
|
||||
// Create a new checklist
|
||||
const createResponse = await fetch('/api/checklists', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ name: importData.name }),
|
||||
})
|
||||
|
||||
if (!createResponse.ok) {
|
||||
throw new Error('Failed to create checklist')
|
||||
}
|
||||
|
||||
const createData = await createResponse.json()
|
||||
if (!createData.success || !createData.uuid) {
|
||||
throw new Error('Invalid response from checklist creation')
|
||||
}
|
||||
|
||||
const newUuid = createData.uuid
|
||||
|
||||
// Create a mapping from old item IDs to new item IDs
|
||||
const idMapping = new Map<number, number>()
|
||||
|
||||
// First pass: Add all items and build the ID mapping
|
||||
for (const item of importData.items) {
|
||||
const addItemResponse = await fetch(`/api/checklists/${newUuid}/items`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
content: item.content,
|
||||
parent_id: null, // We'll handle parent relationships in the second pass
|
||||
not_before: item.not_before,
|
||||
not_after: item.not_after,
|
||||
}),
|
||||
})
|
||||
|
||||
if (!addItemResponse.ok) {
|
||||
throw new Error(`Failed to add item: ${item.content}`)
|
||||
}
|
||||
|
||||
const addItemData = await addItemResponse.json()
|
||||
if (!addItemData.success || !addItemData.item) {
|
||||
throw new Error(`Invalid response when adding item: ${item.content}`)
|
||||
}
|
||||
|
||||
const newItemId = addItemData.item.id
|
||||
idMapping.set(item.id, newItemId)
|
||||
}
|
||||
|
||||
// Second pass: Update parent relationships and dependencies
|
||||
for (const item of importData.items) {
|
||||
const newItemId = idMapping.get(item.id)
|
||||
if (!newItemId) continue
|
||||
|
||||
const updates: Partial<ChecklistItem> = {}
|
||||
|
||||
// Handle parent relationships
|
||||
if (item.parent_id !== null) {
|
||||
const newParentId = idMapping.get(item.parent_id)
|
||||
if (newParentId) {
|
||||
updates.parent_id = newParentId
|
||||
}
|
||||
}
|
||||
|
||||
// Handle dependencies
|
||||
if (item.dependencies && item.dependencies.length > 0) {
|
||||
const newDependencies = item.dependencies
|
||||
.map(oldDepId => idMapping.get(oldDepId))
|
||||
.filter(newDepId => newDepId !== undefined) as number[]
|
||||
|
||||
if (newDependencies.length > 0) {
|
||||
updates.dependencies = newDependencies
|
||||
}
|
||||
}
|
||||
|
||||
// Update item if it was checked in the original
|
||||
if (item.checked) {
|
||||
updates.checked = true
|
||||
}
|
||||
|
||||
// Apply updates if there are any
|
||||
if (Object.keys(updates).length > 0) {
|
||||
const updateResponse = await fetch(`/api/checklists/${newUuid}/items/${newItemId}`, {
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(updates),
|
||||
})
|
||||
|
||||
if (!updateResponse.ok) {
|
||||
console.warn(`Failed to update item: ${item.content}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return newUuid
|
||||
} catch (error) {
|
||||
console.error('Error importing checklist:', error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
|
|
@ -3,6 +3,7 @@ import { useParams, Link } from 'react-router-dom'
|
|||
import { useSSE } from '../hooks/useSSE'
|
||||
import ChecklistItem from '../components/ChecklistItem'
|
||||
import { EditableTitle } from '../components/EditableTitle'
|
||||
import { exportChecklistToJSON } from '../hooks/useLocalStorage'
|
||||
import type { ChecklistItem as ChecklistItemType } from '../types'
|
||||
|
||||
interface ItemGroup {
|
||||
|
@ -19,6 +20,7 @@ export default function Checklist() {
|
|||
const [newItemContent, setNewItemContent] = useState('')
|
||||
const [isAddingItem, setIsAddingItem] = useState(false)
|
||||
const [completedItemsCollapsed, setCompletedItemsCollapsed] = useState(false)
|
||||
const [isExporting, setIsExporting] = useState(false)
|
||||
|
||||
|
||||
const buildItemTree = (items: ChecklistItemType[]): ChecklistItemType[] => {
|
||||
|
@ -232,6 +234,19 @@ export default function Checklist() {
|
|||
}
|
||||
}
|
||||
|
||||
const handleExportChecklist = async () => {
|
||||
if (!uuid || !checkListName) return
|
||||
|
||||
setIsExporting(true)
|
||||
try {
|
||||
await exportChecklistToJSON(uuid, checkListName)
|
||||
} catch (error) {
|
||||
alert('Failed to export checklist')
|
||||
} finally {
|
||||
setIsExporting(false)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
const renderGroupedItems = (allItems: ChecklistItemType[]) => {
|
||||
|
@ -377,6 +392,14 @@ export default function Checklist() {
|
|||
/>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
onClick={handleExportChecklist}
|
||||
disabled={isExporting || !isConnected}
|
||||
className="px-3 py-1 bg-purple-600 dark:bg-purple-500 text-white font-medium rounded-lg hover:bg-purple-700 dark:hover:bg-purple-600 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:ring-offset-2 dark:focus:ring-offset-gray-800 transition-colors duration-200 disabled:opacity-50 disabled:cursor-not-allowed text-sm"
|
||||
title="Export checklist to JSON"
|
||||
>
|
||||
{isExporting ? '📥 Exporting...' : '📥 Export'}
|
||||
</button>
|
||||
{isConnected ? (
|
||||
<span className="flex items-center gap-2 text-green-600 dark:text-green-400 bg-green-50 dark:bg-green-900/30 px-2 py-0.5 rounded-full text-sm font-medium">
|
||||
<span className="w-2 h-2 bg-green-500 rounded-full"></span>
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue