diff --git a/core/Document/DocumentCollection.go b/core/Document/DocumentCollection.go index 4419c72..dc721cd 100644 --- a/core/Document/DocumentCollection.go +++ b/core/Document/DocumentCollection.go @@ -19,6 +19,11 @@ func (collection *DocumentCollection) AddDocument(document Entity) { collection.Documents = append(collection.Documents, document) } +func SetDocumentCollection(collection DocumentCollection) *DocumentCollection { + documentCollectionInstance = &collection + return documentCollectionInstance +} + func (collection *DocumentCollection) GetDocumentById(id string) *Entity { var foundDocument *Entity diff --git a/core/Document/DocumentGroup.go b/core/Document/DocumentGroup.go index 192f62e..74221e3 100644 --- a/core/Document/DocumentGroup.go +++ b/core/Document/DocumentGroup.go @@ -24,6 +24,11 @@ func GetGroupCollection() *GroupCollection { return groupCollectionInstance } +func SetGroupCollection(collection GroupCollection) *GroupCollection { + groupCollectionInstance = &collection + return groupCollectionInstance +} + func (collection *GroupCollection) AddDocumentGroup(group Group) { collection.Groups = append(collection.Groups, group) } diff --git a/frontend/context/Project/provider.tsx b/frontend/context/Project/provider.tsx index 88f10ab..e9ff3d6 100644 --- a/frontend/context/Project/provider.tsx +++ b/frontend/context/Project/provider.tsx @@ -11,8 +11,9 @@ import { RequestChangeAreaOrder, RequestDeleteAreaById, RequestChangeGroupOrder, - GetProjectByName, RequestChangeSessionProjectByName, + RequestSaveDocumentCollection, + RequestSaveGroupCollection, } from '../../wailsjs/wailsjs/go/ipc/Channel' import { ipc } from '../../wailsjs/wailsjs/go/models' import { AddAreaProps, AreaProps, ProjectContextType, ProjectProps, UpdateDocumentRequest, UserProps } from './types' @@ -24,8 +25,6 @@ export function useProject() { return useContext(ProjectContext) } -let attempts = 0 - type Props = { children: ReactNode, projectProps: ProjectProps } export function ProjectProvider({ children, projectProps }: Props) { const [documents, setDocuments] = useState(projectProps.documents) @@ -34,10 +33,25 @@ export function ProjectProvider({ children, projectProps }: Props) { const [selectedDocumentId, setSelectedDocumentId] = useState('') const [currentSession, setCurrentSession] = useState(new ipc.Session()) + const saveDocumentsAndGroups = () => { + RequestSaveDocumentCollection().then(success => { + if (!success) console.error('Could not save DocumentCollection') + }).catch(err => { + console.error('Could not save DocumentCollection:', err) + }) + RequestSaveGroupCollection().then(success => { + if (!success) console.error('Could not save GroupCollection') + }).catch(err => { + console.error('Could not save GroupCollection:', err) + }) + } + const updateDocuments = async () => { GetDocuments().then(response => { + console.log(response) if (response.documents.length) setDocuments(response.documents) if (response.groups.length) setGroups(response.groups) + saveDocumentsAndGroups() Promise.resolve(response) }) } @@ -162,6 +176,7 @@ export function ProjectProvider({ children, projectProps }: Props) { const requestSelectProjectByName = async (name: string) => { const successfulResponse = await RequestChangeSessionProjectByName(name) await updateSession() + await updateDocuments() return successfulResponse } @@ -173,7 +188,6 @@ export function ProjectProvider({ children, projectProps }: Props) { useEffect(() => { if ((!currentSession?.user?.localId || !currentSession?.user?.id)) { updateSession() - attempts++ } }, [currentSession?.user?.localId, currentSession?.user?.id]) diff --git a/frontend/wailsjs/wailsjs/go/ipc/Channel.d.ts b/frontend/wailsjs/wailsjs/go/ipc/Channel.d.ts index a254ff4..ccd708e 100755 --- a/frontend/wailsjs/wailsjs/go/ipc/Channel.d.ts +++ b/frontend/wailsjs/wailsjs/go/ipc/Channel.d.ts @@ -42,6 +42,10 @@ export function RequestChooseUserAvatar():Promise; export function RequestDeleteAreaById(arg1:string):Promise; +export function RequestSaveDocumentCollection():Promise; + +export function RequestSaveGroupCollection():Promise; + export function RequestUpdateArea(arg1:ipc.Area):Promise; export function RequestUpdateCurrentUser(arg1:ipc.User):Promise; diff --git a/frontend/wailsjs/wailsjs/go/ipc/Channel.js b/frontend/wailsjs/wailsjs/go/ipc/Channel.js index 498d759..c3de667 100755 --- a/frontend/wailsjs/wailsjs/go/ipc/Channel.js +++ b/frontend/wailsjs/wailsjs/go/ipc/Channel.js @@ -82,6 +82,14 @@ export function RequestDeleteAreaById(arg1) { return window['go']['ipc']['Channel']['RequestDeleteAreaById'](arg1); } +export function RequestSaveDocumentCollection() { + return window['go']['ipc']['Channel']['RequestSaveDocumentCollection'](); +} + +export function RequestSaveGroupCollection() { + return window['go']['ipc']['Channel']['RequestSaveGroupCollection'](); +} + export function RequestUpdateArea(arg1) { return window['go']['ipc']['Channel']['RequestUpdateArea'](arg1); } diff --git a/ipc/Documents.go b/ipc/Documents.go index a85053a..5fc9f17 100644 --- a/ipc/Documents.go +++ b/ipc/Documents.go @@ -6,6 +6,7 @@ import ( consts "textualize/core/Consts" document "textualize/core/Document" session "textualize/core/Session" + storage "textualize/storage/Local" "github.com/google/uuid" "github.com/wailsapp/wails/v2/pkg/runtime" @@ -206,30 +207,6 @@ func (c *Channel) RequestAddDocumentGroup(name string) Group { func (c *Channel) RequestChangeGroupOrder(groupId string, newOrder int) Group { groupCollection := document.GetGroupCollection() - // var foundArea document.Area - // for _, a := range documentOfArea.Areas { - // if a.Id == areaId { - // foundArea = a - // break - // } - // } - - // if foundArea.Id == "" { - // return Document{} - // } - - // processedAreasCollection := document.GetProcessedAreaCollection() - - // for index, a := range documentOfArea.Areas { - // if a.Id == areaId { - // documentOfArea.Areas[index].Order = newOrder - // processedAreasCollection.GetAreaById(a.Id).Order = newOrder - // } else if a.Order >= newOrder { - // documentOfArea.Areas[index].Order = a.Order + 1 - // processedAreasCollection.GetAreaById(a.Id).Order = a.Order + 1 - // } - // } - for _, g := range groupCollection.Groups { if g.Id == groupId { // document.GetGroupCollection().Groups[index].Order = newOrder @@ -355,11 +332,6 @@ func (c *Channel) RequestDeleteAreaById(areaId string) bool { return false } - // func remove(s []int, i int) []int { - // s[i] = s[len(s)-1] - // return s[:len(s)-1] - // } - documentOfArea.Areas[areaToDeleteIndex] = documentOfArea.Areas[len(documentOfArea.Areas)-1] documentOfArea.Areas = documentOfArea.Areas[:len(documentOfArea.Areas)-1] return true @@ -425,3 +397,72 @@ func (c *Channel) RequestChangeAreaOrder(areaId string, newOrder int) Document { return c.GetDocumentById(documentOfArea.Id) } + +func (c *Channel) RequestSaveDocumentCollection() bool { + documentCollection := document.GetDocumentCollection() + projectName := c.GetCurrentSession().Project.Name + + fullProject := storage.ReadLocalProjectByName(projectName) + + if fullProject.Id == "" { + return false + } + + var documentsToWrite []storage.LocalDocument + for _, d := range documentCollection.Documents { + var areasToWrite []storage.LocalArea + for _, a := range d.Areas { + areasToWrite = append(areasToWrite, storage.LocalArea{ + Id: a.Id, + Name: a.Name, + StartX: a.StartX, + StartY: a.StartY, + EndX: a.EndX, + EndY: a.EndY, + Language: storage.Language(a.Language), + Order: a.Order, + }) + } + + documentsToWrite = append(documentsToWrite, storage.LocalDocument{ + Id: d.Id, + GroupId: d.GroupId, + Name: d.Name, + Path: d.Path, + ProjectId: d.ProjectId, + Areas: areasToWrite, + DefaultLanguage: storage.Language(d.DefaultLanguage), + }) + } + + successfulWrite := storage.WriteLocalDocumentCollection(storage.LocalDocumentCollection{ + Documents: documentsToWrite, + ProjectId: fullProject.Id, + }, projectName) + + return successfulWrite +} + +func (c *Channel) RequestSaveGroupCollection() bool { + groupCollection := document.GetGroupCollection() + projectName := c.GetCurrentSession().Project.Name + + fullProject := storage.ReadLocalProjectByName(projectName) + + if fullProject.Id == "" { + return false + } + + var groupsToWrite []storage.LocalGroup + for _, g := range groupCollection.Groups { + groupsToWrite = append(groupsToWrite, storage.LocalGroup(g)) + } + + successfulWrite := storage.WriteLocalGroupCollection(storage.LocalGroupCollection{ + Id: groupCollection.Id, + ProjectId: groupCollection.ProjectId, + Groups: groupsToWrite, + }, projectName) + + return successfulWrite +} diff --git a/ipc/Session.go b/ipc/Session.go index 4b1bc0c..1d413df 100644 --- a/ipc/Session.go +++ b/ipc/Session.go @@ -1,8 +1,10 @@ package ipc import ( + "fmt" app "textualize/core/App" consts "textualize/core/Consts" + document "textualize/core/Document" session "textualize/core/Session" storage "textualize/storage/Local" @@ -179,6 +181,53 @@ func (c *Channel) RequestChangeSessionProjectByName(projectName string) bool { }, } + localDocumentCollection := storage.ReadLocalDocumentCollection(projectName) + newDocuments := make([]document.Entity, 0) + for _, d := range localDocumentCollection.Documents { + newAreas := make([]document.Area, 0) + for _, a := range d.Areas { + newAreas = append(newAreas, document.Area{ + Id: a.Id, + Name: a.Name, + StartX: a.StartX, + StartY: a.StartY, + EndX: a.EndX, + EndY: a.EndY, + Language: consts.Language(a.Language), + Order: a.Order, + }) + } + newDocuments = append(newDocuments, document.Entity{ + Id: d.Id, + GroupId: d.GroupId, + Name: d.Name, + Path: d.Path, + ProjectId: d.ProjectId, + Areas: newAreas, + DefaultLanguage: consts.Language(d.DefaultLanguage), + }) + } + newDocumentColllection := document.DocumentCollection{ + Documents: newDocuments, + ProjectId: foundProject.Id, + } + document.SetDocumentCollection(newDocumentColllection) + + localGroupsCollection := storage.ReadLocalGroupCollection(projectName) + newGroups := make([]document.Group, 0) + for _, g := range localGroupsCollection.Groups { + newGroups = append(newGroups, document.Group(g)) + } + newGroupCollection := document.GroupCollection{ + Id: localGroupsCollection.Id, + ProjectId: localGroupsCollection.ProjectId, + Groups: newGroups, + } + document.SetGroupCollection(newGroupCollection) + + fmt.Println("newSESSION_______") + fmt.Println(document.GetDocumentCollection()) + return session.GetInstance().Project.Id == foundProject.Id } diff --git a/storage/Local/Interface.go b/storage/Local/Interface.go index e202052..3c66aa2 100644 --- a/storage/Local/Interface.go +++ b/storage/Local/Interface.go @@ -4,7 +4,6 @@ import ( "encoding/json" "fmt" "os" - "strings" ) func GetLocalStoragePath() string { @@ -88,7 +87,7 @@ func ReadLocalUserData() LocalUser { } func ReadLocalProjectByName(name string) LocalProject { - file, err := os.ReadFile(GetLocalStoragePath() + "/projects/" + name + ".json") + file, err := os.ReadFile(GetLocalStoragePath() + "/projects/" + name + "/Project.json") if err != nil { return LocalProject{} @@ -111,13 +110,13 @@ func WriteLocalProjectData(project LocalProject) bool { return false } - subdirectory := "/projects/" + subdirectory := "/projects/" + project.Name + "/" isLocalStorageDirectoryCreated := createLocalStorageSubDirIfNeeded(subdirectory) if !isLocalStorageDirectoryCreated { return false } - err := os.WriteFile(GetLocalStoragePath()+subdirectory+project.Name+".json", file, 0644) + err := os.WriteFile(GetLocalStoragePath()+subdirectory+project.Name+"/Project.json", file, 0644) return err == nil } @@ -138,8 +137,9 @@ func ReadAllLocalProjects() []LocalProject { } localProjectNames := make([]string, 0) - for _, fileName := range localProjectFileEntries { - localProjectNames = append(localProjectNames, strings.ReplaceAll(fileName.Name(), ".json", "")) + for _, fileEntry := range localProjectFileEntries { + localProjectNames = append(localProjectNames, fileEntry.Name()) + // localProjectNames = append(localProjectNames, strings.ReplaceAll(fileName.Name(), ".json", "")) } for _, projectName := range localProjectNames { @@ -148,3 +148,73 @@ func ReadAllLocalProjects() []LocalProject { return localProjects } + +func WriteLocalDocumentCollection(documentCollection LocalDocumentCollection, projectName string) bool { + file, _ := json.MarshalIndent(documentCollection, "", " ") + path := GetLocalStoragePath() + + if path == "" { + return false + } + + subdirectory := "/projects/" + projectName + isLocalStorageDirectoryCreated := createLocalStorageSubDirIfNeeded(subdirectory) + if !isLocalStorageDirectoryCreated { + return false + } + + err := os.WriteFile(GetLocalStoragePath()+subdirectory+"/Documents.json", file, 0644) + + return err == nil +} + +func ReadLocalDocumentCollection(projectName string) LocalDocumentCollection { + file, err := os.ReadFile(GetLocalStoragePath() + "/projects/" + projectName + "/Documents.json") + + if err != nil { + return LocalDocumentCollection{} + } + + response := LocalDocumentCollection{} + errorUnmarshaling := json.Unmarshal([]byte(file), &response) + if errorUnmarshaling != nil { + return LocalDocumentCollection{} + } + + return response +} + +func WriteLocalGroupCollection(groupCollection LocalGroupCollection, projectName string) bool { + file, _ := json.MarshalIndent(groupCollection, "", " ") + path := GetLocalStoragePath() + + if path == "" { + return false + } + + subdirectory := "/projects/" + projectName + isLocalStorageDirectoryCreated := createLocalStorageSubDirIfNeeded(subdirectory) + if !isLocalStorageDirectoryCreated { + return false + } + + err := os.WriteFile(GetLocalStoragePath()+subdirectory+"/Groups.json", file, 0644) + + return err == nil +} + +func ReadLocalGroupCollection(projectName string) LocalGroupCollection { + file, err := os.ReadFile(GetLocalStoragePath() + "/projects/" + projectName + "/Groups.json") + + if err != nil { + return LocalGroupCollection{} + } + + response := LocalGroupCollection{} + errorUnmarshaling := json.Unmarshal([]byte(file), &response) + if errorUnmarshaling != nil { + return LocalGroupCollection{} + } + + return response +} diff --git a/storage/Local/JsonEntities.go b/storage/Local/JsonEntities.go index 673ea8b..5b2119b 100644 --- a/storage/Local/JsonEntities.go +++ b/storage/Local/JsonEntities.go @@ -28,3 +28,43 @@ type LocalUser struct { AuthToken string `json:"authToken"` Email string `json:"email"` } + +type LocalDocument struct { + Id string `json:"id"` + GroupId string `json:"groupId"` + Name string `json:"name"` + Path string `json:"path"` + ProjectId string `json:"projectId"` + Areas []LocalArea `json:"areas"` + DefaultLanguage Language `json:"defaultLanguage"` +} + +type LocalDocumentCollection struct { + Documents []LocalDocument `json:"documents"` + ProjectId string `json:"projectId"` +} + +type LocalArea struct { + Id string `json:"id"` + Name string `json:"name"` + StartX int `json:"startX"` + StartY int `json:"startY"` + EndX int `json:"endX"` + EndY int `json:"endY"` + Language Language `json:"language"` + Order int `json:"order"` +} + +type LocalGroup struct { + Id string `json:"id"` + ParentId string `json:"parentId"` + ProjectId string `json:"projectId"` + Name string `json:"name"` + Order int `json:"order"` +} + +type LocalGroupCollection struct { + Id string `json:"id"` + Groups []LocalGroup `json:"groups"` + ProjectId string `json:"projectId"` +}