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/editor key events #14

Merged
merged 5 commits into from
Nov 12, 2023
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
33 changes: 33 additions & 0 deletions src/main/ipc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,39 @@ ipcMain.on('open-file-dialog', async (event) => {
}
});

ipcMain.handle('save-file', async (event, { fileData, storePath }) => {
try {
const currentDate = new Date();
const year = String(currentDate.getFullYear()).slice(-2);
const month = String(currentDate.getMonth() + 1).padStart(2, '0');
const day = String(currentDate.getDate()).padStart(2, '0');
const hours = String(currentDate.getHours()).padStart(2, '0');
const minutes = String(currentDate.getMinutes()).padStart(2, '0');
const seconds = String(currentDate.getSeconds()).padStart(2, '0');
const extension = 'png'; // Replace with the desired file extension
Copy link
Owner

Choose a reason for hiding this comment

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

is the extension always png in the case of pasting from clipboard?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Thank you for pointing out. Fixed that, checking filename and determine which extension is posted:

const file = item.getAsFile();
const fileName = file.name; // Retrieve the filename
const fileExtension = fileName.split('.').pop(); // Extract the file extension

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@UdaraJay I also updated the way to handle paste using editorProps and handlePaste instead of useEffect.

const fileName = `${year}${month}${day}-${hours}${minutes}${seconds}.${extension}`;
const fullStorePath = path.join(
storePath,
String(currentDate.getFullYear()),
currentDate.toLocaleString('default', { month: 'short' }),
'media'
);
const newFilePath = path.join(fullStorePath, fileName);

// Convert Data URL to Buffer
const dataUrlParts = fileData.split(';base64,');
const fileBuffer = Buffer.from(dataUrlParts[1], 'base64');

await fs.promises.mkdir(fullStorePath, { recursive: true });
await fs.promises.writeFile(newFilePath, fileBuffer);
return newFilePath;

} catch (error) {
console.error('Failed to save the file:', error);
}
});


ipcMain.handle('open-file', async (event, data) => {
let attachments: string[] = [];
const storePath = data.storePath;
Expand Down
24 changes: 20 additions & 4 deletions src/renderer/hooks/usePostHelpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,28 @@ export const getPost = async (postPath) => {
};

export const attachToPostCreator =
(setPost, getCurrentPilePath) => async () => {
(setPost, getCurrentPilePath) => async (imageData) => {
const storePath = getCurrentPilePath();

const newAttachments = await window.electron.ipc.invoke('open-file', {
storePath: storePath,
});
let newAttachments = [];
if (imageData) {
// save image data to a file
const newFilePath = await window.electron.ipc.invoke('save-file', {
fileData: imageData,
storePath: storePath,
});

if (newFilePath) {
newAttachments.push(newFilePath);
} else {
console.error('Failed to save the pasted image.');
}
} else {
newAttachments = await window.electron.ipc.invoke('open-file', {
storePath: storePath,
});
}


// Attachments are stored relative to the base path from the
// base directory of the pile
Expand Down
59 changes: 57 additions & 2 deletions src/renderer/pages/Pile/Editor/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ export default function Editor({
const [isDragging, setIsDragging] = useState(false);
const [isAIResponding, setIsAiResponding] = useState(false);
const [prevDragPos, setPrevDragPos] = useState(0);
const [isActive, setIsActive] = useState(false);
Copy link
Owner

Choose a reason for hiding this comment

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

You can use editor.isFocused instead of managing the active state yourself.


const handleMouseDown = (e) => {
setIsDragging(true);
Expand All @@ -93,7 +94,6 @@ export default function Editor({

const handleSubmit = useCallback(async () => {
await savePost();

if (isNew) {
resetPost();
closeReply();
Expand All @@ -104,6 +104,59 @@ export default function Editor({
setEditable(false);
}, [editor, isNew, post]);

useEffect(() => {
if (!editor || !editable) return;

const handleKeyDown = (event) => {
if (isActive && editable && (event.metaKey || event.ctrlKey) && event.key === 'Enter') {
handleSubmit();
}
};

document.addEventListener('keydown', handleKeyDown);

return () => {
document.removeEventListener('keydown', handleKeyDown);
};
}, [isActive, editable, handleSubmit]);

useEffect(() => {
if (!editor || !editable) return;

const handlePaste = (event) => {
if (isActive && editable) {
const items = (event.clipboardData || event.originalEvent.clipboardData).items;
for (let i = 0; i < items.length; i++) {
const item = items[i];
if (item.type.indexOf('image') === 0) {
const file = item.getAsFile();
// Handle the image file here (e.g., upload, display, etc.)
const reader = new FileReader();
reader.onload = () => {
const imageData = reader.result;
attachToPost(imageData);
};
reader.readAsDataURL(file);
}
}
}
};

document.addEventListener('paste', handlePaste);

return () => {
document.removeEventListener('paste', handlePaste);
};
}, [isActive, editable]);

const handleFocus = () => {
setIsActive(true);
};

const handleBlur = () => {
setIsActive(false);
};

const generateAiResponse = useCallback(async () => {
if (!editor) return;
if (isAIResponding) return;
Expand Down Expand Up @@ -185,9 +238,11 @@ export default function Editor({
if (!post) return;

return (
<div className={`${styles.frame} ${isNew && styles.isNew}`}>
<div className={`${styles.frame} ${isNew && styles.isNew}`}>
{editable ? (
<EditorContent
onFocus={handleFocus}
onBlur={handleBlur}
key={'new'}
className={`${styles.editor} ${isBig() && styles.editorBig} ${
isAIResponding && styles.responding
Expand Down
Loading