Skip to content

Commit

Permalink
Refactor editorToCode.ts and remove
Browse files Browse the repository at this point in the history
selectionToUrl.ts
  • Loading branch information
gramliu committed Nov 27, 2023
1 parent 31abd75 commit 2f3fe09
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 33 deletions.
39 changes: 34 additions & 5 deletions apps/web/src/lib/editorToCode.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { Editor } from "@tldraw/tldraw";
import { Editor, getSvgAsImage } from "@tldraw/tldraw";
import fetchCanvasToPageResponse from "./fetchCanvasToPageResponse";
import { getSelectionAsImageDataUrl } from "./selectionToUrl";

/**
* Convert the editor selection to code
Expand All @@ -11,16 +10,16 @@ export async function convertEditorToCode(editor: Editor): Promise<string> {
throw new Error("Page is empty. Draw something first");
}

const imageUrl = await getSelectionAsImageDataUrl(editor);
const selectionText = getSelectionAsText(editor);
const imageUrl = await getCurrentPageImageDataUrl(editor);
const selectionText = getCurrentPageAsText(editor);

return fetchCanvasToPageResponse(imageUrl, selectionText);
}

/**
* Serialize the contents of the current selection
*/
function getSelectionAsText(editor: Editor) {
function getCurrentPageAsText(editor: Editor) {
const shapeIds = editor.getCurrentPageShapeIds();
const shapeDescendantIds =
editor.getShapeAndDescendantIds([...shapeIds]);
Expand All @@ -44,3 +43,33 @@ function getSelectionAsText(editor: Editor) {

return texts.join("\n");
}

/**
* Convert a binary blob to base64
*/
function blobToBase64(blob: Blob): Promise<string> {
return new Promise((resolve, _) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result as string);
reader.readAsDataURL(blob);
});
}

/**
* Get the current selection as a base64 encoded image data url
*/
export async function getCurrentPageImageDataUrl(editor: Editor) {
const svg = await editor.getSvg([...editor.getCurrentPageShapeIds()]);
if (!svg) throw new Error("Could not get SVG");

const IS_SAFARI = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);

const blob = await getSvgAsImage(svg, IS_SAFARI, {
type: "png",
quality: 1,
scale: 1,
});

if (!blob) throw new Error("Could not get blob");
return await blobToBase64(blob);
}
28 changes: 0 additions & 28 deletions apps/web/src/lib/selectionToUrl.ts

This file was deleted.

0 comments on commit 2f3fe09

Please sign in to comment.