Skip to content

refactor: allow undo redo action with font #1751

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Apr 13, 2025
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 29 additions & 20 deletions apps/studio/electron/main/assets/fonts/font.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import generate from '@babel/generator';
import { formatContent, readFile, writeFile } from '../../code/files';
import fs from 'fs';
import { extractFontParts, getFontFileName } from '@onlook/utility';
import type { CodeDiff } from '@onlook/models';

/**
* Adds a new font to the project by:
Expand Down Expand Up @@ -129,9 +130,12 @@ export async function addFont(projectRoot: string, font: Font) {
// Generate the new code from the AST
const { code } = generate(ast);

// Write the updated content back to the file
const formattedCode = await formatContent(fontPath, code);
await writeFile(fontPath, formattedCode);
const codeDiff: CodeDiff = {
original: content,
generated: code,
path: fontPath,
};
return codeDiff;
} catch (error) {
console.error('Error adding font:', error);
}
Expand Down Expand Up @@ -278,25 +282,30 @@ export async function removeFont(projectRoot: string, font: Font) {
/import\s+localFont\s+from\s+['"]next\/font\/local['"];\n?/g;
code = code.replace(localFontImportRegex, '');
}
const formattedCode = await formatContent(fontPath, code);
await writeFile(fontPath, formattedCode);
const codeDiff: CodeDiff = {
original: content,
generated: code,
path: fontPath,
};

// Delete font files if found
if (fontFilesToDelete.length > 0) {
for (const fileRelativePath of fontFilesToDelete) {
const absoluteFilePath = pathModule.join(projectRoot, fileRelativePath);
if (fs.existsSync(absoluteFilePath)) {
try {
fs.unlinkSync(absoluteFilePath);
console.log(`Deleted font file: ${absoluteFilePath}`);
} catch (error) {
console.error(`Error deleting font file ${absoluteFilePath}:`, error);
}
} else {
console.log(`Font file not found: ${absoluteFilePath}`);
}
}
}
// if (fontFilesToDelete.length > 0) {
// for (const fileRelativePath of fontFilesToDelete) {
// const absoluteFilePath = pathModule.join(projectRoot, fileRelativePath);
// if (fs.existsSync(absoluteFilePath)) {
// try {
// fs.unlinkSync(absoluteFilePath);
// console.log(`Deleted font file: ${absoluteFilePath}`);
// } catch (error) {
// console.error(`Error deleting font file ${absoluteFilePath}:`, error);
// }
// } else {
// console.log(`Font file not found: ${absoluteFilePath}`);
// }
// }
// }
// Commented out for now—since we have undo/redo functionality for adding/removing fonts, we shouldn’t delete these files to ensure proper rollback support.
return codeDiff;
} else {
console.log(`Font ${fontIdToRemove} not found in font.ts`);
}
Expand Down
13 changes: 11 additions & 2 deletions apps/studio/electron/main/assets/fonts/watcher.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { subscribe, type AsyncSubscription } from '@parcel/watcher';
import { DefaultSettings } from '@onlook/models/constants';
import { DefaultSettings, MainChannels } from '@onlook/models/constants';
import * as pathModule from 'path';
import { scanFonts } from './scanner';
import fs from 'fs';
Expand All @@ -8,6 +8,7 @@ import { removeFontVariableFromLayout } from './layout';
import { removeFontFromTailwindConfig, updateTailwindFontConfig } from './tailwind';
import type { Font } from '@onlook/models/assets';
import { detectRouterType } from '../../pages';
import { mainWindow } from '../../index';

export class FontFileWatcher {
private subscription: AsyncSubscription | null = null;
Expand Down Expand Up @@ -78,7 +79,7 @@ export class FontFileWatcher {
);

const addedFonts = currentFonts.filter(
(currFont) => !this.previousFonts.some((prevFont) => prevFont.id === currFont.id),
(currFont) => !this.previousFonts.some((prevFont) => currFont.id === prevFont.id),
);

for (const font of removedFonts) {
Expand Down Expand Up @@ -108,6 +109,14 @@ export class FontFileWatcher {
}
}

if (removedFonts.length > 0 || addedFonts.length > 0) {
mainWindow?.webContents.send(MainChannels.FONTS_CHANGED, {
currentFonts,
removedFonts,
addedFonts,
});
}

this.previousFonts = currentFonts;
} catch (error) {
console.error('Error syncing fonts:', error);
Expand Down
52 changes: 41 additions & 11 deletions apps/studio/src/lib/editor/engine/font/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { makeAutoObservable, reaction } from 'mobx';
import type { EditorEngine } from '..';
import { invokeMainChannel } from '@/lib/utils';
import { fontFamilies, MainChannels } from '@onlook/models';
import { fontFamilies, MainChannels, type CodeDiff, type WriteCodeAction } from '@onlook/models';
import type { ProjectsManager } from '@/lib/projects';
import type { Font } from '@onlook/models/assets';
import type { FontFile } from '@/routes/editor/LayersPanel/BrandTab/FontPanel/FontFiles';
Expand Down Expand Up @@ -38,6 +38,15 @@ export class FontManager {
makeAutoObservable(this);
this.loadInitialFonts();

const fontChangeHandler = (data: {
currentFonts: Font[];
removedFonts: Font[];
addedFonts: Font[];
}) => {
this._fonts = data.currentFonts;
};
window.api.on(MainChannels.FONTS_CHANGED, fontChangeHandler);

// Watch for project changes and set up watcher when a project is selected
const disposer = reaction(
() => this.projectsManager.project?.folderPath,
Expand All @@ -51,6 +60,9 @@ export class FontManager {
);

this.disposers.push(disposer);
this.disposers.push(() =>
window.api.removeListener(MainChannels.FONTS_CHANGED, fontChangeHandler),
);
}

private convertFont(font: RawFont): Font {
Expand Down Expand Up @@ -133,12 +145,17 @@ export class FontManager {
}

try {
await invokeMainChannel(MainChannels.ADD_FONT, {
const result = (await invokeMainChannel(MainChannels.ADD_FONT, {
projectRoot,
font,
});
})) as CodeDiff;

await this.scanFonts();
const writeCodeAction: WriteCodeAction = {
type: 'write-code',
diffs: [result],
};

this.editorEngine.history.push(writeCodeAction);
} catch (error) {
console.error('Error adding font:', error);
}
Expand All @@ -152,16 +169,21 @@ export class FontManager {
}

try {
await invokeMainChannel(MainChannels.REMOVE_FONT, {
const result = (await invokeMainChannel(MainChannels.REMOVE_FONT, {
projectRoot,
font,
});
})) as CodeDiff;

const writeCodeAction: WriteCodeAction = {
type: 'write-code',
diffs: [result],
};

this.editorEngine.history.push(writeCodeAction);

if (font.id === this.defaultFont) {
this._defaultFont = null;
}

await this.scanFonts();
} catch (error) {
console.error('Error removing font:', error);
}
Expand All @@ -175,12 +197,20 @@ export class FontManager {
}

try {
await invokeMainChannel(MainChannels.SET_FONT, {
const result = (await invokeMainChannel(MainChannels.SET_FONT, {
projectRoot,
font,
});
})) as CodeDiff;

if (result) {
const writeCodeAction: WriteCodeAction = {
type: 'write-code',
diffs: [result],
};
this.editorEngine.history.push(writeCodeAction);
}

await this.getDefaultFont();
setTimeout(() => this.getDefaultFont(), 300);
} catch (error) {
console.error('Error setting font:', error);
}
Expand Down
3 changes: 3 additions & 0 deletions packages/models/src/constants/ipc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,9 @@ export enum MainChannels {

// Trainloop
SAVE_APPLY_RESULT = 'save-apply-result',

// New channel
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Need to clean up comments. Also fonts group exists already.

FONTS_CHANGED = 'fonts-changed',
}

export enum GitChannels {
Expand Down