Skip to content
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

Feature/#119 save file #252

Merged
merged 10 commits into from
Aug 22, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
7 changes: 7 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
"@types/react": "^18.3.3",
"@types/react-dom": "^18.3.0",
"@types/uuid": "^10.0.0",
"@types/wicg-file-system-access": "^2023.10.5",
"@typescript-eslint/eslint-plugin": "^7.13.1",
"@typescript-eslint/parser": "^7.13.1",
"@vitejs/plugin-react": "^4.3.1",
Expand Down
1 change: 1 addition & 0 deletions src/common/export/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./save-file-modern"
34 changes: 34 additions & 0 deletions src/common/export/save-file-modern.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
interface FileInfo {
filename: string;
extension: string;
description: string;
}
export const saveFileModern = async (
fileInfo: FileInfo,
content: string
): Promise<string> => {
let savedFilename = '';
const { filename, extension, description } = fileInfo;
try {
const newFileHandle = await window.showSaveFilePicker({
suggestedName: filename,
types: [
{
description,
accept: {
'text/plain': [`.${extension}`],
},
},
],
});
savedFilename = newFileHandle.name;
const writableStream = await newFileHandle.createWritable();
await writableStream.write(content);
await writableStream.close();
} catch (error) {
// Nothing to do here if user aborts filename
// TODO: add later on more elaborated error handling
// throw new Error('Error save file: ' + error);
}
return savedFilename;
};
1 change: 1 addition & 0 deletions src/core/local-disk/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './use-local-disk.hook';
12 changes: 12 additions & 0 deletions src/core/local-disk/local-disk.model.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { ShapeModel } from '../model';

export interface Page {
id: string;
name: string;
shapes: ShapeModel[];
}

export interface QuickMockFileContract {
version: string;
pages: Page[];
}
21 changes: 21 additions & 0 deletions src/core/local-disk/shapes-to-document.mapper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { ShapeModel } from '../model';
import { QuickMockFileContract, Page } from './local-disk.model';

export const mapFromShapesArrayToQuickMockFileDocument = (
shapes: ShapeModel[]
): QuickMockFileContract => {
const pages: Page[] = shapes.reduce((acc, shape) => {
const newPage: Page = {
id: '1',
name: 'default',
shapes: [{ ...shape }],
};

return [...acc, newPage];
}, [] as Page[]);

return {
version: '0.1',
pages,
};
};
131 changes: 131 additions & 0 deletions src/core/local-disk/shapes-to.document.mapper.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
import { mapFromShapesArrayToQuickMockFileDocument } from './shapes-to-document.mapper';
import { ShapeModel } from '../model';
import { QuickMockFileContract } from './local-disk.model';

describe('shapes to document mapper', () => {
describe('mapFromShapesArrayToQuickMockFileDocument', () => {
it('Should return a ShapeModel with empty pages', () => {
// Arrange
const shapes: ShapeModel[] = [];
const expectedResult: QuickMockFileContract = {
version: '0.1',
pages: [],
};
// Act
const result = mapFromShapesArrayToQuickMockFileDocument(shapes);

// Assert
expect(result).toEqual(expectedResult);
});

it('Should return a ShapeModel with one pages and shapes', () => {
// Arrange
const shapes: ShapeModel[] = [
{
id: '1',
x: 0,
y: 0,
width: 100,
height: 100,
type: 'rectangle',
allowsInlineEdition: false,
typeOfTransformer: ['rotate'],
},
];
const expectedResult: QuickMockFileContract = {
version: '0.1',
pages: [
{
id: '1',
name: 'default',
shapes: [
{
id: '1',
x: 0,
y: 0,
width: 100,
height: 100,
type: 'rectangle',
allowsInlineEdition: false,
typeOfTransformer: ['rotate'],
},
],
},
],
};
// Act
const result = mapFromShapesArrayToQuickMockFileDocument(shapes);

// Assert
expect(result).toEqual(expectedResult);
});

it('Should return a ShapeModel with two pages and shapes', () => {
// Arrange
const shapes: ShapeModel[] = [
{
id: '1',
x: 0,
y: 0,
width: 100,
height: 100,
type: 'rectangle',
allowsInlineEdition: false,
typeOfTransformer: ['rotate'],
},
{
id: '2',
x: 0,
y: 0,
width: 100,
height: 100,
type: 'circle',
allowsInlineEdition: true,
typeOfTransformer: ['rotate'],
},
];
const expectedResult: QuickMockFileContract = {
version: '0.1',
pages: [
{
id: '1',
name: 'default',
shapes: [
{
id: '1',
x: 0,
y: 0,
width: 100,
height: 100,
type: 'rectangle',
allowsInlineEdition: false,
typeOfTransformer: ['rotate'],
},
],
},
{
id: '1',
name: 'default',
shapes: [
{
id: '2',
x: 0,
y: 0,
width: 100,
height: 100,
type: 'circle',
allowsInlineEdition: true,
typeOfTransformer: ['rotate'],
},
],
},
],
};
// Act
const result = mapFromShapesArrayToQuickMockFileDocument(shapes);

// Assert
expect(result).toEqual(expectedResult);
});
});
});
52 changes: 52 additions & 0 deletions src/core/local-disk/use-local-disk.hook.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { saveFileModern } from '@/common/export';
import { useCanvasContext } from '../providers';
import { mapFromShapesArrayToQuickMockFileDocument } from './shapes-to-document.mapper';

const DEFAULT_FILE_NAME = 'mymockui';
const DEFAULT_FILE_EXTENSION = 'qm';
const DEFAULT_EXTENSION_DESCRIPTION = 'quick mock';

export const useLocalDisk = () => {
const { shapes } = useCanvasContext();

const serializeShapes = (): string => {
const quickMockDocument = mapFromShapesArrayToQuickMockFileDocument(shapes);
return JSON.stringify(quickMockDocument);
};

const OldBrowsersDownloadFile = (filename: string, content: string) => {
const blob = new Blob([content], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${filename}.qm`;
a.click();
URL.revokeObjectURL(url);
};

const newBrowsersDownloadFile = async (filename: string, content: string) => {
const savedFilename = await saveFileModern(
{
filename,
extension: DEFAULT_FILE_EXTENSION,
description: DEFAULT_EXTENSION_DESCRIPTION,
},
content
);
console.log('saveFilename', savedFilename);
};

const handleSave = () => {
const filename = DEFAULT_FILE_NAME;
const content = serializeShapes();
if (window.showDirectoryPicker === undefined) {
OldBrowsersDownloadFile(filename, content);
} else {
newBrowsersDownloadFile(filename, content);
}
};

return {
handleSave,
};
};
9 changes: 4 additions & 5 deletions src/pods/toolbar/components/save-button/save-button.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
import { SaveIcon } from '@/common/components/icons/save-icon.component';
import classes from '@/pods/toolbar/toolbar.pod.module.css';
import { ToolbarButton } from '../toolbar-button';
import { useLocalDisk } from '@/core/local-disk';

export const SaveButton = () => {
const handleClick = () => {
console.log('Save');
};
export const SaveButton: React.FC = () => {
const { handleSave } = useLocalDisk();

return (
<ToolbarButton
onClick={handleClick}
onClick={handleSave}
className={classes.button}
icon={<SaveIcon />}
label="Save"
Expand Down
Loading