This commit is contained in:
2025-11-14 14:47:26 +00:00
parent 69ecf2c7c1
commit 3b4876793e
104 changed files with 231517 additions and 1029 deletions
@@ -57,7 +57,7 @@ export const CalendarComponent: React.FC<CalendarComponentProps> = ({ shape }) =
try {
const fetchedEvents = await TimetableNeoDBService.fetchTeacherTimetableEvents(
workerNode.nodeData.unique_id,
workerNode.nodeData.uuid_string,
workerDbName || ''
);
@@ -134,13 +134,13 @@ export const EventDetailsDialog = ({
setFileLoadingState
}: EventDetailsDialogProps) => {
const handleOpenFile = () => {
if (!selectedEvent?.extendedProps?.tldraw_snapshot || !workerDbName) {
if (!selectedEvent?.extendedProps?.node_storage_path || !workerDbName) {
console.error('❌ Failed to open tldraw file - missing snapshot or db name')
return
}
onOpenFile(
selectedEvent.extendedProps.tldraw_snapshot,
selectedEvent.extendedProps.node_storage_path,
workerDbName,
editor,
setFileLoadingState
@@ -166,7 +166,7 @@ export const EventDetailsDialog = ({
<p style={{color: 'red'}}>Error: {fileLoadingState.error}</p>
)}
{selectedEvent.extendedProps?.tldraw_snapshot && fileLoadingState.status !== 'loading' && (
{selectedEvent.extendedProps?.node_storage_path && fileLoadingState.status !== 'loading' && (
<TldrawUiButton type="normal" onClick={handleOpenFile}>
<TldrawUiButtonLabel>
Open Tldraw File <FaExternalLinkAlt style={{ marginLeft: '8px' }} />
@@ -32,19 +32,19 @@ export class CCSchoolNodeShapeUtil extends CCBaseShapeUtil<CCSchoolNodeShape> {
<div style={styles.container}>
<NodeProperty
label="School Name"
value={shape.props.school_name}
value={shape.props.name}
labelStyle={styles.property.label}
valueStyle={styles.property.value}
/>
<NodeProperty
label="School Website"
value={shape.props.school_website}
value={shape.props.website}
labelStyle={styles.property.label}
valueStyle={styles.property.value}
/>
<NodeProperty
label="School UUID"
value={shape.props.school_uuid}
value={shape.props.uuid_string}
labelStyle={styles.property.label}
valueStyle={styles.property.value}
/>
@@ -51,12 +51,12 @@ export class CCTeacherNodeShapeUtil extends CCBaseShapeUtil<CCTeacherNodeShape>
{ label: 'Teacher Name', value: props.teacher_name_formal },
{ label: 'Teacher Code', value: props.teacher_code },
{ label: 'Email', value: props.teacher_email },
{ label: 'Node Snapshot', value: props.tldraw_snapshot }
{ label: 'Node Snapshot', value: props.node_storage_path }
]
return (
<div style={styles.container}>
{defaultComponent && <DefaultNodeComponent tldraw_snapshot={props.tldraw_snapshot} />}
{defaultComponent && <DefaultNodeComponent node_storage_path={props.node_storage_path} />}
{properties.map((prop, index) => (
<div key={index} style={styles.property.wrapper}>
<span style={styles.property.label}>{prop.label}:</span>
@@ -51,7 +51,7 @@ export class CCUserNodeShapeUtil extends CCBaseShapeUtil<CCUserNodeShape> {
{ label: 'User Email', value: props.user_email },
{ label: 'User Type', value: props.user_type },
{ label: 'User ID', value: props.user_id },
{ label: 'Node Snapshot', value: props.tldraw_snapshot },
{ label: 'Node Snapshot', value: props.node_storage_path },
{ label: 'Worker Node Data', value: props.worker_node_data }
] : [
{ label: 'User Name', value: props.user_name },
@@ -60,7 +60,7 @@ export class CCUserNodeShapeUtil extends CCBaseShapeUtil<CCUserNodeShape> {
return (
<div style={styles.container}>
{defaultComponent && <DefaultNodeComponent tldraw_snapshot={props.tldraw_snapshot} />}
{defaultComponent && <DefaultNodeComponent node_storage_path={props.node_storage_path} />}
{properties.map((prop, index) => (
<div key={index} style={styles.property.wrapper}>
<span style={styles.property.label}>{prop.label}:</span>
@@ -1,23 +1,23 @@
import { CCBaseShapeUtil } from '../CCBaseShapeUtil'
import { CCBaseShape } from '../cc-types'
import { NodeProperty, formatDate } from './cc-graph-shared'
import { ccGraphShapeProps, getDefaultCCUserTimetableLessonNodeProps } from './cc-graph-props'
import { ccGraphShapeProps, getDefaultCCTimetableLessonNodeProps } from './cc-graph-props'
import { getNodeStyles } from './cc-graph-styles'
import { NODE_THEMES, NODE_TYPE_THEMES } from './cc-graph-styles'
import { CCUserTimetableLessonNodeProps } from './cc-graph-types'
import { CCTimetableLessonNodeProps } from './cc-graph-types'
export interface CCUserTimetableLessonNodeShape extends CCBaseShape {
export interface CCTimetableLessonNodeShape extends CCBaseShape {
type: 'cc-user-timetable-lesson-node'
props: CCUserTimetableLessonNodeProps
props: CCTimetableLessonNodeProps
}
export class CCUserTimetableLessonNodeShapeUtil extends CCBaseShapeUtil<CCUserTimetableLessonNodeShape> {
export class CCTimetableLessonNodeShapeUtil extends CCBaseShapeUtil<CCTimetableLessonNodeShape> {
static type = 'cc-user-timetable-lesson-node' as const
static props = ccGraphShapeProps['cc-user-timetable-lesson-node']
getDefaultProps(): CCUserTimetableLessonNodeShape['props'] {
const defaultProps = getDefaultCCUserTimetableLessonNodeProps() as CCUserTimetableLessonNodeShape['props']
const theme = NODE_THEMES[NODE_TYPE_THEMES[CCUserTimetableLessonNodeShapeUtil.type]]
getDefaultProps(): CCTimetableLessonNodeShape['props'] {
const defaultProps = getDefaultCCTimetableLessonNodeProps() as CCTimetableLessonNodeShape['props']
const theme = NODE_THEMES[NODE_TYPE_THEMES[CCTimetableLessonNodeShapeUtil.type]]
return {
...defaultProps,
headerColor: theme.headerColor,
@@ -27,7 +27,7 @@ export class CCUserTimetableLessonNodeShapeUtil extends CCBaseShapeUtil<CCUserTi
// Override to nullify the default node component
DefaultComponent = () => null
renderContent = (shape: CCUserTimetableLessonNodeShape) => {
renderContent = (shape: CCTimetableLessonNodeShape) => {
const styles = getNodeStyles(shape.type)
return (
@@ -14,8 +14,8 @@ const stateProps = T.object({
const graphBaseProps = {
...baseShapeProps,
__primarylabel__: T.string,
unique_id: T.string,
tldraw_snapshot: T.string,
uuid_string: T.string,
node_storage_path: T.string,
created: T.string,
merged: T.string,
state: T.optional(stateProps.nullable()),
@@ -84,9 +84,8 @@ export const ccGraphShapeProps = {
},
'cc-school-node': {
...graphBaseProps,
school_uuid: T.string,
school_name: T.string,
school_website: T.string,
name: T.string,
website: T.string,
},
'cc-department-node': {
...graphBaseProps,
@@ -283,8 +282,8 @@ export const getDefaultBaseProps = () => ({
backgroundColor: '#f0f0f0' as string,
title: 'Untitled' as string,
isLocked: false as boolean,
unique_id: '' as string,
tldraw_snapshot: '' as string,
uuid_string: '' as string,
node_storage_path: '' as string,
created: '' as string,
merged: '' as string,
state: {
@@ -383,9 +382,8 @@ export const getDefaultCCSchoolNodeProps = () => ({
...getDefaultBaseProps(),
title: 'School',
__primarylabel__: 'School',
school_uuid: '',
school_name: '',
school_website: '',
name: '',
website: '',
})
export const getDefaultCCDepartmentNodeProps = () => ({
@@ -642,16 +640,3 @@ export const getDefaultCCUserTeacherTimetableNodeProps = () => ({
school_db_name: '',
school_timetable_id: '',
})
export const getDefaultCCUserTimetableLessonNodeProps = () => ({
...getDefaultBaseProps(),
title: 'User Timetable Lesson',
__primarylabel__: 'UserTimetableLesson',
subject_class: '',
date: '',
start_time: '',
end_time: '',
period_code: '',
school_db_name: '',
school_period_id: '',
})
@@ -35,7 +35,7 @@ import { CCTimetableLessonNodeShape, CCTimetableLessonNodeShapeUtil } from './CC
import { CCPlannedLessonNodeShape, CCPlannedLessonNodeShapeUtil } from './CCPlannedLessonNodeShapeUtil'
import { CCDepartmentStructureNodeShape, CCDepartmentStructureNodeShapeUtil } from './CCDepartmentStructureNodeShapeUtil'
import { CCUserTeacherTimetableNodeShape, CCUserTeacherTimetableNodeShapeUtil } from './CCUserTeacherTimetableNodeShapeUtil'
import { CCUserTimetableLessonNodeShape, CCUserTimetableLessonNodeShapeUtil } from './CCUserTimetableLessonNodeShapeUtil'
import { CCTimetableLessonNodeShape, CCTimetableLessonNodeShapeUtil } from './CCTimetableLessonNodeShapeUtil'
// Create a const object with all node types
export const NODE_SHAPE_TYPES = {
@@ -75,7 +75,7 @@ export const NODE_SHAPE_TYPES = {
PLANNED_LESSON: CCPlannedLessonNodeShapeUtil.type,
DEPARTMENT_STRUCTURE: CCDepartmentStructureNodeShapeUtil.type,
USER_TEACHER_TIMETABLE: CCUserTeacherTimetableNodeShapeUtil.type,
USER_TIMETABLE_LESSON: CCUserTimetableLessonNodeShapeUtil.type,
USER_TIMETABLE_LESSON: CCTimetableLessonNodeShapeUtil.type,
} as const;
// Create the type from the const object's values
@@ -119,7 +119,7 @@ export type AllNodeShapes =
| CCPlannedLessonNodeShape
| CCDepartmentStructureNodeShape
| CCUserTeacherTimetableNodeShape
| CCUserTimetableLessonNodeShape;
| CCTimetableLessonNodeShape;
// Export all shape utils in an object for easy access
export const ShapeUtils = {
@@ -159,7 +159,7 @@ export const ShapeUtils = {
[CCPlannedLessonNodeShapeUtil.type]: CCPlannedLessonNodeShapeUtil,
[CCDepartmentStructureNodeShapeUtil.type]: CCDepartmentStructureNodeShapeUtil,
[CCUserTeacherTimetableNodeShapeUtil.type]: CCUserTeacherTimetableNodeShapeUtil,
[CCUserTimetableLessonNodeShapeUtil.type]: CCUserTimetableLessonNodeShapeUtil,
[CCTimetableLessonNodeShapeUtil.type]: CCTimetableLessonNodeShapeUtil,
} as const;
// Add a type guard to check if a shape is a valid node shape
@@ -177,8 +177,8 @@ export const checkDefaultComponent = (defaultComponent: boolean | { action: { la
// Base component for all graph nodes
interface DefaultNodeComponentProps {
tldraw_snapshot: string
onInspect?: (tldraw_snapshot: string) => void
node_storage_path: string
onInspect?: (node_storage_path: string) => void
customAction?: {
label: string
handler: () => void
@@ -186,13 +186,13 @@ interface DefaultNodeComponentProps {
}
export const DefaultNodeComponent: React.FC<DefaultNodeComponentProps> = ({
tldraw_snapshot,
onInspect = () => console.log(`Inspecting node at path: ${tldraw_snapshot}`),
node_storage_path,
onInspect = () => console.log(`Inspecting node at path: ${node_storage_path}`),
customAction
}) => {
return (
<div style={SHARED_NODE_STYLES.defaultComponent.container}>
<button style={SHARED_NODE_STYLES.defaultComponent.button} onClick={() => onInspect(tldraw_snapshot)}>
<button style={SHARED_NODE_STYLES.defaultComponent.button} onClick={() => onInspect(node_storage_path)}>
Inspect
</button>
{customAction && (
@@ -15,8 +15,8 @@ export interface ShapeState {
export type CCGraphShapeProps = CCBaseProps & {
__primarylabel__: string
unique_id: string
tldraw_snapshot: string
uuid_string: string
node_storage_path: string
created: string
merged: string
state: ShapeState | null | undefined
@@ -26,8 +26,8 @@ export type CCGraphShapeProps = CCBaseProps & {
// Define the base shape type for graph shapes
export type CCGraphShape = CCBaseShape & TLBaseShape<GraphShapeType, {
__primarylabel__: CCGraphShapeProps['__primarylabel__']
unique_id: CCGraphShapeProps['unique_id']
tldraw_snapshot: CCGraphShapeProps['tldraw_snapshot']
uuid_string: CCGraphShapeProps['uuid_string']
node_storage_path: CCGraphShapeProps['node_storage_path']
created: CCGraphShapeProps['created']
merged: CCGraphShapeProps['merged']
state: CCGraphShapeProps['state']
@@ -95,9 +95,8 @@ export type CCCalendarTimeChunkNodeProps = CCGraphShapeProps & {
}
export type CCSchoolNodeProps = CCGraphShapeProps & {
school_uuid: string
school_name: string
school_website: string
name: string
website: string
}
export type CCDepartmentNodeProps = CCGraphShapeProps & {
@@ -195,14 +194,6 @@ export type CCTeacherTimetableNodeProps = CCGraphShapeProps & {
end_date: string
}
export type CCTimetableLessonNodeProps = CCGraphShapeProps & {
subject_class: string
date: string
start_time: string
end_time: string
period_code: string
}
export type CCPlannedLessonNodeProps = CCGraphShapeProps & {
date: string
start_time: string
@@ -277,7 +268,7 @@ export type CCUserTeacherTimetableNodeProps = CCGraphShapeProps & {
school_timetable_id: string
}
export type CCUserTimetableLessonNodeProps = CCGraphShapeProps & {
export type CCTimetableLessonNodeProps = CCGraphShapeProps & {
subject_class: string
date: string
start_time: string
@@ -324,7 +315,7 @@ export type CCNodeTypes = {
SubjectClass: { props: CCSubjectClassNodeProps }
DepartmentStructure: { props: CCDepartmentStructureNodeProps }
UserTeacherTimetable: { props: CCUserTeacherTimetableNodeProps }
UserTimetableLesson: { props: CCUserTimetableLessonNodeProps }
UserTimetableLesson: { props: CCTimetableLessonNodeProps }
}
// Helper function to get shape type from node type
@@ -334,7 +325,7 @@ export const getShapeType = (nodeType: keyof CCNodeTypes): string => {
// Helper function to get allowed props from node type
export const getAllowedProps = (): string[] => {
return ['__primarylabel__', 'unique_id'];
return ['__primarylabel__', 'uuid_string'];
}
// Helper function to get node configuration
@@ -52,7 +52,7 @@ export const graphState = {
const updatedShapeIds: string[] = [];
nodes.forEach((node, index) => {
if (!node.props?.unique_id) return;
if (!node.props?.uuid_string) return;
const row = Math.floor(index / gridColumns);
const col = index % gridColumns;
@@ -60,13 +60,13 @@ export const graphState = {
const x = startX + (col * (GRID_CELL_SIZE + GRID_PADDING));
const y = startY + (row * (GRID_CELL_SIZE + GRID_PADDING));
const shapeId = createShapeId(node.props.unique_id);
const shapeId = createShapeId(node.props.uuid_string);
updatedShapeIds.push(shapeId.toString());
// Update both our internal state and the editor
node.x = x;
node.y = y;
graphState.nodeData.set(node.props.unique_id, node);
graphState.nodeData.set(node.props.uuid_string, node);
// Only create if the shape doesn't exist in our tracking
if (!graphState.shapeIds.has(shapeId.toString())) {
@@ -123,12 +123,12 @@ export const graphState = {
addNode: (shape: AllNodeShapes) => {
logger.debug('graphStateUtil', '🔍 Adding shape to graphState:', { shape });
if (!shape.props?.unique_id || !shape.type) {
if (!shape.props?.uuid_string || !shape.type) {
logger.error('graphStateUtil', '❌ Invalid shape data', { shape });
return;
}
const id = shape.props.unique_id;
const id = shape.props.uuid_string;
const shapeId = createShapeId(id).toString();
// Track the shape ID
@@ -208,7 +208,7 @@ export const graphState = {
getShapeByUniqueId: (uniqueId: string) => {
return Array.from(graphState.nodeData.values()).find(
shape => shape.props?.unique_id === uniqueId
shape => shape.props?.uuid_string === uniqueId
);
},
+91 -190
View File
@@ -1,246 +1,147 @@
import { TLRecord, TLShape } from '@tldraw/tldraw'
import { createShapePropsMigrationIds, createShapePropsMigrationSequence, createBindingPropsMigrationIds, createBindingPropsMigrationSequence } from '@tldraw/tldraw'
import { getDefaultCCBaseProps, getDefaultCCCalendarProps, getDefaultCCLiveTranscriptionProps, getDefaultCCSettingsProps, getDefaultCCSlideProps, getDefaultCCSlideShowProps, getDefaultCCSlideLayoutBindingProps, getDefaultCCYoutubeEmbedProps, getDefaultCCSearchProps, getDefaultCCWebBrowserProps } from './cc-props'
// Export both shape and binding migrations
export const ccBindingMigrations = {
'cc-slide-layout': {
firstVersion: 1,
currentVersion: 1,
migrators: {
1: {
up: (record: TLRecord) => {
if (record.typeName !== 'binding') return record
if (record.type !== 'cc-slide-layout') return record
'cc-slide-layout': createBindingPropsMigrationSequence({
sequence: [
{
id: createBindingPropsMigrationIds('cc-slide-layout', { Initial: 1 }).Initial,
up: (props: Record<string, unknown>) => {
return {
...record,
props: {
...getDefaultCCSlideLayoutBindingProps(),
...record.props,
},
...getDefaultCCSlideLayoutBindingProps(),
...props,
}
},
down: (record: TLRecord) => {
return record
},
},
},
},
],
}),
}
export const ccShapeMigrations = {
base: {
firstVersion: 1,
currentVersion: 1,
migrators: {
1: {
up: (record: TLRecord) => {
if (record.typeName !== 'shape') return record
const shape = record as TLShape
if (shape.type !== 'cc-base') return record
base: createShapePropsMigrationSequence({
sequence: [
{
id: createShapePropsMigrationIds('cc-base', { Initial: 1 }).Initial,
up: (props: Record<string, unknown>) => {
return {
...shape,
props: {
...getDefaultCCBaseProps(),
...shape.props,
},
...getDefaultCCBaseProps(),
...props,
}
},
down: (record: TLRecord) => {
return record
},
},
},
},
],
}),
calendar: {
firstVersion: 1,
currentVersion: 1,
migrators: {
1: {
up: (record: TLRecord) => {
if (record.typeName !== 'shape') return record
const shape = record as TLShape
if (shape.type !== 'cc-calendar') return record
calendar: createShapePropsMigrationSequence({
sequence: [
{
id: createShapePropsMigrationIds('cc-calendar', { Initial: 1 }).Initial,
up: (props: Record<string, unknown>) => {
return {
...shape,
props: {
...getDefaultCCCalendarProps(),
...shape.props,
},
...getDefaultCCCalendarProps(),
...props,
}
},
down: (record: TLRecord) => {
return record
},
},
},
},
],
}),
liveTranscription: {
firstVersion: 1,
currentVersion: 1,
migrators: {
1: {
up: (record: TLRecord) => {
if (record.typeName !== 'shape') return record
const shape = record as TLShape
if (shape.type !== 'cc-live-transcription') return record
liveTranscription: createShapePropsMigrationSequence({
sequence: [
{
id: createShapePropsMigrationIds('cc-live-transcription', { Initial: 1 }).Initial,
up: (props: Record<string, unknown>) => {
return {
...shape,
props: {
...getDefaultCCLiveTranscriptionProps(),
...shape.props,
},
...getDefaultCCLiveTranscriptionProps(),
...props,
}
},
down: (record: TLRecord) => {
return record
},
},
},
},
],
}),
settings: {
firstVersion: 1,
currentVersion: 1,
migrators: {
1: {
up: (record: TLRecord) => {
if (record.typeName !== 'shape') return record
const shape = record as TLShape
if (shape.type !== 'cc-settings') return record
settings: createShapePropsMigrationSequence({
sequence: [
{
id: createShapePropsMigrationIds('cc-settings', { Initial: 1 }).Initial,
up: (props: Record<string, unknown>) => {
return {
...shape,
props: {
...getDefaultCCSettingsProps(),
...shape.props,
},
...getDefaultCCSettingsProps(),
...props,
}
},
down: (record: TLRecord) => {
return record
},
},
},
},
],
}),
slideshow: {
firstVersion: 1,
currentVersion: 1,
migrators: {
1: {
up: (record: TLRecord) => {
if (record.typeName !== 'shape') return record
const shape = record as TLShape
if (shape.type !== 'cc-slideshow') return record
slideshow: createShapePropsMigrationSequence({
sequence: [
{
id: createShapePropsMigrationIds('cc-slideshow', { Initial: 1 }).Initial,
up: (props: Record<string, unknown>) => {
return {
...shape,
props: {
...getDefaultCCSlideShowProps(),
...shape.props,
},
...getDefaultCCSlideShowProps(),
...props,
}
},
down: (record: TLRecord) => {
return record
},
},
},
},
],
}),
slide: {
firstVersion: 1,
currentVersion: 1,
migrators: {
1: {
up: (record: TLRecord) => {
if (record.typeName !== 'shape') return record
const shape = record as TLShape
if (shape.type !== 'cc-slide') return record
slide: createShapePropsMigrationSequence({
sequence: [
{
id: createShapePropsMigrationIds('cc-slide', { Initial: 1 }).Initial,
up: (props: Record<string, unknown>) => {
return {
...shape,
props: {
...getDefaultCCSlideProps(),
...shape.props,
},
...getDefaultCCSlideProps(),
...props,
}
},
down: (record: TLRecord) => {
return record
},
},
},
},
],
}),
'cc-youtube-embed': {
firstVersion: 1,
currentVersion: 1,
migrators: {
1: {
up: (record: TLRecord) => {
if (record.typeName !== 'shape') return record
const shape = record as TLShape
if (shape.type !== 'cc-youtube-embed') return record
'cc-youtube-embed': createShapePropsMigrationSequence({
sequence: [
{
id: createShapePropsMigrationIds('cc-youtube-embed', { Initial: 1 }).Initial,
up: (props: Record<string, unknown>) => {
return {
...shape,
props: {
...getDefaultCCYoutubeEmbedProps(),
...shape.props,
},
...getDefaultCCYoutubeEmbedProps(),
...props,
}
},
down: (record: TLRecord) => {
return record
},
},
},
},
],
}),
search: {
firstVersion: 1,
currentVersion: 1,
migrators: {
1: {
up: (record: TLRecord) => {
if (record.typeName !== 'shape') return record
const shape = record as TLShape
if (shape.type !== 'cc-search') return record
search: createShapePropsMigrationSequence({
sequence: [
{
id: createShapePropsMigrationIds('cc-search', { Initial: 1 }).Initial,
up: (props: Record<string, unknown>) => {
return {
...shape,
props: {
...getDefaultCCSearchProps(),
...shape.props,
},
...getDefaultCCSearchProps(),
...props,
}
},
down: (record: TLRecord) => {
return record
},
},
},
},
],
}),
webBrowser: {
firstVersion: 1,
currentVersion: 1,
migrators: {
1: {
up: (record: TLRecord) => {
if (record.typeName !== 'shape') return record
const shape = record as TLShape
if (shape.type !== 'cc-web-browser') return record
webBrowser: createShapePropsMigrationSequence({
sequence: [
{
id: createShapePropsMigrationIds('cc-web-browser', { Initial: 1 }).Initial,
up: (props: Record<string, unknown>) => {
return {
...shape,
props: {
...getDefaultCCWebBrowserProps(),
...shape.props,
},
...getDefaultCCWebBrowserProps(),
...props,
}
},
down: (record: TLRecord) => {
return record
},
},
},
},
],
}),
}
+1 -1
View File
@@ -38,7 +38,7 @@ export const ccShapeProps = {
subjectClass: T.string,
color: T.string,
periodCode: T.string,
tldraw_snapshot: T.string.optional()
node_storage_path: T.string.optional()
})
})),
},
@@ -50,12 +50,12 @@ export const createUserNodeFromProfile = (
...getDefaultCCUserNodeProps(),
headerColor: theme.headerColor,
title: userNode.user_email,
unique_id: userNode.unique_id,
uuid_string: userNode.uuid_string,
user_name: userNode.user_name,
user_email: userNode.user_email,
user_type: userNode.user_type,
user_id: userNode.user_id,
path: userNode.tldraw_snapshot,
node_storage_path: userNode.node_storage_path,
worker_node_data: userNode.worker_node_data,
state: {
parentId: null,
+32 -19
View File
@@ -1,3 +1,5 @@
console.log('🔍 SCHEMA FILE: Starting schema file execution');
import { createTLSchema, defaultShapeSchemas, defaultBindingSchemas } from '@tldraw/tlschema';
import { createTLSchemaFromUtils, defaultBindingUtils, defaultShapeUtils } from '@tldraw/tldraw';
import { ShapeUtils } from './shapes';
@@ -7,26 +9,33 @@ import { ccGraphMigrations } from './cc-base/cc-graph/cc-graph-migrations';
import { GraphShapeType } from './cc-base/cc-graph/cc-graph-types';
// Create schema with shape definitions
const customShapes = {
...defaultShapeSchemas,
// Dynamically generate shape schemas from ShapeUtils
...Object.values(ShapeUtils).reduce((acc, util) => ({
...acc,
[util.type]: {
props: util.props,
migrations: util.migrations,
}
}), {}),
// Add graph shapes
...(ccGraphShapeProps ? Object.entries(ccGraphShapeProps).reduce((acc, [type, props]) => ({
...acc,
[type]: {
props,
migrations: ccGraphMigrations[type as GraphShapeType],
}
}), {}) : {})
};
// Debug: Log the custom shapes being added
console.log('🔍 SCHEMA DEBUG: Custom shapes in schema:', Object.keys(customShapes).filter(key => key.startsWith('cc-')));
console.log('🔍 SCHEMA DEBUG: ShapeUtils types:', Object.values(ShapeUtils).map(util => util.type));
console.log('🔍 SCHEMA DEBUG: ccGraphShapeProps types:', Object.keys(ccGraphShapeProps || {}));
export const customSchema = createTLSchema({
shapes: {
...defaultShapeSchemas,
// Dynamically generate shape schemas from ShapeUtils
...Object.values(ShapeUtils).reduce((acc, util) => ({
...acc,
[util.type]: {
props: util.props,
migrations: util.migrations,
}
}), {}),
// Add graph shapes
...(ccGraphShapeProps ? Object.entries(ccGraphShapeProps).reduce((acc, [type, props]) => ({
...acc,
[type]: {
props,
migrations: ccGraphMigrations[type as GraphShapeType],
}
}), {}) : {})
},
shapes: customShapes,
bindings: {
...defaultBindingSchemas,
// Add binding schemas from our custom binding utils
@@ -40,6 +49,10 @@ export const customSchema = createTLSchema({
},
});
// Debug: Log the final schema sequences
console.log('🔍 SCHEMA DEBUG: Final schema sequences:', customSchema.serialize().sequences);
console.log('🔍 SCHEMA DEBUG: Custom shape sequences:', Object.keys(customSchema.serialize().sequences).filter(key => key.includes('cc-')));
// Create schema from utils (alternative approach)
export const schemaFromUtils = createTLSchemaFromUtils({
shapeUtils: [
-2
View File
@@ -41,7 +41,6 @@ import { CCAcademicPeriodNodeShapeUtil } from './cc-base/cc-graph/CCAcademicPeri
import { CCRegistrationPeriodNodeShapeUtil } from './cc-base/cc-graph/CCRegistrationPeriodNodeShapeUtil'
import { CCDepartmentStructureNodeShapeUtil } from './cc-base/cc-graph/CCDepartmentStructureNodeShapeUtil'
import { CCUserTeacherTimetableNodeShapeUtil } from './cc-base/cc-graph/CCUserTeacherTimetableNodeShapeUtil'
import { CCUserTimetableLessonNodeShapeUtil } from './cc-base/cc-graph/CCUserTimetableLessonNodeShapeUtil'
import { CCSearchShapeUtil } from './cc-base/cc-search/CCSearchShapeUtil'
import { CCWebBrowserShapeUtil } from './cc-base/cc-web-browser/CCWebBrowserUtil'
// Define all shape utils in a single object for easy maintenance
@@ -88,7 +87,6 @@ export const ShapeUtils = {
CCRegistrationPeriodNode: CCRegistrationPeriodNodeShapeUtil,
CCDepartmentStructureNode: CCDepartmentStructureNodeShapeUtil,
CCUserTeacherTimetableNode: CCUserTeacherTimetableNodeShapeUtil,
CCUserTimetableLessonNode: CCUserTimetableLessonNodeShapeUtil,
CCSearch: CCSearchShapeUtil,
CCWebBrowser: CCWebBrowserShapeUtil,
}
@@ -27,6 +27,8 @@ import {
} from '@mui/icons-material';
import { CCShapesPanel } from './CCShapesPanel';
import { CCSlidesPanel } from './CCSlidesPanel';
import { CCFilesPanel } from './CCFilesPanel';
import { CCCabinetsPanel } from './CCCabinetsPanel';
import { CCYoutubePanel } from './CCYoutubePanel';
import { CCGraphPanel } from './CCGraphPanel';
import { CCExamMarkerPanel } from './CCExamMarkerPanel';
@@ -40,8 +42,10 @@ import { useTLDraw } from '../../../../../contexts/TLDrawContext';
export const PANEL_TYPES = {
default: [
{ id: 'cabinets', label: 'Cabinets', order: 5 },
{ id: 'navigation', label: 'Navigation', order: 10 },
{ id: 'node-snapshot', label: 'Node', order: 20 },
{ id: 'files', label: 'Files', order: 25 },
{ id: 'cc-shapes', label: 'Shapes', order: 30 },
{ id: 'slides', label: 'Slides', order: 40 },
{ id: 'youtube', label: 'YouTube', order: 50 },
@@ -111,7 +115,7 @@ const StyledMenuItem = styled(MenuItem)(() => ({
}));
export const BasePanel: React.FC<BasePanelProps> = ({
initialPanelType = 'cc-shapes',
initialPanelType = 'files',
examMarkerProps,
isExpanded: controlledIsExpanded,
isPinned: controlledIsPinned,
@@ -151,8 +155,8 @@ export const BasePanel: React.FC<BasePanelProps> = ({
);
// Use controlled state if provided, otherwise use internal state
const [internalIsExpanded, setInternalIsExpanded] = React.useState(false);
const [internalIsPinned, setInternalIsPinned] = React.useState(false);
const [internalIsExpanded, setInternalIsExpanded] = React.useState(true);
const [internalIsPinned, setInternalIsPinned] = React.useState(true);
const isExpanded = controlledIsExpanded ?? internalIsExpanded;
const isPinned = controlledIsPinned ?? internalIsPinned;
@@ -200,6 +204,8 @@ export const BasePanel: React.FC<BasePanelProps> = ({
const getIconForPanel = (panelId: PanelType) => {
switch (panelId) {
case 'cabinets':
return <NavigationIcon />;
case 'cc-shapes':
return <ShapesIcon />;
case 'slides':
@@ -223,6 +229,8 @@ export const BasePanel: React.FC<BasePanelProps> = ({
const getDescriptionForPanel = (panelId: PanelType) => {
switch (panelId) {
case 'cabinets':
return 'Manage file cabinets';
case 'cc-shapes':
return 'Add shapes and elements to your canvas';
case 'slides':
@@ -250,6 +258,10 @@ export const BasePanel: React.FC<BasePanelProps> = ({
}
switch (currentPanelType) {
case 'cabinets':
return <CCCabinetsPanel />;
case 'files':
return <CCFilesPanel />;
case 'cc-shapes':
return <CCShapesPanel />;
case 'slides':
@@ -0,0 +1,129 @@
import React, { useEffect, useMemo, useState } from 'react';
import { ThemeProvider, createTheme, useMediaQuery, Box, Grid, Card, CardContent, CardActions, Typography, Button, TextField, Dialog, DialogTitle, DialogContent, DialogActions, IconButton, styled } from '@mui/material';
import EditIcon from '@mui/icons-material/Edit';
import DeleteIcon from '@mui/icons-material/Delete';
import AddIcon from '@mui/icons-material/Add';
import { useTLDraw } from '../../../../../contexts/TLDrawContext';
import { supabase } from '../../../../../supabaseClient';
type Cabinet = { id: string; name: string };
const Toolbar = styled('div')(() => ({ display: 'flex', gap: '8px', marginBottom: '8px' }));
export const CCCabinetsPanel: React.FC = () => {
const { tldrawPreferences, authToken } = useTLDraw() as { tldrawPreferences?: { colorScheme?: 'light' | 'dark' | 'system' }, authToken?: string };
const prefersDarkMode = useMediaQuery('(prefers-color-scheme: dark)');
const [cabinets, setCabinets] = useState<Cabinet[]>([]);
const [createOpen, setCreateOpen] = useState(false);
const [renameOpen, setRenameOpen] = useState<null | Cabinet>(null);
const [newName, setNewName] = useState('');
const theme = useMemo(() => {
const mode = (tldrawPreferences?.colorScheme === 'system')
? (prefersDarkMode ? 'dark' : 'light')
: (tldrawPreferences?.colorScheme === 'dark' ? 'dark' : 'light');
return createTheme({ palette: { mode, divider: 'var(--color-divider)' } });
}, [tldrawPreferences?.colorScheme, prefersDarkMode]);
const API_BASE: string = (import.meta as unknown as { env?: { VITE_API_BASE?: string } })?.env?.VITE_API_BASE || (location.port.startsWith('517') ? 'http://127.0.0.1:8080' : '/api');
type RequestInitLite = { method?: string; body?: string | FormData | Blob | null; headers?: Record<string, string> } | undefined;
const apiFetch = async (url: string, init?: RequestInitLite) => {
const fullUrl = url.startsWith('http') ? url : `${API_BASE}${url}`;
const { data: { session } } = await supabase.auth.getSession();
const bearer = session?.access_token || authToken || '';
const res = await fetch(fullUrl, {
...init,
headers: {
'Authorization': `Bearer ${bearer}`,
...(init?.headers || {})
}
});
if (!res.ok) throw new Error(await res.text());
return res.json();
};
const loadCabinets = async () => {
const data = await apiFetch('/database/cabinets');
setCabinets([...(data.owned || []), ...(data.shared || [])]);
};
useEffect(() => { loadCabinets(); /* eslint-disable-line react-hooks/exhaustive-deps */ }, []);
const handleCreate = async () => {
if (!newName.trim()) return;
await apiFetch('/database/cabinets', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: newName }) });
setNewName('');
setCreateOpen(false);
await loadCabinets();
};
const handleRename = async () => {
if (!renameOpen || !newName.trim()) return;
await apiFetch(`/database/cabinets/${renameOpen.id}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: newName }) });
setRenameOpen(null);
setNewName('');
await loadCabinets();
};
const handleDelete = async (cabinetId: string) => {
await apiFetch(`/database/cabinets/${cabinetId}`, { method: 'DELETE' });
await loadCabinets();
};
return (
<ThemeProvider theme={theme}>
<Box sx={{ p: 1, height: '100%', display: 'flex', flexDirection: 'column', gap: 1 }}>
<Toolbar>
<Button size="small" variant="outlined" startIcon={<AddIcon/>} onClick={() => { setNewName(''); setCreateOpen(true); }}>New Cabinet</Button>
</Toolbar>
<Grid container spacing={1} sx={{ overflow: 'auto' }}>
{cabinets.map(c => (
<Grid item xs={12} key={c.id}>
<Card variant="outlined">
<CardContent sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<div>
<Typography variant="subtitle1" sx={{ color: 'var(--color-text)' }}>{c.name}</Typography>
<Typography variant="caption" sx={{ color: 'var(--color-text-secondary)' }}>{c.id}</Typography>
</div>
<CardActions>
<IconButton size="small" onClick={() => { setRenameOpen(c); setNewName(c.name); }} title="Rename">
<EditIcon />
</IconButton>
<IconButton size="small" onClick={() => handleDelete(c.id)} title="Delete">
<DeleteIcon />
</IconButton>
</CardActions>
</CardContent>
</Card>
</Grid>
))}
</Grid>
<Dialog open={createOpen} onClose={() => setCreateOpen(false)}>
<DialogTitle>Create Cabinet</DialogTitle>
<DialogContent>
<TextField autoFocus fullWidth label="Name" value={newName} onChange={(e) => setNewName(e.target.value)} />
</DialogContent>
<DialogActions>
<Button onClick={() => setCreateOpen(false)}>Cancel</Button>
<Button onClick={handleCreate} disabled={!newName.trim()}>Create</Button>
</DialogActions>
</Dialog>
<Dialog open={!!renameOpen} onClose={() => setRenameOpen(null)}>
<DialogTitle>Rename Cabinet</DialogTitle>
<DialogContent>
<TextField autoFocus fullWidth label="New name" value={newName} onChange={(e) => setNewName(e.target.value)} />
</DialogContent>
<DialogActions>
<Button onClick={() => setRenameOpen(null)}>Cancel</Button>
<Button onClick={handleRename} disabled={!newName.trim()}>Save</Button>
</DialogActions>
</Dialog>
</Box>
</ThemeProvider>
);
};
@@ -0,0 +1,863 @@
import React, { useEffect, useMemo, useState, useCallback, useRef } from 'react';
import {
ThemeProvider,
createTheme,
useMediaQuery,
Button,
List,
ListItem,
ListItemText,
IconButton,
styled,
CircularProgress,
Divider,
Menu,
MenuItem,
Box,
Typography,
TextField,
Select,
FormControl,
InputLabel,
Pagination,
Stack,
Chip,
Dialog,
DialogTitle,
DialogContent,
DialogActions,
Paper,
Alert,
LinearProgress
} from '@mui/material';
import UploadIcon from '@mui/icons-material/Upload';
import FolderIcon from '@mui/icons-material/Folder';
import FolderOpenIcon from '@mui/icons-material/FolderOpen';
import DeleteIcon from '@mui/icons-material/Delete';
import RefreshIcon from '@mui/icons-material/Refresh';
import MoreVertIcon from '@mui/icons-material/MoreVert';
import ImageIcon from '@mui/icons-material/Image';
import DescriptionIcon from '@mui/icons-material/Description';
import InsertDriveFileIcon from '@mui/icons-material/InsertDriveFile';
import { useTLDraw } from '../../../../../contexts/TLDrawContext';
import { supabase } from '../../../../../supabaseClient';
import { useNavigate } from 'react-router-dom';
import {
calculateDirectoryStats,
isDirectoryPickerSupported,
FileWithPath
} from '../../../../../utils/folderPicker';
const Container = styled('div')(() => ({
padding: '8px',
display: 'flex',
flexDirection: 'column',
gap: '8px',
height: '100%'
}));
type Cabinet = { id: string; name: string };
type FileRow = {
id: string;
name: string;
mime_type?: string;
is_directory?: boolean;
size_bytes?: number;
processing_status?: string;
relative_path?: string;
created_at?: string;
};
type Artefact = { id: string; type: string; rel_path: string; created_at: string };
interface PaginationInfo {
page: number;
per_page: number;
total_count: number;
total_pages: number;
has_next: boolean;
has_prev: boolean;
offset: number;
}
interface FileListResponse {
files: FileRow[];
pagination: PaginationInfo;
filters: {
search?: string;
sort_by: string;
sort_order: string;
include_directories: boolean;
parent_directory_id?: string;
};
}
export const CCFilesPanel: React.FC = () => {
const { tldrawPreferences, authToken } = useTLDraw() as { tldrawPreferences?: { colorScheme?: 'light' | 'dark' | 'system' }, authToken?: string };
const prefersDarkMode = useMediaQuery('(prefers-color-scheme: dark)');
const [cabinets, setCabinets] = useState<Cabinet[]>([]);
const [selectedCabinet, setSelectedCabinet] = useState<string>('');
const [files, setFiles] = useState<FileRow[]>([]);
const [pagination, setPagination] = useState<PaginationInfo | null>(null);
const [loading, setLoading] = useState(false);
const [menuAnchor, setMenuAnchor] = useState<null | { el: HTMLElement; fileId: string }>(null);
const [artefacts, setArtefacts] = useState<Artefact[]>([]);
// Pagination and filtering state
const [currentPage, setCurrentPage] = useState(1);
const [itemsPerPage, setItemsPerPage] = useState(15); // Slightly more for main panel
const [searchTerm, setSearchTerm] = useState('');
const [sortBy, setSortBy] = useState('created_at');
const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('desc');
const previousSearchTerm = useRef(searchTerm);
// Directory navigation state
const [currentDirectoryId, setCurrentDirectoryId] = useState<string | null>(null);
const [breadcrumbs, setBreadcrumbs] = useState<{ id: string | null; name: string }[]>([
{ id: null, name: 'Root' }
]);
// Directory upload state
const [selectedFiles, setSelectedFiles] = useState<FileWithPath[]>([]);
const [showDirectoryDialog, setShowDirectoryDialog] = useState(false);
const [isDirectoryUploading, setIsDirectoryUploading] = useState(false);
const [directoryStats, setDirectoryStats] = useState<{
fileCount: number;
directoryCount: number;
totalSize: number;
formattedSize: string;
} | null>(null);
const navigate = useNavigate();
const theme = useMemo(() => {
const mode = (tldrawPreferences?.colorScheme === 'system')
? (prefersDarkMode ? 'dark' : 'light')
: (tldrawPreferences?.colorScheme === 'dark' ? 'dark' : 'light');
return createTheme({ palette: { mode, divider: 'var(--color-divider)' } });
}, [tldrawPreferences?.colorScheme, prefersDarkMode]);
type RequestInitLike = { method?: string; body?: FormData | string | Blob | null; headers?: Record<string, string> } | undefined;
type HeadersInitLike = Record<string, string>;
const API_BASE: string = (import.meta as unknown as { env?: { VITE_API_BASE?: string } })?.env?.VITE_API_BASE || (location.port.startsWith('517') ? 'http://127.0.0.1:8080' : '/api');
const apiFetch = useCallback(async (url: string, init?: RequestInitLike) => {
const headers: HeadersInitLike = {
'Authorization': `Bearer ${(await supabase.auth.getSession()).data.session?.access_token || authToken || ''}`,
...(init?.headers || {})
};
const fullUrl = url.startsWith('http') ? url : `${API_BASE}${url}`;
const res = await fetch(fullUrl, { ...(init || {}), headers });
if (!res.ok) throw new Error(await res.text());
return res.json();
}, [authToken, API_BASE]);
const loadCabinets = useCallback(async () => {
setLoading(true);
try {
const data = await apiFetch('/database/cabinets');
const all = [...(data.owned || []), ...(data.shared || [])];
setCabinets(all);
if (all.length && !selectedCabinet) setSelectedCabinet(all[0].id);
} catch (error) {
console.error('Failed to load cabinets:', error);
} finally {
setLoading(false);
}
}, [selectedCabinet, apiFetch]);
const loadFiles = useCallback(async (cabinetId: string, page: number = currentPage) => {
if (!cabinetId) return;
setLoading(true);
try {
// Build query parameters for pagination, search, and sorting
const params = new URLSearchParams({
cabinet_id: cabinetId,
page: page.toString(),
per_page: itemsPerPage.toString(),
sort_by: sortBy,
sort_order: sortOrder,
include_directories: 'true'
});
// Add directory filtering
if (currentDirectoryId) {
params.append('parent_directory_id', currentDirectoryId);
}
if (searchTerm) {
params.append('search', searchTerm);
}
// Use the new simple upload endpoint for listing files with pagination
const data: FileListResponse = await apiFetch(`/simple-upload/files?${params.toString()}`);
setFiles(data.files || []);
setPagination(data.pagination);
} catch (error) {
console.error('Failed to load files:', error);
} finally {
setLoading(false);
}
}, [currentPage, itemsPerPage, sortBy, sortOrder, searchTerm, apiFetch, currentDirectoryId]);
useEffect(() => {
loadCabinets();
}, [loadCabinets]);
// Main loading effect - handles pagination, sorting, cabinet changes, directory navigation
useEffect(() => {
if (selectedCabinet) {
loadFiles(selectedCabinet, currentPage);
}
}, [selectedCabinet, loadFiles, currentPage, itemsPerPage, sortBy, sortOrder, currentDirectoryId]);
// Reset to page 1 and root directory when cabinet changes
useEffect(() => {
if (selectedCabinet) {
setCurrentPage(1);
setCurrentDirectoryId(null);
setBreadcrumbs([{ id: null, name: 'Root' }]);
}
}, [selectedCabinet]);
// Search with debouncing - only when search term actually changes
useEffect(() => {
if (selectedCabinet && searchTerm !== previousSearchTerm.current) {
previousSearchTerm.current = searchTerm;
const timeoutId = setTimeout(() => {
setCurrentPage(1); // Reset to first page when searching
loadFiles(selectedCabinet, 1);
}, 500); // 500ms debounce
return () => clearTimeout(timeoutId);
}
}, [searchTerm, selectedCabinet, loadFiles]);
// Directory navigation handlers
const navigateToFolder = useCallback((folder: FileRow) => {
if (!folder.is_directory) return;
setCurrentDirectoryId(folder.id);
setCurrentPage(1); // Reset to first page when entering folder
// Add to breadcrumbs
setBreadcrumbs(prev => [...prev, { id: folder.id, name: folder.name }]);
}, []);
const navigateToBreadcrumb = useCallback((targetBreadcrumb: { id: string | null; name: string }) => {
setCurrentDirectoryId(targetBreadcrumb.id);
setCurrentPage(1); // Reset to first page
// Trim breadcrumbs to the selected one
setBreadcrumbs(prev => {
const targetIndex = prev.findIndex(b => b.id === targetBreadcrumb.id && b.name === targetBreadcrumb.name);
return targetIndex !== -1 ? prev.slice(0, targetIndex + 1) : [{ id: null, name: 'Root' }];
});
}, []);
// Sort files to group directories first, then regular files
const sortedFiles = useMemo(() => {
return [...files].sort((a, b) => {
// Directories come first
if (a.is_directory && !b.is_directory) return -1;
if (!a.is_directory && b.is_directory) return 1;
// Within the same type (both directories or both files), sort alphabetically by name
return a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: 'base' });
});
}, [files]);
// Check if we need a separator between directories and files
const needsGroupSeparator = useMemo(() => {
const hasDirectories = sortedFiles.some(f => f.is_directory);
const hasFiles = sortedFiles.some(f => !f.is_directory);
return hasDirectories && hasFiles;
}, [sortedFiles]);
const getGroupSeparatorIndex = useMemo(() => {
if (!needsGroupSeparator) return -1;
return sortedFiles.findIndex(f => !f.is_directory) - 1;
}, [sortedFiles, needsGroupSeparator]);
const handleUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
if (!e.target.files || !selectedCabinet) return;
const file = e.target.files[0];
await uploadFile(file);
(e.target as HTMLInputElement).value = '';
};
const handleDirectorySelect = (e: React.ChangeEvent<HTMLInputElement>) => {
if (!e.target.files || !selectedCabinet) return;
// Convert FileList to FileWithPath array with relative paths
const files: FileWithPath[] = [];
Array.from(e.target.files).forEach(file => {
const relativePath = (file as File & { webkitRelativePath?: string }).webkitRelativePath || file.name;
(file as FileWithPath).relativePath = relativePath;
files.push(file as FileWithPath);
});
if (files.length > 0) {
prepareDirectoryUpload(files);
}
(e.target as HTMLInputElement).value = '';
};
const uploadFile = async (file: File) => {
if (!selectedCabinet) return;
const form = new FormData();
form.append('cabinet_id', selectedCabinet);
form.append('path', file.name);
form.append('scope', 'teacher');
form.append('file', file);
await apiFetch('/database/files/upload', { method: 'POST', body: form });
await loadFiles(selectedCabinet);
};
const prepareDirectoryUpload = (files: FileWithPath[]) => {
if (files.length === 0) return;
setSelectedFiles(files);
setDirectoryStats(calculateDirectoryStats(files));
setShowDirectoryDialog(true);
};
const startDirectoryUpload = async () => {
if (!selectedCabinet || selectedFiles.length === 0) return;
setIsDirectoryUploading(true);
try {
const firstFilePath = selectedFiles[0].relativePath;
const directoryName = firstFilePath.split('/')[0] || 'uploaded-folder';
const formData = new FormData();
formData.append('cabinet_id', selectedCabinet);
formData.append('scope', 'teacher');
formData.append('directory_name', directoryName);
selectedFiles.forEach(file => {
formData.append('files', file);
});
const relativePaths = selectedFiles.map(f => f.relativePath);
formData.append('file_paths', JSON.stringify(relativePaths));
await apiFetch('/simple-upload/files/upload-directory', {
method: 'POST',
body: formData
});
await loadFiles(selectedCabinet);
setShowDirectoryDialog(false);
setSelectedFiles([]);
setDirectoryStats(null);
} catch (error) {
console.error('Directory upload failed:', error);
} finally {
setIsDirectoryUploading(false);
}
};
const handleDelete = async (fileId: string) => {
await apiFetch(`/database/files/${fileId}`, { method: 'DELETE' });
await loadFiles(selectedCabinet);
};
const handleGenerateInitial = async (fileId: string) => {
await apiFetch(`/database/files/${fileId}/artefacts/initial`, { method: 'POST' });
const arts = await apiFetch(`/database/files/${fileId}/artefacts`);
setArtefacts(arts || []);
};
const openMenu = (el: HTMLElement, fileId: string) => setMenuAnchor({ el, fileId });
const closeMenu = () => setMenuAnchor(null);
const goToAIContent = () => {
if (!menuAnchor) return;
const fileId = menuAnchor.fileId;
closeMenu();
navigate(`/doc-intelligence/${encodeURIComponent(fileId)}`);
};
const iconForMime = (mime?: string, isDirectory?: boolean) => {
if (isDirectory) return <FolderIcon />;
if (!mime) return <InsertDriveFileIcon/>;
if (mime.startsWith('image/')) return <ImageIcon/>;
if (mime === 'application/pdf' || mime.startsWith('application/')) return <DescriptionIcon/>;
return <InsertDriveFileIcon/>;
};
const formatFileSize = (bytes: number): string => {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};
const getStatusColor = (status?: string) => {
switch (status) {
case 'uploaded': return 'primary';
case 'processing': return 'warning';
case 'completed': return 'success';
case 'failed': return 'error';
default: return 'default';
}
};
return (
<ThemeProvider theme={theme}>
<Container>
{/* Cabinet Selection Dropdown */}
<Box sx={{ display: 'flex', gap: 1, alignItems: 'center', mb: 1 }}>
<FormControl size="small" fullWidth>
<InputLabel>Cabinet</InputLabel>
<Select
value={selectedCabinet}
label="Cabinet"
onChange={(e) => setSelectedCabinet(e.target.value)}
startAdornment={<FolderIcon sx={{ color: 'action.active', mr: 1, fontSize: '1rem' }} />}
>
{cabinets.map(c => (
<MenuItem key={c.id} value={c.id}>
<Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: '100%' }}>
<Typography variant="body2">{c.name}</Typography>
{pagination && selectedCabinet === c.id && (
<Chip label={`${pagination.total_count} files`} size="small" sx={{ ml: 1 }} />
)}
</Box>
</MenuItem>
))}
</Select>
</FormControl>
<Button
size="small"
variant="outlined"
onClick={() => {
setCurrentPage(1);
setSearchTerm('');
loadCabinets();
}}
sx={{
minWidth: 40,
width: 40,
height: 40, // Match the height of Select components
padding: 0,
'& .MuiButton-startIcon': {
margin: 0
}
}}
>
<RefreshIcon fontSize="small" />
</Button>
</Box>
{/* Search Box - Full Width */}
<Box sx={{ mb: 1 }}>
<TextField
size="small"
label="Search files"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
fullWidth
placeholder="Type to search files..."
/>
</Box>
{/* Sort and Filter Controls */}
<Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap', alignItems: 'center', py: 1 }}>
<FormControl size="small" sx={{ minWidth: 80 }}>
<InputLabel>Sort</InputLabel>
<Select
value={sortBy}
label="Sort"
onChange={(e) => setSortBy(e.target.value)}
>
<MenuItem value="name">Name</MenuItem>
<MenuItem value="created_at">Date</MenuItem>
<MenuItem value="size_bytes">Size</MenuItem>
</Select>
</FormControl>
<FormControl size="small" sx={{ minWidth: 60 }}>
<InputLabel>Order</InputLabel>
<Select
value={sortOrder}
label="Order"
onChange={(e) => setSortOrder(e.target.value as 'asc' | 'desc')}
>
<MenuItem value="asc"></MenuItem>
<MenuItem value="desc"></MenuItem>
</Select>
</FormControl>
<FormControl size="small" sx={{ minWidth: 60 }}>
<InputLabel>Per page</InputLabel>
<Select
value={itemsPerPage}
label="Per page"
onChange={(e) => {
setItemsPerPage(Number(e.target.value));
setCurrentPage(1);
}}
>
<MenuItem value={10}>10</MenuItem>
<MenuItem value={15}>15</MenuItem>
<MenuItem value={25}>25</MenuItem>
</Select>
</FormControl>
</Box>
{/* Breadcrumb Navigation */}
<Box sx={{
display: 'flex',
alignItems: 'center',
gap: 1,
py: 1,
px: 1,
bgcolor: 'background.paper',
borderBottom: '1px solid var(--color-divider)'
}}>
{breadcrumbs.map((breadcrumb, index) => (
<React.Fragment key={`${breadcrumb.id}-${breadcrumb.name}`}>
{index > 0 && (
<Typography variant="caption" color="textSecondary">
/
</Typography>
)}
<Button
size="small"
variant="text"
onClick={() => navigateToBreadcrumb(breadcrumb)}
sx={{
minWidth: 'auto',
textTransform: 'none',
color: index === breadcrumbs.length - 1 ? 'primary.main' : 'text.secondary',
fontWeight: index === breadcrumbs.length - 1 ? 600 : 400
}}
>
{breadcrumb.name}
</Button>
</React.Fragment>
))}
</Box>
{/* File List with Fixed Height */}
<Box sx={{
border: '1px solid var(--color-divider)',
borderRadius: '4px',
height: 300, // Fixed height for main panel
overflow: 'auto',
flex: 1,
// Hide scrollbar while keeping scroll functionality
scrollbarWidth: 'none', // Firefox
'&::-webkit-scrollbar': {
display: 'none' // WebKit browsers (Chrome, Safari, Edge)
}
}}>
{loading ? (
<Box sx={{ p: 2, textAlign: 'center' }}>
<CircularProgress size={20}/>
<Typography variant="caption" display="block" sx={{ mt: 1 }}>
Loading files...
</Typography>
</Box>
) : sortedFiles.length === 0 ? (
<Box sx={{ p: 2, textAlign: 'center' }}>
<Typography variant="body2" color="textSecondary">
{searchTerm ? 'No files found matching your search.' : 'No files found. Upload some files!'}
</Typography>
</Box>
) : (
<List dense disablePadding>
{sortedFiles.map((f, index) => (
<React.Fragment key={f.id}>
{f.is_directory ? (
<ListItem
button
onClick={() => navigateToFolder(f)}
sx={{
cursor: 'pointer',
'&:hover': {
backgroundColor: 'action.hover'
}
}}
secondaryAction={
<>
<IconButton size="small" onClick={(e) => openMenu(e.currentTarget, f.id)} title="File actions">
<MoreVertIcon/>
</IconButton>
<IconButton edge="end" size="small" onClick={() => handleDelete(f.id)} title="Delete file">
<DeleteIcon/>
</IconButton>
</>
}
>
{iconForMime(f.mime_type, f.is_directory)}
<ListItemText
sx={{ ml: 1 }}
primary={
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<Typography variant="body2" sx={{ wordBreak: 'break-all' }}>
{f.name}
</Typography>
{f.is_directory && <Chip label="Dir" size="small" />}
{f.processing_status && f.processing_status !== 'uploaded' && (
<Chip
label={f.processing_status}
size="small"
color={getStatusColor(f.processing_status)}
/>
)}
</Box>
}
secondary={
<Typography variant="caption" color="textSecondary">
{f.size_bytes ? formatFileSize(f.size_bytes) : 'Unknown size'}
{f.mime_type && `${f.mime_type.split('/')[1]}`}
</Typography>
}
/>
</ListItem>
) : (
<ListItem
secondaryAction={
<>
<IconButton size="small" onClick={(e) => openMenu(e.currentTarget, f.id)} title="File actions">
<MoreVertIcon/>
</IconButton>
<IconButton edge="end" size="small" onClick={() => handleDelete(f.id)} title="Delete file">
<DeleteIcon/>
</IconButton>
</>
}
>
{iconForMime(f.mime_type, f.is_directory)}
<ListItemText
sx={{ ml: 1 }}
primary={
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<Typography variant="body2" sx={{ wordBreak: 'break-all' }}>
{f.name}
</Typography>
{f.is_directory && <Chip label="Dir" size="small" />}
{f.processing_status && f.processing_status !== 'uploaded' && (
<Chip
label={f.processing_status}
size="small"
color={getStatusColor(f.processing_status)}
/>
)}
</Box>
}
secondary={
<Typography variant="caption" color="textSecondary">
{f.size_bytes ? formatFileSize(f.size_bytes) : 'Unknown size'}
{f.mime_type && `${f.mime_type.split('/')[1]}`}
</Typography>
}
/>
</ListItem>
)}
{/* Group separator between directories and files */}
{index === getGroupSeparatorIndex && needsGroupSeparator && (
<Divider sx={{ my: 1, borderStyle: 'dashed', borderColor: 'divider' }} />
)}
{/* Regular divider between items */}
{index < sortedFiles.length - 1 && index !== getGroupSeparatorIndex && <Divider />}
</React.Fragment>
))}
</List>
)}
</Box>
{/* Pagination Controls */}
{pagination && pagination.total_pages > 1 && (
<Box sx={{ mt: 1, display: 'flex', justifyContent: 'center' }}>
<Stack spacing={1} alignItems="center">
<Pagination
count={pagination.total_pages}
page={pagination.page}
onChange={(event, value) => setCurrentPage(value)}
color="primary"
size="small"
showFirstButton
showLastButton
/>
<Typography variant="caption" color="textSecondary">
{pagination.offset + 1}-{Math.min(pagination.offset + pagination.per_page, pagination.total_count)} of {pagination.total_count}
</Typography>
</Stack>
</Box>
)}
{/* Upload Controls */}
<Box sx={{ mt: 2, display: 'flex', gap: 1, flexDirection: 'column' }}>
{/* File Inputs */}
<input
id="cc-file-input"
type="file"
style={{ display: 'none' }}
onChange={handleUpload}
disabled={!selectedCabinet}
/>
<input
id="cc-directory-input"
type="file"
style={{ display: 'none' }}
{...({ webkitdirectory: '' } as React.InputHTMLAttributes<HTMLInputElement>)}
multiple
onChange={handleDirectorySelect}
disabled={!selectedCabinet}
/>
{/* Upload Buttons */}
<Box sx={{ display: 'flex', gap: 1 }}>
<Button
variant="outlined"
startIcon={<UploadIcon />}
onClick={() => selectedCabinet && document.getElementById('cc-file-input')?.click()}
disabled={!selectedCabinet}
fullWidth
>
Upload File
</Button>
<Button
variant="outlined"
startIcon={<FolderOpenIcon />}
onClick={() => selectedCabinet && document.getElementById('cc-directory-input')?.click()}
disabled={!selectedCabinet}
fullWidth
>
Upload Folder
</Button>
</Box>
{!selectedCabinet && (
<Typography variant="caption" color="text.secondary" sx={{ textAlign: 'center', mt: 0.5 }}>
Select a cabinet first to enable uploads
</Typography>
)}
{selectedCabinet && !isDirectoryPickerSupported() && (
<Typography variant="caption" color="warning.main" sx={{ textAlign: 'center', mt: 0.5 }}>
Folder uploads may have limited support in this browser
</Typography>
)}
</Box>
<Menu
anchorEl={menuAnchor?.el ?? null}
open={!!menuAnchor}
onClose={closeMenu}
anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
transformOrigin={{ vertical: 'top', horizontal: 'right' }}
>
<MenuItem onClick={() => { if (menuAnchor) { handleGenerateInitial(menuAnchor.fileId); closeMenu(); } }}>Generate initial artefacts</MenuItem>
<MenuItem onClick={goToAIContent}>Open AI content</MenuItem>
</Menu>
{artefacts.length > 0 && (
<>
<Divider/>
<List dense sx={{
border: '1px solid var(--color-divider)',
borderRadius: '4px',
overflow: 'auto',
maxHeight: 160,
// Hide scrollbar while keeping scroll functionality
scrollbarWidth: 'none', // Firefox
'&::-webkit-scrollbar': {
display: 'none' // WebKit browsers (Chrome, Safari, Edge)
}
}}>
{artefacts.map(a => (
<ListItem key={a.id}>
<ListItemText primary={a.type} secondary={a.rel_path} />
</ListItem>
))}
</List>
</>
)}
{/* Directory Upload Dialog */}
<Dialog
open={showDirectoryDialog}
onClose={() => !isDirectoryUploading && setShowDirectoryDialog(false)}
maxWidth="md"
fullWidth
>
<DialogTitle>
<Box display="flex" alignItems="center" gap={1}>
<FolderOpenIcon />
Directory Upload
{isDirectoryUploading && <LinearProgress sx={{ flexGrow: 1, ml: 2 }} />}
</Box>
</DialogTitle>
<DialogContent>
{directoryStats && (
<Alert severity="info" sx={{ mb: 2 }}>
<Typography variant="body2">
<strong>{directoryStats.fileCount} files</strong> in{' '}
<strong>{directoryStats.directoryCount} folders</strong><br/>
Total size: <strong>{directoryStats.formattedSize}</strong>
</Typography>
</Alert>
)}
<Paper variant="outlined" sx={{
p: 2,
maxHeight: 200,
overflow: 'auto',
// Hide scrollbar while keeping scroll functionality
scrollbarWidth: 'none', // Firefox
'&::-webkit-scrollbar': {
display: 'none' // WebKit browsers (Chrome, Safari, Edge)
}
}}>
<Typography variant="body2" color="textSecondary" gutterBottom>
Files to upload:
</Typography>
{selectedFiles.map((file, i) => (
<Box key={i} sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', py: 0.5 }}>
<Typography variant="body2" sx={{ flex: 1, mr: 2 }} noWrap>
{file.relativePath}
</Typography>
<Typography variant="caption" color="textSecondary">
{formatFileSize(file.size)}
</Typography>
</Box>
))}
</Paper>
</DialogContent>
<DialogActions>
<Button onClick={() => setShowDirectoryDialog(false)} disabled={isDirectoryUploading}>
Cancel
</Button>
<Button
onClick={startDirectoryUpload}
variant="contained"
disabled={isDirectoryUploading || selectedFiles.length === 0}
>
{isDirectoryUploading ? 'Uploading...' : 'Upload Directory'}
</Button>
</DialogActions>
</Dialog>
</Container>
</ThemeProvider>
);
};
@@ -0,0 +1,505 @@
import React, { useEffect, useMemo, useState, useRef } from 'react';
import {
ThemeProvider,
createTheme,
useMediaQuery,
Button,
List,
ListItem,
ListItemText,
IconButton,
styled,
CircularProgress,
Divider,
Menu,
MenuItem,
Box,
Typography,
LinearProgress,
Dialog,
DialogTitle,
DialogContent,
DialogActions,
Chip,
Tooltip,
Alert
} from '@mui/material';
import UploadIcon from '@mui/icons-material/Upload';
import FolderIcon from '@mui/icons-material/Folder';
import FolderOpenIcon from '@mui/icons-material/FolderOpen';
import DeleteIcon from '@mui/icons-material/Delete';
import RefreshIcon from '@mui/icons-material/Refresh';
import MoreVertIcon from '@mui/icons-material/MoreVert';
import ImageIcon from '@mui/icons-material/Image';
import DescriptionIcon from '@mui/icons-material/Description';
import InsertDriveFileIcon from '@mui/icons-material/InsertDriveFile';
import CloudUploadIcon from '@mui/icons-material/CloudUpload';
import { useTLDraw } from '../../../../../contexts/TLDrawContext';
import { supabase } from '../../../../../supabaseClient';
import { useNavigate } from 'react-router-dom';
import {
pickDirectory,
processDirectoryFiles,
calculateDirectoryStats,
createDirectoryTree,
formatFileSize,
isDirectoryPickerSupported,
FileWithPath
} from '../../../../folderPicker';
import pLimit from 'p-limit';
const Container = styled('div')(() => ({
padding: '8px',
display: 'flex',
flexDirection: 'column',
gap: '8px',
height: '100%'
}));
const Row = styled('div')(() => ({
display: 'flex',
gap: '8px',
alignItems: 'center'
}));
type Cabinet = { id: string; name: string };
type FileRow = { id: string; name: string; mime_type?: string; is_directory?: boolean; size_bytes?: number };
type Artefact = { id: string; type: string; rel_path: string; created_at: string };
interface UploadProgress {
path: string;
size: number;
status: 'queued' | 'uploading' | 'done' | 'error';
progress: number;
error?: string;
}
export const CCFilesPanelEnhanced: React.FC = () => {
const { tldrawPreferences, authToken } = useTLDraw() as { tldrawPreferences?: { colorScheme?: 'light' | 'dark' | 'system' }, authToken?: string };
const prefersDarkMode = useMediaQuery('(prefers-color-scheme: dark)');
const [cabinets, setCabinets] = useState<Cabinet[]>([]);
const [selectedCabinet, setSelectedCabinet] = useState<string>('');
const [files, setFiles] = useState<FileRow[]>([]);
const [loading, setLoading] = useState(false);
const [menuAnchor, setMenuAnchor] = useState<null | { el: HTMLElement; fileId: string }>(null);
const [artefacts, setArtefacts] = useState<Artefact[]>([]);
// Directory upload states
const [uploadProgress, setUploadProgress] = useState<UploadProgress[]>([]);
const [showUploadDialog, setShowUploadDialog] = useState(false);
const [isUploading, setIsUploading] = useState(false);
const [selectedFiles, setSelectedFiles] = useState<FileWithPath[]>([]);
const [directoryStats, setDirectoryStats] = useState<any>(null);
const navigate = useNavigate();
const fileInputRef = useRef<HTMLInputElement>(null);
const dirInputRef = useRef<HTMLInputElement>(null);
const theme = useMemo(() => {
const mode = (tldrawPreferences?.colorScheme === 'system')
? (prefersDarkMode ? 'dark' : 'light')
: (tldrawPreferences?.colorScheme === 'dark' ? 'dark' : 'light');
return createTheme({ palette: { mode, divider: 'var(--color-divider)' } });
}, [tldrawPreferences?.colorScheme, prefersDarkMode]);
type RequestInitLike = { method?: string; body?: FormData | string | Blob | null; headers?: Record<string, string> } | undefined;
type HeadersInitLike = Record<string, string>;
const API_BASE: string = (import.meta as unknown as { env?: { VITE_API_BASE?: string } })?.env?.VITE_API_BASE || (location.port.startsWith('517') ? 'http://127.0.0.1:8080' : '/api');
const apiFetch = async (url: string, init?: RequestInitLike) => {
const headers: HeadersInitLike = {
'Authorization': `Bearer ${(await supabase.auth.getSession()).data.session?.access_token || authToken || ''}`,
...(init?.headers || {})
};
const fullUrl = url.startsWith('http') ? url : `${API_BASE}${url}`;
const res = await fetch(fullUrl, { ...(init || {}), headers });
if (!res.ok) throw new Error(await res.text());
return res.json();
};
const loadCabinets = async () => {
setLoading(true);
try {
const data = await apiFetch('/database/cabinets');
const all = [...(data.owned || []), ...(data.shared || [])];
setCabinets(all);
if (all.length && !selectedCabinet) setSelectedCabinet(all[0].id);
} finally {
setLoading(false);
}
};
const loadFiles = async (cabinetId: string) => {
setLoading(true);
try {
const data = await apiFetch(`/simple-upload/files?cabinet_id=${encodeURIComponent(cabinetId)}`);
setFiles(data.files || []);
} finally {
setLoading(false);
}
};
useEffect(() => { loadCabinets(); }, []);
useEffect(() => { if (selectedCabinet) loadFiles(selectedCabinet); }, [selectedCabinet]);
const handleSingleUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
if (!e.target.files || !selectedCabinet) return;
const file = e.target.files[0];
const form = new FormData();
form.append('cabinet_id', selectedCabinet);
form.append('path', file.name);
form.append('scope', 'teacher');
form.append('file', file);
try {
await apiFetch('/simple-upload/files/upload', { method: 'POST', body: form });
await loadFiles(selectedCabinet);
(e.target as HTMLInputElement).value = '';
} catch (error) {
console.error('Upload failed:', error);
alert(`Upload failed: ${error}`);
}
};
const handleDirectoryPicker = async () => {
try {
const files = await pickDirectory();
prepareDirectoryUpload(files);
} catch (error: any) {
if (error.message === 'fallback-input') {
// Use fallback input
dirInputRef.current?.click();
} else if (error.message === 'user-cancelled') {
// User cancelled, do nothing
} else {
console.error('Directory picker error:', error);
alert('Failed to pick directory. Please try the fallback method.');
dirInputRef.current?.click();
}
}
};
const handleFallbackDirectorySelect = (e: React.ChangeEvent<HTMLInputElement>) => {
if (!e.target.files) return;
const files = processDirectoryFiles(e.target.files);
prepareDirectoryUpload(files);
e.target.value = ''; // Reset input
};
const prepareDirectoryUpload = (files: FileWithPath[]) => {
if (files.length === 0) {
alert('No files selected');
return;
}
setSelectedFiles(files);
setDirectoryStats(calculateDirectoryStats(files));
// Initialize upload progress
const progress: UploadProgress[] = files.map(file => ({
path: file.relativePath,
size: file.size,
status: 'queued',
progress: 0
}));
setUploadProgress(progress);
setShowUploadDialog(true);
};
const startDirectoryUpload = async () => {
if (!selectedCabinet || selectedFiles.length === 0) return;
setIsUploading(true);
try {
// Get directory name from first file's path
const firstFilePath = selectedFiles[0].relativePath;
const directoryName = firstFilePath.split('/')[0] || 'uploaded-folder';
// Prepare form data
const formData = new FormData();
formData.append('cabinet_id', selectedCabinet);
formData.append('scope', 'teacher');
formData.append('directory_name', directoryName);
// Add all files
selectedFiles.forEach(file => {
formData.append('files', file);
});
// Add relative paths as JSON
const relativePaths = selectedFiles.map(f => f.relativePath);
formData.append('file_paths', JSON.stringify(relativePaths));
// Upload directory
const result = await apiFetch('/simple-upload/files/upload-directory', {
method: 'POST',
body: formData
});
console.log('Directory upload result:', result);
// Update progress to completed
setUploadProgress(prev => prev.map(item => ({
...item,
status: 'done',
progress: 100
})));
// Refresh file list
await loadFiles(selectedCabinet);
// Close dialog after a short delay
setTimeout(() => {
setShowUploadDialog(false);
setIsUploading(false);
setSelectedFiles([]);
setUploadProgress([]);
}, 2000);
} catch (error) {
console.error('Directory upload failed:', error);
alert(`Directory upload failed: ${error}`);
// Mark all as error
setUploadProgress(prev => prev.map(item => ({
...item,
status: 'error',
error: String(error)
})));
setIsUploading(false);
}
};
const handleDelete = async (fileId: string) => {
try {
await apiFetch(`/simple-upload/files/${fileId}`, { method: 'DELETE' });
await loadFiles(selectedCabinet);
} catch (error) {
console.error('Delete failed:', error);
alert(`Delete failed: ${error}`);
}
};
const handleGenerateInitial = async (fileId: string) => {
// This would trigger manual processing if we implement it later
alert('Manual processing not yet implemented');
};
const openMenu = (el: HTMLElement, fileId: string) => setMenuAnchor({ el, fileId });
const closeMenu = () => setMenuAnchor(null);
const goToAIContent = () => {
if (!menuAnchor) return;
const fileId = menuAnchor.fileId;
closeMenu();
navigate(`/doc-intelligence/${encodeURIComponent(fileId)}`);
};
const iconForMime = (mime?: string, isDirectory?: boolean) => {
if (isDirectory) return <FolderIcon />;
if (!mime) return <InsertDriveFileIcon />;
if (mime.startsWith('image/')) return <ImageIcon />;
if (mime === 'application/pdf' || mime.startsWith('application/')) return <DescriptionIcon />;
return <InsertDriveFileIcon />;
};
const formatFileInfo = (file: FileRow) => {
if (file.is_directory) {
return `Directory • ${file.size_bytes ? formatFileSize(file.size_bytes) : 'Unknown size'}`;
}
return file.size_bytes ? formatFileSize(file.size_bytes) : 'Unknown size';
};
return (
<ThemeProvider theme={theme}>
<Container>
<Row>
<Button size="small" startIcon={<RefreshIcon/>} onClick={loadCabinets}>Refresh</Button>
</Row>
<List dense sx={{ border: '1px solid var(--color-divider)', borderRadius: '4px', overflow: 'auto', maxHeight: 140 }}>
{cabinets.map(c => (
<ListItem key={c.id} selected={c.id === selectedCabinet} onClick={() => setSelectedCabinet(c.id)} sx={{ cursor: 'pointer' }}>
<FolderIcon sx={{ mr: 1 }}/>
<ListItemText primary={c.name} secondary={c.id} />
</ListItem>
))}
</List>
<Divider/>
<Row>
{/* Single file upload */}
<input id="cc-file-input" type="file" style={{ display: 'none' }} onChange={handleSingleUpload}/>
<label htmlFor="cc-file-input">
<Button size="small" variant="outlined" startIcon={<UploadIcon/>} component="span" disabled={!selectedCabinet}>
Upload File
</Button>
</label>
{/* Directory upload */}
<input
ref={dirInputRef}
type="file"
style={{ display: 'none' }}
webkitdirectory=""
multiple
onChange={handleFallbackDirectorySelect}
/>
<Tooltip title={isDirectoryPickerSupported() ? "Uses modern directory picker" : "Uses fallback method"}>
<Button
size="small"
variant="outlined"
startIcon={<FolderOpenIcon/>}
onClick={handleDirectoryPicker}
disabled={!selectedCabinet}
>
Upload Folder
</Button>
</Tooltip>
</Row>
{loading ? <CircularProgress size={20}/> : (
<List dense sx={{ border: '1px solid var(--color-divider)', borderRadius: '4px', overflow: 'auto', flex: 1 }}>
{files.map(f => (
<ListItem key={f.id}
secondaryAction={
<>
<IconButton size="small" onClick={(e) => openMenu(e.currentTarget, f.id)} title="File actions">
<MoreVertIcon/>
</IconButton>
<IconButton edge="end" size="small" onClick={() => handleDelete(f.id)} title="Delete file">
<DeleteIcon/>
</IconButton>
</>
}
>
{iconForMime(f.mime_type, f.is_directory)}
<ListItemText
sx={{ ml: 1 }}
primary={f.name}
secondary={formatFileInfo(f)}
/>
{f.is_directory && <Chip label="Directory" size="small" />}
</ListItem>
))}
</List>
)}
<Menu
anchorEl={menuAnchor?.el ?? null}
open={!!menuAnchor}
onClose={closeMenu}
anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
transformOrigin={{ vertical: 'top', horizontal: 'right' }}
>
<MenuItem onClick={() => { if (menuAnchor) { handleGenerateInitial(menuAnchor.fileId); closeMenu(); } }}>
Process manually
</MenuItem>
<MenuItem onClick={goToAIContent}>Open AI content</MenuItem>
</Menu>
{/* Directory Upload Dialog */}
<Dialog open={showUploadDialog} onClose={() => !isUploading && setShowUploadDialog(false)} maxWidth="md" fullWidth>
<DialogTitle>
<Box display="flex" alignItems="center" gap={1}>
<CloudUploadIcon />
Directory Upload
{isUploading && <CircularProgress size={20} />}
</Box>
</DialogTitle>
<DialogContent>
{directoryStats && (
<Box sx={{ mb: 2 }}>
<Alert severity="info">
<Typography variant="body2">
<strong>{directoryStats.fileCount} files</strong> in{' '}
<strong>{directoryStats.directoryCount} folders</strong><br/>
Total size: <strong>{directoryStats.formattedSize}</strong>
</Typography>
</Alert>
</Box>
)}
<Box sx={{ mb: 2 }}>
<Typography variant="h6" gutterBottom>
Upload Progress
</Typography>
{uploadProgress.length > 0 && (
<>
<Box sx={{ mb: 1 }}>
<Typography variant="body2" color="textSecondary">
{uploadProgress.filter(p => p.status === 'done').length} / {uploadProgress.length} files completed
</Typography>
<LinearProgress
variant="determinate"
value={(uploadProgress.filter(p => p.status === 'done').length / uploadProgress.length) * 100}
sx={{ mt: 1 }}
/>
</Box>
<Box sx={{ maxHeight: 300, overflow: 'auto', border: '1px solid', borderColor: 'divider', borderRadius: 1 }}>
<table style={{ width: '100%', fontSize: '0.875rem' }}>
<thead>
<tr style={{ borderBottom: '1px solid', backgroundColor: 'rgba(0,0,0,0.05)' }}>
<th style={{ textAlign: 'left', padding: '8px' }}>Path</th>
<th style={{ textAlign: 'right', padding: '8px' }}>Size</th>
<th style={{ textAlign: 'center', padding: '8px' }}>Status</th>
</tr>
</thead>
<tbody>
{uploadProgress.map((item, i) => (
<tr key={i} style={{ borderBottom: '1px solid rgba(0,0,0,0.1)' }}>
<td style={{ padding: '4px 8px', maxWidth: 300, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{item.path}
</td>
<td style={{ padding: '4px 8px', textAlign: 'right' }}>
{formatFileSize(item.size)}
</td>
<td style={{ padding: '4px 8px', textAlign: 'center' }}>
<Chip
label={item.status}
size="small"
color={
item.status === 'done' ? 'success' :
item.status === 'error' ? 'error' :
item.status === 'uploading' ? 'primary' : 'default'
}
/>
</td>
</tr>
))}
</tbody>
</table>
</Box>
</>
)}
</Box>
</DialogContent>
<DialogActions>
<Button onClick={() => setShowUploadDialog(false)} disabled={isUploading}>
Cancel
</Button>
<Button
onClick={startDirectoryUpload}
variant="contained"
disabled={isUploading || selectedFiles.length === 0}
startIcon={isUploading ? <CircularProgress size={16} /> : <CloudUploadIcon />}
>
{isUploading ? 'Uploading...' : 'Start Upload'}
</Button>
</DialogActions>
</Dialog>
</Container>
</ThemeProvider>
);
};
export default CCFilesPanelEnhanced;
@@ -4,11 +4,21 @@ export const PANEL_DIMENSIONS = {
topOffset: `0px`,
bottomOffset: '0px',
},
'cabinets': {
width: '300px',
topOffset: `0px`,
bottomOffset: '0px',
},
'node-snapshot': {
width: '300px',
topOffset: `0px`,
bottomOffset: '0px',
},
'files': {
width: '300px',
topOffset: `0px`,
bottomOffset: '0px',
},
'cc-shapes': {
width: '300px',
topOffset: `0px`,
@@ -17,7 +17,7 @@ export function ToolsToolbar({ children }: { children: (props: {
console.error("User node is not available");
return;
}
const existingNode = graphState.getNode(userNode.unique_id);
const existingNode = graphState.getNode(userNode.uuid_string);
if (!existingNode) {
console.log("Adding user node to graphState:", userNode);
const centerX = editor.getViewportScreenCenter().x
@@ -54,7 +54,7 @@ export function ToolsToolbar({ children }: { children: (props: {
}
}
} else {
console.log(`Node with id ${userNode.unique_id} already exists on the canvas.`);
console.log(`Node with id ${userNode.uuid_string} already exists on the canvas.`);
}
};