Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,8 @@ export function useHandwritingManager({ scrapId }: UseHandwritingManagerProps) {
if (appliedScrapIdRef.current === scrapId) return;
if (!canvasMounted) return;
try {
const decoded = handwritingData?.data
? decodeHandwritingData(handwritingData.data)
const decoded = handwritingData
? decodeHandwritingData(handwritingData)
: { strokes: [] as Stroke[], texts: [] as TextItem[] };
applyData(decoded.strokes, decoded.texts);
} catch (e) {
Expand Down Expand Up @@ -152,10 +152,10 @@ export function useHandwritingManager({ scrapId }: UseHandwritingManagerProps) {
hasCanvas: !!c,
});
if (decision !== 'allow' || !c) return;
const data = encodeHandwritingData(c.getStrokes() ?? [], c.getTexts() ?? []);
const dataJson = encodeHandwritingData(c.getStrokes() ?? [], c.getTexts() ?? []);
needsSaveRef.current = false;
updateMutationRef.current.mutate(
{ scrapId, request: { data } },
{ scrapId, request: { dataJson } },
{
// autosave 는 silent — 토스트 없이 다음 interval 에 재시도
onError: () => {
Expand All @@ -177,12 +177,12 @@ export function useHandwritingManager({ scrapId }: UseHandwritingManagerProps) {
});
if (decision !== 'allow' || !c) return;

const data = encodeHandwritingData(c.getStrokes() ?? [], c.getTexts() ?? []);
const dataJson = encodeHandwritingData(c.getStrokes() ?? [], c.getTexts() ?? []);
needsSaveRef.current = false;

try {
await Promise.race([
updateMutationRef.current.mutateAsync({ scrapId, request: { data } }),
updateMutationRef.current.mutateAsync({ scrapId, request: { dataJson } }),
new Promise<never>((_, reject) =>
setTimeout(() => reject(new Error('flush-timeout')), FLUSH_TIMEOUT_MS)
),
Expand Down
93 changes: 45 additions & 48 deletions apps/native/src/features/student/scrap/utils/handwritingEncoder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,59 +5,56 @@ export interface HandwritingData {
texts: TextItem[];
}

/**
* 필기 데이터를 Base64로 인코딩합니다.
* @param strokes - 그리기 스트로크 배열
* @param texts - 텍스트 아이템 배열
* @returns Base64로 인코딩된 문자열
*/
export function encodeHandwritingData(strokes: Stroke[], texts: TextItem[]): string {
const data: HandwritingData = {
strokes: strokes || [],
texts: texts || [],
type DecodeSource = {
dataJson?: string | null;
data?: string | null;
};

// 캐노니컬 키 순서로 재구성한다 — 동일 입력에 대한 byte-stable JSON 출력 보장.
function canonicalize(strokes: Stroke[], texts: TextItem[]): HandwritingData {
return {
strokes: strokes.map((s) => ({
points: s.points.map((p) => ({ x: p.x, y: p.y })),
color: s.color,
width: s.width,
})),
texts: texts.map((t) => ({
id: t.id,
text: t.text,
x: t.x,
y: t.y,
fontSize: t.fontSize,
color: t.color,
})),
};
const jsonString = JSON.stringify(data);
const base64Data = btoa(unescape(encodeURIComponent(jsonString)));
return base64Data;
}

/**
* Base64로 인코딩된 필기 데이터를 디코딩합니다.
* @param base64Data - Base64로 인코딩된 문자열
* @returns 디코딩된 필기 데이터 (strokes, texts)
* @throws 디코딩 실패 시 에러
*/
export function decodeHandwritingData(base64Data: string): HandwritingData {
try {
const decodedData = decodeURIComponent(escape(atob(base64Data)));
const data = JSON.parse(decodedData);
export function encodeHandwritingData(strokes: Stroke[], texts: TextItem[]): string {
return JSON.stringify(canonicalize(strokes ?? [], texts ?? []));
}

// 이전 형식 호환성: strokes만 있는 경우와 { strokes, texts } 형식 모두 지원
if (Array.isArray(data)) {
// 이전 형식: strokes 배열만
return {
strokes: data,
texts: [],
};
} else {
// 새 형식: { strokes, texts } 객체
return {
strokes: data.strokes || [],
texts: data.texts || [],
};
}
} catch (error) {
console.error('필기 데이터 디코딩 실패:', error);
throw error;
function parseHandwriting(jsonString: string): HandwritingData {
const parsed = JSON.parse(jsonString);
if (Array.isArray(parsed)) {
return { strokes: parsed, texts: [] };
}
return {
strokes: parsed.strokes ?? [],
texts: parsed.texts ?? [],
};
}

export function decodeHandwritingData(source: DecodeSource): HandwritingData {
if (source.dataJson && source.dataJson.length > 0) {
return parseHandwriting(source.dataJson);
}
if (source.data && source.data.length > 0) {
const decoded = decodeURIComponent(escape(atob(source.data)));
return parseHandwriting(decoded);
}
return { strokes: [], texts: [] };
}

/**
* 두 필기 데이터가 동일한지 비교합니다.
* @param data1 - 첫 번째 Base64 인코딩된 데이터
* @param data2 - 두 번째 Base64 인코딩된 데이터
* @returns 동일 여부
*/
export function isSameHandwritingData(data1: string, data2: string): boolean {
return data1 === data2;
export function isSameHandwritingData(a: string, b: string): boolean {
return a === b;
}
Loading