@folijs/react 0.6.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/editor.tsx CHANGED
@@ -1,11 +1,15 @@
1
1
  import {
2
+ type Command,
2
3
  createEditor,
3
4
  type Editor,
4
5
  type EditorDocument,
5
6
  type EditorState,
7
+ type Extension,
8
+ type FoliCommands,
6
9
  type Plugin,
7
10
  type ReviewView,
8
11
  } from "@folijs/core";
12
+ import { editorCommand } from "@folijs/core/internal";
9
13
  import {
10
14
  createContext,
11
15
  type ReactNode,
@@ -21,6 +25,7 @@ import {
21
25
  /**
22
26
  * `useLayoutEffect` in the browser, `useEffect` on the server, where neither runs: React 18
23
27
  * warns about a layout effect in server rendering.
28
+ * @internal
24
29
  */
25
30
  export const useIsomorphicLayoutEffect =
26
31
  typeof document === "undefined" ? useEffect : useLayoutEffect;
@@ -32,8 +37,17 @@ export interface UseFoliEditorOptions {
32
37
  * load another document, `editor.setDocument()`.
33
38
  */
34
39
  initialContent?: EditorDocument | undefined;
35
- /** Read once, when the editor is created. */
40
+ /**
41
+ * Read once, when the editor is created. A different list later (other plugins, not a new
42
+ * array of the same ones) is ignored, with a warning unless `process.env.NODE_ENV` is
43
+ * `"production"` at run time: give the component a new `key` to make a new editor with it.
44
+ */
36
45
  plugins?: readonly Plugin[] | undefined;
46
+ /**
47
+ * Read once: custom nodes and marks, their plugins and view hooks (`ViewExtension` from
48
+ * `@folijs/view`), as `createEditor`'s `extensions`. Changed later: as `plugins`.
49
+ */
50
+ extensions?: readonly Extension[] | undefined;
37
51
  /** Read once: who edits (tracked changes are made in this name; `createEditor`'s `author`). */
38
52
  author?: string | undefined;
39
53
  /** Read once: record edits as tracked changes from the start (a `.docx`'s `trackRevisions`). */
@@ -49,18 +63,56 @@ export interface UseFoliEditorOptions {
49
63
  */
50
64
  export function useFoliEditor(options: UseFoliEditorOptions = {}): Editor {
51
65
  const [editor] = useState(() => {
52
- const { initialContent: document, plugins, author, trackChanges, reviewView } = options;
66
+ const {
67
+ initialContent: document,
68
+ plugins,
69
+ extensions,
70
+ author,
71
+ trackChanges,
72
+ reviewView,
73
+ } = options;
53
74
  return createEditor({
54
75
  ...(document && { document }),
55
76
  ...(plugins && { plugins }),
77
+ ...(extensions && { extensions }),
56
78
  ...(author !== undefined && { author }),
57
79
  ...(trackChanges !== undefined && { trackChanges }),
58
80
  ...(reviewView !== undefined && { reviewView }),
59
81
  });
60
82
  });
83
+ // ADR-0008: the editor takes its plugins and extensions once; say so when an app changes them.
84
+ const first = useRef(options);
85
+ const warned = useRef(false);
86
+ useEffect(() => {
87
+ if (warned.current || !development()) return;
88
+ const changed = (["plugins", "extensions"] as const).find(
89
+ (name) => !sameItems(first.current[name], options[name]),
90
+ );
91
+ if (!changed) return;
92
+ warned.current = true;
93
+ console.warn(
94
+ `Foli: \`${changed}\` changed after the editor was created and is ignored. Give the component a new \`key\` to create an editor with the new list.`,
95
+ );
96
+ });
61
97
  return editor;
62
98
  }
63
99
 
100
+ /**
101
+ * Dev-only checks run unless `process.env.NODE_ENV` is "production" at run time: read through
102
+ * `globalThis`, so a bundle that defines no `process` runs them too.
103
+ * @internal
104
+ */
105
+ export const development = () =>
106
+ (globalThis as { process?: { env?: { NODE_ENV?: string } } }).process?.env?.NODE_ENV !==
107
+ "production";
108
+
109
+ /**
110
+ * The same elements (an inline array of the same plugins is not a change).
111
+ * @internal
112
+ */
113
+ export const sameItems = (a: readonly unknown[] = [], b: readonly unknown[] = []) =>
114
+ a.length === b.length && a.every((item, i) => item === b[i]);
115
+
64
116
  const EditorContext = createContext<Editor | null>(null);
65
117
 
66
118
  /** Makes `editor` the one `useCurrentEditor`, `useEditorState` and `FoliCanvas` use below it. */
@@ -81,7 +133,10 @@ export function useCurrentEditor(): Editor {
81
133
  return editor;
82
134
  }
83
135
 
84
- /** `editor` if given, else the context's. */
136
+ /**
137
+ * `editor` if given, else the context's.
138
+ * @internal
139
+ */
85
140
  export function useEditorOrContext(editor: Editor | undefined, caller: string): Editor {
86
141
  const context = useContext(EditorContext);
87
142
  const found = editor ?? context;
@@ -89,7 +144,10 @@ export function useEditorOrContext(editor: Editor | undefined, caller: string):
89
144
  return found;
90
145
  }
91
146
 
92
- /** The editor commands go to: the story open on its page, if any, else `editor`. */
147
+ /**
148
+ * The editor commands go to: the story open on its page, if any, else `editor`.
149
+ * @internal
150
+ */
93
151
  export function useActiveEditor(editor: Editor): Editor {
94
152
  const subscribe = useCallback((notify: () => void) => editor.subscribe(notify), [editor]);
95
153
  const id = useSyncExternalStore(
@@ -132,3 +190,68 @@ export function useEditorState<T>(
132
190
  };
133
191
  return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
134
192
  }
193
+
194
+ /** What `useCommand` gives: whether the command applies now, and a way to run it. */
195
+ export interface CommandState {
196
+ /** A dry run (`editor.can`), again after every transaction. */
197
+ readonly enabled: boolean;
198
+ /** Runs the command on the editor; whether it applied. */
199
+ run(): boolean;
200
+ }
201
+
202
+ export interface UseCommandOptions {
203
+ /** Default: the context's editor. */
204
+ editor?: Editor | undefined;
205
+ }
206
+
207
+ /**
208
+ * A command's state for a button of the app's own: `enabled` re-renders the component when a dry
209
+ * run's answer changes, `run` runs it, e.g. `useCommand(toggleMark("bold"))`. Both act on the
210
+ * editor of the header, footer or note open on its page, else on `editor` (default: the
211
+ * context's), as the toolbar's items do. The dry run runs after every transaction (and on a
212
+ * render with another command: keep the command's identity, e.g. made outside the component).
213
+ */
214
+ export function useCommand(command: Command, options?: UseCommandOptions): CommandState;
215
+ /**
216
+ * A named command of `editor.commands` (built-in, or a plugin's `PluginSpec.commands`), typed by
217
+ * `FoliCommands`, on the context's editor (or the story open on its page):
218
+ * `useCommand("toggleMark", "bold")`, `useCommand("insertMention", "u-1", "Ada")`. Throws when
219
+ * the editor has no command of that name.
220
+ */
221
+ export function useCommand<K extends keyof FoliCommands>(
222
+ name: K,
223
+ ...args: Parameters<FoliCommands[K]>
224
+ ): CommandState;
225
+ export function useCommand(target: Command | string, ...rest: unknown[]): CommandState {
226
+ const named = typeof target === "string";
227
+ const editor = useActiveEditor(
228
+ useEditorOrContext(
229
+ named ? undefined : (rest[0] as UseCommandOptions | undefined)?.editor,
230
+ "useCommand",
231
+ ),
232
+ );
233
+ const args = named ? rest : [];
234
+ // One command and selector per editor, target and arguments: useEditorState keeps its answer.
235
+ const memo = useRef<{
236
+ editor: Editor;
237
+ target: Command | string;
238
+ args: readonly unknown[];
239
+ command: Command;
240
+ selector: (state: EditorState, editor: Editor) => boolean;
241
+ } | null>(null);
242
+ let current = memo.current;
243
+ if (
244
+ !current ||
245
+ current.editor !== editor ||
246
+ current.target !== target ||
247
+ !sameItems(current.args, args)
248
+ ) {
249
+ const command = typeof target === "string" ? editorCommand(editor, target, args) : target;
250
+ if (!command) throw new RangeError(`useCommand: the editor has no command named "${target}"`);
251
+ current = { editor, target, args, command, selector: (_state, e) => e.can(command) };
252
+ memo.current = current;
253
+ }
254
+ const { command, selector } = current;
255
+ const enabled = useEditorState(selector, { editor });
256
+ return { enabled, run: () => editor.run(command) };
257
+ }
package/src/index.ts CHANGED
@@ -1,7 +1,10 @@
1
1
  export {
2
+ type CommandState,
2
3
  FoliEditorProvider,
4
+ type UseCommandOptions,
3
5
  type UseEditorStateOptions,
4
6
  type UseFoliEditorOptions,
7
+ useCommand,
5
8
  useCurrentEditor,
6
9
  useEditorState,
7
10
  useFoliEditor,
@@ -15,4 +18,14 @@ export {
15
18
  type FoliEditorProps,
16
19
  } from "./FoliEditor.js";
17
20
  export { FoliNavigation, type FoliNavigationProps } from "./FoliNavigation.js";
18
- export { FoliToolbar, type FoliToolbarProps } from "./FoliToolbar.js";
21
+ export {
22
+ defaultToolbarItems,
23
+ FoliToolbar,
24
+ type FoliToolbarProps,
25
+ type ToolbarAction,
26
+ type ToolbarButton,
27
+ type ToolbarItem,
28
+ type ToolbarItemName,
29
+ type ToolbarMenu,
30
+ toolbarItems,
31
+ } from "./FoliToolbar.js";