Skip to content

Commit

Permalink
feat: fixing addDocuments and target controls mismatch
Browse files Browse the repository at this point in the history
  • Loading branch information
hlolli committed Jan 4, 2025
1 parent b156389 commit 081801c
Show file tree
Hide file tree
Showing 10 changed files with 111 additions and 177 deletions.
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"deploy": "./node_modules/.bin/firebase deploy -P default --token=$FIREBASE_TOKEN",
"deploy:dev": "./node_modules/.bin/firebase deploy -P develop --token=$FIREBASE_TOKEN",
"precommit-hook": "npm run lint:check",
"prepare": "husky install"
"prepare": "husky"
},
"dependencies": {
"@csound/browser": "^6.18.7",
Expand All @@ -25,7 +25,7 @@
"@emotion/css": "^11.13.5",
"@emotion/react": "^11.14.0",
"@emotion/styled": "^11.14.0",
"@hlolli/codemirror-lang-csound": "^1.0.0-alpha9",
"@hlolli/codemirror-lang-csound": "^1.0.0-alpha10",
"@mui/icons-material": "^6.2.0",
"@mui/material": "^6.2.0",
"@reduxjs/toolkit": "^2.5.0",
Expand Down
90 changes: 38 additions & 52 deletions src/components/editor/editor.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useCallback, useEffect, useRef, useState } from "react";
import { useCallback, useEffect, useRef, useState } from "react";
import { useDispatch, useSelector } from "@root/store";
import { csoundMode } from "@hlolli/codemirror-lang-csound";
import { EditorView } from "codemirror";
Expand Down Expand Up @@ -27,7 +27,6 @@ import { EditorState, StateField } from "@codemirror/state";
import { filenameToCsoundType } from "@comp/csound/utils";
import { evalBlinkExtension } from "./utils";
import { IDocument, IProject } from "../projects/types";
import { reject, pathOr, propOr } from "ramda";
import * as projectActions from "../projects/actions";
import { editorStyle } from "@styles/code-mirror-painter";

Expand All @@ -40,30 +39,26 @@ const histories: Record<string, any> = {};
const getInitialState = (
documentUid: string
): { json: any; fields: any } | undefined => {
const hasHistory = Boolean(stateFields[documentUid + ":serialized"]);
const hasHistory = !!stateFields[`${documentUid}:serialized`];
stateFields[documentUid] = stateFields[documentUid] || {};
stateFields[documentUid].history =
stateFields[documentUid].history || historyField;
return hasHistory
? {
json: JSON.parse(stateFields[documentUid + ":serialized"]),
json: JSON.parse(stateFields[`${documentUid}:serialized`]),
fields: stateFields[documentUid]
}
: undefined;
};

const getInitialScrollPosition = (documentUid: string): number => {
return scrollPos[documentUid] || 0;
};
const getInitialScrollPosition = (documentUid: string): number =>
scrollPos[documentUid] || 0;

const getHistory = (documentUid: string): any => {
const previousHistory = histories[documentUid];
if (previousHistory) {
return previousHistory;
} else {
if (!histories[documentUid]) {
histories[documentUid] = history();
return histories[documentUid];
}
return histories[documentUid];
};

const CodeEditor = ({
Expand All @@ -72,30 +67,25 @@ const CodeEditor = ({
}: {
documentUid: string;
projectUid: string;
}): React.ReactElement => {
const editorReference = useRef(null);
}) => {
const editorReference = useRef<HTMLDivElement>(null);
const [isMounted, setIsMounted] = useState(false);
const dispatch = useDispatch();

const project = useSelector(
pathOr({} as IProject, ["ProjectsReducer", "projects", projectUid])
(state: any) =>
state?.ProjectsReducer?.projects?.[projectUid] ?? ({} as IProject)
);

const document = pathOr(
{} as IDocument,
["documents", documentUid],
project
);
const document = project?.documents?.[documentUid] ?? ({} as IDocument);

const csoundFileType = filenameToCsoundType(document.filename || "");

const [csoundDocumentStateField, setCsoundDocumentStateField] = useState(
undefined as
| StateField<{ documentUid: string; documentType: string }>
| undefined
);
const [csoundDocumentStateField, setCsoundDocumentStateField] = useState<
StateField<{ documentUid: string; documentType: string }> | undefined
>(undefined);

const currentDocumentValue: string = propOr("", "currentValue", document);
const currentDocumentValue: string = document.currentValue || "";

const onChange = useCallback(
(event: any) => {
Expand Down Expand Up @@ -132,17 +122,16 @@ const CodeEditor = ({
"scroll",
onScroll
);

editorStateInstance.destroy();
openEditors.delete(documentUid);
}
};
}, [isMounted, setIsMounted, documentUid, onScroll]);
}, [isMounted, documentUid, onScroll]);

