- Trang chủ nhà phát triển
- Nhúng trình soạn thảo
- Component cho framework
Component cho framework
Component cho framework
Gói cung cấp một component cho từng framework, dưới dạng subpath export của mroffice-embed: cài một lần, và mỗi framework là một peer dependency tùy chọn, nên bundle của bạn chỉ chứa entry mà bạn import. Mọi component đều mở cùng trình soạn thảo như MROffice.open(), nhận cùng các tùy chọn dưới dạng props và báo cùng các sự kiện.
npm install mroffice-embed| Framework | Lệnh import | Component, handle, sự kiện |
|---|---|---|
React 17+ | mroffice-embed/react | <MROfficeEditor ref={editorRef} … />; ref là handle của trình soạn thảo; các props onReady, onSave, … |
Next.js App Router | mroffice-embed/react | Một client component ("use client" nằm sẵn trong entry): dùng nó từ một server component; máy chủ kết xuất một vùng chứa rỗng |
Vue 3.3+ / Nuxt | mroffice-embed/vue | <MROfficeEditor ref="editor" … />, @ready, @save, …; composable useMROfficeEditor(container, options); an toàn với SSR |
Angular 17+ | mroffice-embed/angular | MROfficeEditorComponent dạng standalone, <mroffice-editor>, [inputs], (ready), (save), …; chạy ngoài zone, phát sự kiện bên trong zone; an toàn với SSR |
Svelte 4/5 / SvelteKit | mroffice-embed/svelte | <MROfficeEditor bind:editor … />, các props onSave={…} (hoặc on:save); action use:mroffice |
Bất kỳ (Web Component) | mroffice-embed/element | <mroffice-editor> với thuộc tính HTML và thuộc tính đối tượng; các sự kiện mroffice-ready, mroffice-save, …; cũng có tại https://mroffice.ai/embed/v1/element.js |
- tokenUrl là cách vào ngắn nhất: một route trên máy chủ của bạn trả về { token, appId?, origin? } dạng JSON (hoặc token dạng văn bản). Component gọi nó với ?reason=start|refresh|reload|mode&mode=… mỗi khi cần token mới. token (một chuỗi, hoặc một hàm như trong open()) cũng dùng được.
- Props thay đổi trình soạn thảo theo cách ít tốn kém nhất mà nó cho phép: các callback và hàm token được đọc khi được gọi; theme và ui.theme được đặt tại chỗ, locale tải lại khung bằng ngôn ngữ đó (vẫn tài liệu đó), mode gọi setMode với token được ký cho chế độ đó; một tệp, ứng dụng, origin, ui (toolbar, features, brand) hoặc downloads khác sẽ mở một trình soạn thảo mới. Chuỗi token mới cho cùng tệp được giữ lại cho lần cần token mới tiếp theo.
- Handle (React ref, Vue template ref, Svelte bind:editor, component Angular, chính phần tử) có requestSave(), setMode(), setTheme(), setLocale(), focus(), openFile(), destroy(), getCapabilities(), word / excel / powerpoint / pdf / document (Automation API), ready và current; nó giữ nguyên qua mỗi lần mở lại.
- Kết xuất phía máy chủ: mọi component chỉ kết xuất vùng chứa của nó trên máy chủ và mở trình soạn thảo trong trình duyệt. StrictMode của React và việc di chuyển phần tử vẫn giữ nguyên phiên (một token bắt đầu một phiên, một lần duy nhất).
- Hãy đặt chiều cao cho component (style, một class, hoặc phần tử cha flex): nó lấp đầy vùng chứa, tối thiểu 320 px.
- Các sự kiện mới của SDK cũng là props tại đó: onRequestUsers (danh bạ của bạn cho lượt nhắc @), onUsersChange và onMention (Vue @users-change / @mention, Angular (usersChange) / (mention), mroffice-users-change / mroffice-mention của phần tử).
"use client"; // chỉ dành cho trang mà bản thân là client component
import { useRef } from "react";
import { MROfficeEditor, type MROfficeEditorHandle } from "mroffice-embed/react";
export function ContractEditor({ contractId }: { contractId: string }) {
const editor = useRef<MROfficeEditorHandle>(null);
return (
<>
<button onClick={() => editor.current?.requestSave()}>Save</button>
<MROfficeEditor
ref={editor}
appId={process.env.NEXT_PUBLIC_MROFFICE_APP_ID}
// được gọi lại để lấy token mới mỗi khi cần
token={({ mode }) => fetch(`/api/contracts/${contractId}/editor-token?mode=${mode ?? "edit"}`).then((r) => r.text())}
locale="en"
ui={{ toolbar: "full", features: { print: false } }}
onReady={(event) => console.log(event.document.name)}
onSave={(saved) => console.log(saved.version, saved.downloadUrl)}
onError={(error) => console.error(error.code, error.hint)}
style={{ height: "80vh" }}
/>
</>
);
}// app/contracts/[id]/page.tsx — một server component: trình soạn thảo là client
// component, được render thành một <div> rỗng trên máy chủ và mở trong trình duyệt.
import { MROfficeEditor } from "mroffice-embed/react";
export default async function Page({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
return <MROfficeEditor tokenUrl={`/api/mroffice/session?contract=${id}`} style={{ height: "100vh" }} />;
}// GET /api/mroffice/session?reason=start|refresh|reload|mode&mode=edit
// (thứ mà tokenUrl gọi; npx mroffice-embed init tạo sẵn)
import { createSessionToken } from "mroffice-embed/server";
export async function GET(request: Request) {
const user = await requireUser(request); // cơ chế đăng nhập của bạn
const mode = new URL(request.url).searchParams.get("mode") === "view" ? "view" : "edit";
const token = await createSessionToken({
appId: process.env.MROFFICE_APP_ID!, secretKey: process.env.MROFFICE_SECRET_KEY!,
file: { key: "contract-42", name: "contract.docx", url: await signedUrlFor("contract-42") },
user: { id: user.id, name: user.name }, mode,
});
return Response.json({ token, appId: process.env.MROFFICE_APP_ID }, { headers: { "cache-control": "no-store" } });
}<script setup lang="ts">
import { ref } from "vue";
import { MROfficeEditor, useMROfficeEditor, type MROfficeEditorHandle } from "mroffice-embed/vue";
const editor = ref<MROfficeEditorHandle | null>(null);
const locale = ref("en"); // thay đổi giá trị này sẽ tải lại trình soạn thảo bằng ngôn ngữ đó, vẫn tài liệu đó
</script>
<template>
<button @click="editor?.requestSave()">Save</button>
<MROfficeEditor ref="editor" token-url="/api/mroffice/session" :locale="locale"
:ui="{ toolbar: 'full' }" @ready="(e) => console.log(e.document.name)" @save="onSaved" @error="onError"
style="height: 80vh" />
</template>
<!-- Or the composable, in a container of your own:
const container = ref<HTMLElement | null>(null);
const { editor, ready, dirty, error } = useMROfficeEditor(container, () => ({ tokenUrl: "/api/mroffice/session" }));
-->import { Component, ViewChild } from "@angular/core";
import { MROfficeEditorComponent } from "mroffice-embed/angular";
import type { ReadyEvent, SavedEvent } from "mroffice-embed";
@Component({
selector: "app-contract",
standalone: true,
imports: [MROfficeEditorComponent],
template: `
<button (click)="editor.requestSave()">Save</button>
<mroffice-editor #editor tokenUrl="/api/mroffice/session" locale="en"
[ui]="{ toolbar: 'full' }" (ready)="onReady($event)" (save)="onSave($event)"
style="height: 80vh" />`,
})
export class ContractComponent {
@ViewChild("editor") editor!: MROfficeEditorComponent;
onReady(event: ReadyEvent) { console.log(event.document.name); }
onSave(saved: SavedEvent) { console.log(saved.version); }
}<script lang="ts">
import { MROfficeEditor, type MROfficeEditorHandle } from "mroffice-embed/svelte";
let editor: MROfficeEditorHandle | undefined = $state(); // Svelte 4: let editor;
</script>
<button onclick={() => editor?.requestSave()}>Save</button>
<MROfficeEditor bind:editor tokenUrl="/api/mroffice/session" locale="en"
onSave={(saved) => console.log(saved.version)} style="height: 80vh" />
<!-- Or the action, on an element of your own: <div use:mroffice={{ tokenUrl: "/api/mroffice/session" }}></div>
(import { mroffice } from "mroffice-embed/svelte") --><!-- có bundler: import "mroffice-embed/element"; không có bundler: -->
<script src="https://mroffice.ai/embed/v1/element.js"></script>
<mroffice-editor token-url="/api/mroffice/session" locale="en" toolbar="full" style="height: 80vh"></mroffice-editor>
<script>
const editor = document.querySelector("mroffice-editor");
editor.ui = { toolbar: "full", features: { print: false } }; // các đối tượng được truyền vào dưới dạng thuộc tính
editor.addEventListener("mroffice-save", (event) => console.log(event.detail.version));
document.querySelector("#save").onclick = () => editor.requestSave();
</script>