Fix settings saving

This commit is contained in:
2024-10-22 21:21:18 +02:00
parent a231fc48c2
commit 05dd3a83b0
8 changed files with 66 additions and 47 deletions

View File

@@ -218,21 +218,29 @@ func UpdateWorkspaceSettings(db *db.DB, fs *filesystem.FileSystem) http.HandlerF
return return
} }
var settings models.WorkspaceSettings var userSettings models.UserSettings
if err := json.NewDecoder(r.Body).Decode(&settings); err != nil { if err := json.NewDecoder(r.Body).Decode(&userSettings); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
if err := userSettings.Validate(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest) http.Error(w, err.Error(), http.StatusBadRequest)
return return
} }
settings.WorkspaceID = workspaceID workspaceSettings := &models.WorkspaceSettings{
WorkspaceID: workspaceID,
Settings: userSettings,
}
if err := db.SaveWorkspaceSettings(&settings); err != nil { if err := db.SaveWorkspaceSettings(workspaceSettings); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError) http.Error(w, err.Error(), http.StatusInternalServerError)
return return
} }
if settings.Settings.GitEnabled { if userSettings.GitEnabled {
err := fs.SetupGitRepo(userID, workspaceID, settings.Settings.GitURL, settings.Settings.GitUser, settings.Settings.GitToken) err := fs.SetupGitRepo(userID, workspaceID, userSettings.GitURL, userSettings.GitUser, userSettings.GitToken)
if err != nil { if err != nil {
http.Error(w, "Failed to setup git repo", http.StatusInternalServerError) http.Error(w, "Failed to setup git repo", http.StatusInternalServerError)
return return
@@ -241,6 +249,6 @@ func UpdateWorkspaceSettings(db *db.DB, fs *filesystem.FileSystem) http.HandlerF
fs.DisableGitRepo(userID, workspaceID) fs.DisableGitRepo(userID, workspaceID)
} }
respondJSON(w, settings) respondJSON(w, workspaceSettings)
} }
} }

View File

@@ -17,6 +17,17 @@ type UserService struct {
FS *filesystem.FileSystem FS *filesystem.FileSystem
} }
// Default settings for new workspaces
var defaultWorkspaceSettings = models.WorkspaceSettings{
Settings: models.UserSettings{
Theme: "light",
AutoSave: false,
GitEnabled: false,
GitAutoCommit: false,
GitCommitMsgTemplate: "${action} ${filename}",
},
}
func NewUserService(database *db.DB, fs *filesystem.FileSystem) *UserService { func NewUserService(database *db.DB, fs *filesystem.FileSystem) *UserService {
return &UserService{ return &UserService{
DB: database, DB: database,
@@ -62,6 +73,13 @@ func (s *UserService) SetupAdminUser() (*models.User, error) {
return nil, fmt.Errorf("failed to initialize admin workspace: %w", err) return nil, fmt.Errorf("failed to initialize admin workspace: %w", err)
} }
// Save default settings for the admin workspace
defaultWorkspaceSettings.WorkspaceID = adminUser.LastWorkspaceID
err = s.DB.SaveWorkspaceSettings(&defaultWorkspaceSettings)
if err != nil {
return nil, fmt.Errorf("failed to save default workspace settings: %w", err)
}
log.Printf("Created admin user with ID: %d and default workspace with ID: %d", adminUser.ID, adminUser.LastWorkspaceID) log.Printf("Created admin user with ID: %d and default workspace with ID: %d", adminUser.ID, adminUser.LastWorkspaceID)
return adminUser, nil return adminUser, nil
@@ -78,6 +96,14 @@ func (s *UserService) CreateUser(user *models.User) error {
return fmt.Errorf("failed to initialize user workspace: %w", err) return fmt.Errorf("failed to initialize user workspace: %w", err)
} }
// Save default settings for the user's workspace
settings := defaultWorkspaceSettings
settings.WorkspaceID = user.LastWorkspaceID
err = s.DB.SaveWorkspaceSettings(&settings)
if err != nil {
return fmt.Errorf("failed to save default workspace settings: %w", err)
}
return nil return nil
} }

View File

