summaryrefslogtreecommitdiff
path: root/apps/web/src/components/providers/migrators/scenes-migrator.tsx
blob: 521e24af6e7e8c3f381e369c80f0793f00d8657e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
"use client";

import { useEffect, useState } from "react";
import { usePathname } from "next/navigation";
import { storageService } from "@/lib/storage/storage-service";
import { TProject, Scene } from "@/types/project";
import { generateUUID } from "@/lib/utils";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Progress } from "@/components/ui/progress";
import { createMainScene } from "@/stores/project-store";

interface MigrationProgress {
  current: number;
  total: number;
  currentProjectName: string;
}

export function ScenesMigrator({ children }: { children: React.ReactNode }) {
  const pathname = usePathname();
  const [isMigrating, setIsMigrating] = useState(false);
  const [progress, setProgress] = useState<MigrationProgress>({
    current: 0,
    total: 0,
    currentProjectName: "",
  });

  const shouldCheckMigration =
    pathname.startsWith("/editor") || pathname.startsWith("/projects");

  useEffect(() => {
    if (!shouldCheckMigration) return;

    checkAndMigrateProjects();
  }, [shouldCheckMigration]);

  const checkAndMigrateProjects = async () => {
    try {
      const projects = await storageService.loadAllProjects();
      const legacyProjects = projects.filter(
        (project) => !project.scenes || project.scenes.length === 0
      );

      if (legacyProjects.length === 0) {
        // No migration needed
        return;
      }

      setIsMigrating(true);
      setProgress({
        current: 0,
        total: legacyProjects.length,
        currentProjectName: "",
      });

      // Migrate each legacy project
      for (let i = 0; i < legacyProjects.length; i++) {
        const project = legacyProjects[i];

        setProgress({
          current: i,
          total: legacyProjects.length,
          currentProjectName: project.name,
        });

        await migrateLegacyProject(project);
      }

      setProgress({
        current: legacyProjects.length,
        total: legacyProjects.length,
        currentProjectName: "Complete!",
      });

      setTimeout(() => {
        setIsMigrating(false);
      }, 1000);
    } catch (error) {
      console.error("Migration failed:", error);
      setIsMigrating(false);
    }
  };

  const migrateLegacyProject = async (project: TProject) => {
    try {
      const mainScene: Scene = {
        id: generateUUID(),
        name: "Main Scene",
        isMain: true,
        isBackground: false,
        createdAt: new Date(),
        updatedAt: new Date(),
      };

      const backgroundScene: Scene = {
        id: generateUUID(),
        name: "Background",
        isMain: false,
        isBackground: true,
        createdAt: new Date(),
        updatedAt: new Date(),
      };

      const migratedProject: TProject = {
        ...project,
        scenes: [mainScene, backgroundScene],
        currentSceneId: mainScene.id,
        updatedAt: new Date(),
      };

      // Load existing timeline data (legacy format)
      const legacyTimeline = await storageService.loadTimeline({
        projectId: project.id,
      });

      await storageService.saveProject({ project: migratedProject });

      // If timeline data, migrate it to the main scene
      if (legacyTimeline && legacyTimeline.length > 0) {
        await storageService.saveTimeline({
          projectId: project.id,
          tracks: legacyTimeline,
          sceneId: mainScene.id,
        });
      }

      // Clean up legacy timeline storage
      await storageService.deleteProjectTimeline({ projectId: project.id });
    } catch (error) {
      console.error(`Failed to migrate project ${project.name}:`, error);
      throw error;
    }
  };

  if (!shouldCheckMigration) {
    return children;
  }

  if (isMigrating) {
    const progressPercent =
      progress.total > 0 ? (progress.current / progress.total) * 100 : 0;

    return (
      <Dialog open={true}>
        <DialogContent
          className="sm:max-w-md"
          onPointerDownOutside={(e) => e.preventDefault()}
        >
          <DialogHeader>
            <DialogTitle>Updating Projects</DialogTitle>
            <DialogDescription>
              We're adding scene support to your projects. This will only take a
              moment.
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            <div className="space-y-2">
              <div className="flex justify-between text-sm">
                <span>Progress</span>
                <span>
                  {progress.current} of {progress.total}
                </span>
              </div>
              <Progress value={progressPercent} className="w-full" />
            </div>

            {progress.currentProjectName && (
              <div className="text-sm text-muted-foreground">
                {progress.current < progress.total
                  ? `Updating: ${progress.currentProjectName}`
                  : progress.currentProjectName}
              </div>
            )}
          </div>
        </DialogContent>
      </Dialog>
    );
  }

  return children;
}