useEffect(() => {
if (editorReference.current && !openEditors.has(documentUid)) {
const initialState = getInitialState(documentUid);
// console.log({ initialState });

const config = {
extensions: [
lineNumbers(),
Expand All @@ -154,21 +143,21 @@ const CodeEditor = ({
EditorState.allowMultipleSelections.of(true),
indentOnInput(),
csoundMode({
fileType: (["sco", "orc", "csd"].includes(
csoundFileType || ""
)
? csoundFileType
: "orc") as "sco" | "orc" | "csd"
fileType:
csoundFileType &&
((["sco", "orc", "csd"].includes(csoundFileType)
? csoundFileType
: "orc") as "sco" | "orc" | "csd")
}),
keymap.of([
...reject(
(keyb: any) =>
[
...defaultKeymap.filter(
(keyb) =>
keyb &&
![
"Mod-Enter",
"Comd-Enter",
"Ctrl-Enter"
].includes(keyb.key),
defaultKeymap
].includes(keyb.key || "")
),
...historyKeymap
]),
Expand All @@ -181,40 +170,43 @@ const CodeEditor = ({
crosshairCursor()
]
};

const newEditor = initialState
? new EditorView({
state: EditorState.fromJSON(
initialState?.json || {},
initialState.json,
config,
initialState?.fields || {}
initialState.fields
),

parent: editorReference.current
})
: new EditorView({
extensions: config.extensions,
parent: editorReference.current
});

newEditor.scrollDOM.addEventListener("scroll", onScroll);
openEditors.set(documentUid, newEditor);

newEditor.dispatch({
changes: {
from: 0,
to: newEditor.state.doc.length,
insert: currentDocumentValue
}
});

const initialScrollPosition = getInitialScrollPosition(documentUid);
if (initialScrollPosition > 0) {
newEditor.scrollDOM.scrollTop = initialScrollPosition;
for (const timeout of [1, 10, 100]) {
[1, 10, 100].forEach((timeout) =>
setTimeout(() => {
try {
newEditor.scrollDOM.scrollTop =
initialScrollPosition;
} catch {}
}, timeout);
}
}, timeout)
);
}
}
}, [
Expand All @@ -241,13 +233,7 @@ const CodeEditor = ({
})
);
}
}, [
isMounted,
documentUid,
csoundFileType,
csoundDocumentStateField,
setCsoundDocumentStateField
]);
}, [isMounted, documentUid, csoundFileType, csoundDocumentStateField]);

return <div ref={editorReference} css={editorStyle} />;
};
Expand Down
75 changes: 20 additions & 55 deletions src/components/file-tree/index.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
import React, { useState, useCallback } from "react";
import {
AppThunkDispatch,
RootState,
useDispatch,
useSelector
} from "@root/store";
import { AppThunkDispatch, useDispatch, useSelector } from "@root/store";
import { getAuth } from "firebase/auth";
import { uploadBytesResumable } from "firebase/storage";
import { addDoc, collection, doc } from "firebase/firestore";
Expand All @@ -14,29 +9,7 @@ import {
projects,
storageReference
} from "@config/firestore";
import {
addIndex,
append,
assoc,
both,
concat,
curry,
find,
filter,
isEmpty,
last,
mergeAll,
not,
reduce,
reject,
sort,
path,
pathOr,
pipe,
propEq,
propOr,
values
} from "ramda";
import { curry, path, propOr, values } from "ramda";
import { Mime } from "mime";
import moment from "moment";
import { openSnackbar } from "@comp/snackbar/actions";
Expand Down Expand Up @@ -85,8 +58,6 @@ import { NonCloudFile } from "./types";

const mime = new Mime();

const reduceIndexed = addIndex(reduce);