@@ -8,7 +8,7 @@ import { oneDark } from '@codemirror/theme-one-dark';
import { useWorkspace } from '../contexts/WorkspaceContext'; import { useWorkspace } from '../contexts/WorkspaceContext';
const Editor = ({ content, handleContentChange, handleSave, selectedFile }) => { const Editor = ({ content, handleContentChange, handleSave, selectedFile }) => {
const { settings } = useWorkspace(); const { colorScheme } = useWorkspace();
const editorRef = useRef(); const editorRef = useRef();
const viewRef = useRef(); const viewRef = useRef();
@@ -27,12 +27,12 @@ const Editor = ({ content, handleContentChange, handleSave, selectedFile }) => {
overflow: 'auto', overflow: 'auto',
}, },
'.cm-gutters': { '.cm-gutters': {
backgroundColor: settings.theme === 'dark' ? '#1e1e1e' : '#f5f5f5', backgroundColor: colorScheme === 'dark' ? '#1e1e1e' : '#f5f5f5',
color: settings.theme === 'dark' ? '#858585' : '#999', color: colorScheme === 'dark' ? '#858585' : '#999',
border: 'none', border: 'none',
}, },
'.cm-activeLineGutter': { '.cm-activeLineGutter': {
backgroundColor: settings.theme === 'dark' ? '#2c313a' : '#e8e8e8', backgroundColor: colorScheme === 'dark' ? '#2c313a' : '#e8e8e8',
}, },
}); });
@@ -56,7 +56,7 @@ const Editor = ({ content, handleContentChange, handleSave, selectedFile }) => {
} }
}), }),
theme, theme,
settings.theme === 'dark' ? oneDark : [], colorScheme === 'dark' ? oneDark : [],
], ],
}); });
@@ -70,7 +70,7 @@ const Editor = ({ content, handleContentChange, handleSave, selectedFile }) => {
return () => { return () => {
view.destroy(); view.destroy();
}; };
}, [settings.theme, handleContentChange]); }, [colorScheme, handleContentChange]);
useEffect(() => { useEffect(() => {
if (viewRef.current && content !== viewRef.current.state.doc.toString()) { if (viewRef.current && content !== viewRef.current.state.doc.toString()) {

View File

@@ -36,8 +36,8 @@ const Layout = () => {
p={0} p={0}
style={{ style={{
display: 'flex', display: 'flex',
height: 'calc(100vh - 60px - 2rem)', height: 'calc(100vh - 60px - 2rem)', // Subtracting header height and vertical padding
overflow: 'hidden', overflow: 'hidden', // Prevent scrolling in the container
}} }}
> >
<Sidebar <Sidebar

View File

@@ -38,19 +38,13 @@ function settingsReducer(state, action) {
initialSettings: state.localSettings, initialSettings: state.localSettings,
hasUnsavedChanges: false, hasUnsavedChanges: false,
}; };
case 'RESET':
return {
...state,
localSettings: state.initialSettings,
hasUnsavedChanges: false,
};
default: default:
return state; return state;
} }
} }
const Settings = () => { const Settings = () => {
const { settings, updateSettings, colorScheme } = useWorkspace(); const { settings, updateSettings } = useWorkspace();
const { settingsModalVisible, setSettingsModalVisible } = useModalContext(); const { settingsModalVisible, setSettingsModalVisible } = useModalContext();
const [state, dispatch] = useReducer(settingsReducer, initialState); const [state, dispatch] = useReducer(settingsReducer, initialState);
const isInitialMount = useRef(true); const isInitialMount = useRef(true);
@@ -62,13 +56,6 @@ const Settings = () => {
} }
}, [settings]); }, [settings]);
useEffect(() => {
dispatch({
type: 'UPDATE_LOCAL_SETTINGS',
payload: { theme: colorScheme },
});
}, [colorScheme]);
const handleInputChange = useCallback((key, value) => { const handleInputChange = useCallback((key, value) => {
dispatch({ type: 'UPDATE_LOCAL_SETTINGS', payload: { [key]: value } }); dispatch({ type: 'UPDATE_LOCAL_SETTINGS', payload: { [key]: value } });
}, []); }, []);
@@ -92,11 +79,8 @@ const Settings = () => {
}; };
const handleClose = useCallback(() => { const handleClose = useCallback(() => {
if (state.hasUnsavedChanges) {
dispatch({ type: 'RESET' });
}
setSettingsModalVisible(false); setSettingsModalVisible(false);
}, [state.hasUnsavedChanges, setSettingsModalVisible]); }, [setSettingsModalVisible]);
return ( return (
<Modal <Modal

View File

@@ -2,12 +2,13 @@ import React from 'react';
import { Text, Switch, Group, Box, Title } from '@mantine/core'; import { Text, Switch, Group, Box, Title } from '@mantine/core';
import { useWorkspace } from '../../contexts/WorkspaceContext'; import { useWorkspace } from '../../contexts/WorkspaceContext';
const AppearanceSettings = ({ onThemeChange }) => { const AppearanceSettings = ({ themeSettings, onThemeChange }) => {
const { colorScheme, toggleColorScheme } = useWorkspace(); const { colorScheme, updateColorScheme } = useWorkspace();
const handleThemeChange = () => { const handleThemeChange = () => {
toggleColorScheme(); const newTheme = colorScheme === 'dark' ? 'light' : 'dark';
onThemeChange(colorScheme === 'dark' ? 'light' : 'dark'); updateColorScheme(newTheme);
onThemeChange(newTheme);
}; };
return ( return (

View File

@@ -54,9 +54,7 @@ export const WorkspaceProvider = ({ children }) => {
try { try {
await saveWorkspaceSettings(currentWorkspace.id, newSettings); await saveWorkspaceSettings(currentWorkspace.id, newSettings);
setSettings(newSettings); setSettings(newSettings);
if (newSettings.theme) { setColorScheme(newSettings.theme);
setColorScheme(newSettings.theme);
}
} catch (error) { } catch (error) {
console.error('Failed to save settings:', error); console.error('Failed to save settings:', error);
throw error; throw error;
@@ -65,11 +63,13 @@ export const WorkspaceProvider = ({ children }) => {
[currentWorkspace, setColorScheme] [currentWorkspace, setColorScheme]
); );
const toggleColorScheme = useCallback(() => { // Update just the color scheme without saving to backend
const newTheme = colorScheme === 'dark' ? 'light' : 'dark'; const updateColorScheme = useCallback(
setColorScheme(newTheme); (newTheme) => {
updateSettings({ ...settings, theme: newTheme }); setColorScheme(newTheme);
}, [colorScheme, settings, setColorScheme, updateSettings]); },
[setColorScheme]
);
const value = { const value = {
currentWorkspace, currentWorkspace,
@@ -77,7 +77,7 @@ export const WorkspaceProvider = ({ children }) => {
updateSettings, updateSettings,
loading, loading,
colorScheme, colorScheme,
toggleColorScheme, updateColorScheme,
}; };
return ( return (

View File

@@ -81,7 +81,7 @@ export const saveWorkspaceSettings = async (workspaceId, settings) => {
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
}, },
body: JSON.stringify({ settings }), body: JSON.stringify(settings),
} }
); );
return response.json(); return response.json();