implement phase 5 และ fix bugs

This commit is contained in:
Suphonchai Phoonsawat 2026-08-19 23:06:57 +07:00
parent f4b1c3e14b
commit 1bb850c6b8
40 changed files with 1507 additions and 429 deletions

View file

@ -35,20 +35,48 @@ function getFileAsync(): Promise<Office.File> {
});
}
/** host ส่ง slice มาเป็น ArrayBuffer หรือ view — รับทั้งคู่แล้วคืนเป็น BlobPart ตรงๆ */
/**
* host แต่ละตัวส่งข้อมูล slice มาคนละรูปแบบ (เอกสาร Office.js ระบบแค่ "byte array"):
* - Word บน Windows ส่วนใหญ่ = ArrayBuffer / typed-array view
* - Word บน Mac = base64 string หรือ byte array ธรรมดา (number[])
* ปรับเป็น Uint8Array ให้หมดก่อนประกอบเป็น Blob
*/
export function sliceDataToBytes(data: unknown): Uint8Array<ArrayBuffer> {
if (data instanceof ArrayBuffer) {
return new Uint8Array(data);
}
if (ArrayBuffer.isView(data)) {
const view = data as ArrayBufferView;
return new Uint8Array(view.buffer as ArrayBuffer, view.byteOffset, view.byteLength);
}
if (typeof data === "string") {
// base64 (บาง host ใส่ data-url prefix หรือขึ้นบรรทัดมาด้วย — ตัดทิ้งก่อน decode)
const base64 = data.replace(/^data:[^,]*?;base64,/, "").replace(/\s/g, "");
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
for (let index = 0; index < binary.length; index++) {
bytes[index] = binary.charCodeAt(index);
}
return bytes;
}
if (Array.isArray(data) && (data.length === 0 || typeof data[0] === "number")) {
return Uint8Array.from(data);
}
throw new Error(`รูปแบบข้อมูลของ slice ไม่รองรับ (ได้รับ ${typeof data})`);
}
/** อ่าน slice หนึ่งชิ้นแล้ว normalize เป็น Uint8Array */
function getSliceAsync(file: Office.File, sliceIndex: number): Promise<BlobPart> {
return new Promise((resolve, reject) => {
try {
file.getSliceAsync(sliceIndex, (result) => {
if (result.status === Office.AsyncResultStatus.Succeeded) {
const data: unknown = result.value.data;
if (data instanceof ArrayBuffer) {
resolve(data);
} else if (ArrayBuffer.isView(data)) {
const view = data as ArrayBufferView;
resolve(new Uint8Array(view.buffer as ArrayBuffer, view.byteOffset, view.byteLength));
} else {
reject(new Error("รูปแบบข้อมูลของ slice ไม่รองรับ (ต้องเป็น byte array)"));
try {
resolve(sliceDataToBytes(result.value.data));
} catch (error) {
reject(
error instanceof Error ? error : new Error(`อ่าน slice ที่ ${sliceIndex} ไม่สำเร็จ`)
);
}
} else {
reject(officeError(result, `อ่าน slice ที่ ${sliceIndex} ไม่สำเร็จ`));