const RootReference = React.forwardRef((properties: any, reference: any) => (
<div ref={reference} {...properties}>
{properties.children}
Expand Down Expand Up @@ -654,35 +625,27 @@ export const FileTree = ({
}: {
activeProjectUid: string;
}) => {
const [collapseState, setCollapseState] = useState({});
// const [isLoaded, setIsLoaded] = useState(false);
const [collapseState, setCollapseState] = useState<Record<string, boolean>>(
{}
);
const [stateDnD] = useDnD();
const dispatch = useDispatch();
const theme = useTheme();

const nonCloudFileTreeEntries: string[] = useSelector(selectNonCloudFiles);
const nonCloudFileSources: NonCloudFile[] = [];

for (const ncfEntry of nonCloudFileTreeEntries) {
if (nonCloudFiles.has(ncfEntry)) {
nonCloudFileSources.push(
nonCloudFiles.get(ncfEntry) as NonCloudFile
);
}
}
// console.log({ nonCloudFileSources, nonCloudFileTreeEntries });
const isOwner: boolean = useSelector(selectIsOwner);
const project: IProject | undefined = useSelector(
path(["ProjectsReducer", "projects", activeProjectUid])
);

const documents: IDocumentsMap | undefined = useSelector(
path(["ProjectsReducer", "projects", activeProjectUid, "documents"])
);

// Selectors
const nonCloudFileTreeEntries = useSelector(selectNonCloudFiles) || [];
const isOwner = useSelector(selectIsOwner);
const currentTabDocumentUid = useSelector(selectCurrentTabDocumentUid);
const project = useSelector(
(state) => state.ProjectsReducer.projects?.[activeProjectUid]
);
const documents = project?.documents || {};

const filelist = values(documents || {});
// Extract file list and map non-cloud files
const filelist = Object.values(documents);
const nonCloudFileSources = nonCloudFileTreeEntries
.map((entry) => nonCloudFiles.get(entry))
.filter((file): file is NonCloudFile => !!file);

return (
<React.Fragment>
Expand All @@ -705,7 +668,9 @@ export const FileTree = ({
}
{nonCloudFileSources.length > 0 && <hr />}
{nonCloudFileSources.map((file, index) => {
const mimeType = mime.getType(file.name);
const mimeType =
mime.getType(file.name) ||
"application/octet-stream";

return (
<div
Expand Down
2 changes: 1 addition & 1 deletion src/components/project-editor/actions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export const tabDockInit = (
console.error(error);
}
}
console.log("Initial open documents", defaultTarget);

if (
defaultTarget &&
defaultTarget.targetDocumentUid &&
Expand Down
13 changes: 3 additions & 10 deletions src/components/project-editor/selectors.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -64,15 +64,8 @@ export const selectCurrentTabDocumentUid = (
): string | undefined => {
const tabIndex = selectTabDockIndex(store);
if (tabIndex > -1) {
return path(
[
"ProjectEditorReducer",
"tabDock",
"openDocuments",
tabIndex,
"uid"
],
store
);
return store?.ProjectEditorReducer?.tabDock?.openDocuments?.[tabIndex]
?.uid;
}
return undefined;
};
16 changes: 9 additions & 7 deletions src/components/projects/actions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -120,10 +120,12 @@ export const downloadAllProjectDocumentsOnce = (
const allDocuments = await Promise.all(
filesReference.docs.map(async (d) => {
const data = d.data() as IFirestoreDocument;
return fileDocumentDataToDocumentType({
...data,
documentUid: d.id
});
return fileDocumentDataToDocumentType(
{
...data
},
d.id
);
})
);
const allDocumentsMap = reduce(
Expand Down Expand Up @@ -193,11 +195,11 @@ export const unsetProject = (projectUid: string) => {
export const addProjectDocuments = (
projectUid: string,
documents: IDocumentsMap
): ((dispatch: any, getState: () => RootState) => Promise<void>) => {
return async (dispatch: any, getState) => {
) => {
return async (dispatch: AppThunkDispatch, getState: () => RootState) => {
const store: RootState = getState();
const tabIndex: number = selectTabDockIndex(store);
await dispatch({
dispatch({
type: ADD_PROJECT_DOCUMENTS,
projectUid,
documents
Expand Down
Loading

0 comments on commit 081801c

Please sign in to comment.