返回 presentation-ai
font-family-toolbar-button.tsx
根目录 / src / components / plate / ui / font-family-toolbar-button.tsx
1 "use client";
2
3 import { FontFamilyPlugin } from "@platejs/basic-styles/react";
4 import dynamic from "next/dynamic";
5 import { KEYS } from "platejs";
6 import { useEditorRef, useEditorSelector } from "platejs/react";
7
8 import { Skeleton } from "@/components/ui/skeleton";
9
10 // Dynamically import FontPicker with a skeleton loader
11 const FontPicker = dynamic(
12 () => import("@/components/ui/font-picker").then((mod) => mod.FontPicker),
13 {
14 loading: () => <Skeleton className="h-8 w-full" />,
15 ssr: false,
16 },
17 );
18
19 // Define a default font to fall back to if no mark is present.
20 const DEFAULT_FONT_FAMILY = "Open Sans";
21
22 export function FontFamilyToolbarButton() {
23 const editor = useEditorRef();
24
25 // 1. Get the current font family from the editor's marks.
26 // Provides a default value to ensure it's never undefined.
27 const fontFamily = useEditorSelector(
28 (editor) =>
29 (editor.api.marks()?.[KEYS.fontFamily] as string) ?? DEFAULT_FONT_FAMILY,
30 [],
31 );
32
33 // 2. Define the function to handle font changes from the picker.
34 const handleFontChange = (font: string) => {
35 if (!editor || !font) return;
36
37 // Ensure there is a selection to apply the mark to.
38 if (!editor.selection) {
39 editor.tf.select({
40 anchor: { path: [0, 0], offset: 0 },
41 focus: { path: [0, 0], offset: 0 },
42 });
43 }
44
45 // Focus the editor and add the font family mark.
46 editor.tf.focus();
47 editor.tf.addMark(FontFamilyPlugin.key, font);
48 };
49
50 return (
51 <div className="min-w-37.5">
52 <FontPicker
53 value={handleFontChange}
54 defaultValue={fontFamily}
55 autoLoad={true}
56 selectClassName="border-0 h-9! py-0 bg-transparent shadow-none hover:bg-accent hover:text-accent-foreground"
57 />
58 </div>
59 );
60 }
61
61 lines Plain Text