@pixerate/editor-react 0.183.1 → 0.184.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.
@@ -1,67 +1,17 @@
1
1
  import React from "react";
2
- import { Template, ColorGradient, type FileImportOptions } from "@pixerate/editor";
2
+ import { type PromptEditorConfig } from "@pixerate/editor";
3
3
  import { type LoadingIndicatorProps } from "../loading-node/index.cjs";
4
- export interface UsePromptEditorProps {
5
- /**
6
- * The editor content as plain text. Changes from the parent (e.g. clearing
7
- * after submit) are applied to the editor; echoes of the editor's own
8
- * updates via `onContentChange` are ignored.
9
- */
10
- content: string;
11
- /** Callback fired when the editor content changes (returns plain text) */
12
- onContentChange: (text: string) => void;
13
- /** List of available templates to be suggested and highlighted */
14
- templates?: Template[];
15
- /** Custom gradient color map for templates */
16
- templateColorMap?: Map<string, ColorGradient>;
17
- /** Whether the editor is editable */
18
- isEditing?: boolean;
19
- /** Placeholder text for the editor */
20
- placeholder?: string;
21
- /** Additional CSS classes for the editor container */
22
- className?: string;
23
- /** Callback fired when the Escape key is pressed */
24
- onEscape?: () => void;
25
- /** Custom keydown handler. Return true to prevent default behavior */
26
- onKeyDown?: (event: KeyboardEvent) => boolean;
27
- /** Callback fired when text selection changes */
28
- onSelectionChange?: (selection: {
29
- from: number;
30
- to: number;
31
- } | null) => void;
32
- /** Callback fired when a slash command (e.g., /template) matches */
33
- onSlashCommandMatch?: (match: RegExpMatchArray, from: number, to: number, coords: {
34
- top: number;
35
- left: number;
36
- }) => void;
37
- /** Callback to dismiss/clear the active slash command */
38
- clearSlashCommand?: () => void;
39
- /** Whether a slash command menu is currently active */
40
- slashCommandActive?: boolean;
41
- /**
42
- * Callback fired the first time each milestone is reached while the editor
43
- * is mounted: `used_variable` ({variable}) and `used_magic` (__instruction__).
44
- */
45
- onMilestone?: (milestone: string) => void;
46
- /** DOM element ID of the container, used for positioning popovers */
47
- containerId?: string;
48
- /** Variable names originating from structured JSON output steps */
49
- jsonVariables?: string[];
50
- /** Animation speed for gradient decorations */
51
- speed?: number;
52
- /**
53
- * Import text from .md, .html, .txt and .rtf files dropped onto the editor
54
- * (opt-in). Content is always inserted as plain text. Pasting keeps the
55
- * plain-text paste handler, so pasted files are not imported.
56
- */
57
- fileImport?: Omit<FileImportOptions, "asPlainText"> | boolean;
4
+ export interface UsePromptEditorProps extends PromptEditorConfig {
58
5
  /**
59
6
  * Component drawn inside each `loadingNode` placeholder instead of the default SVG spinner,
60
7
  * e.g. your design system's loader. It receives `state` (`id`, `label`). Read when a
61
8
  * placeholder renders, so changing it does not recreate the editor.
62
9
  */
63
10
  loadingIndicator?: React.ComponentType<LoadingIndicatorProps>;
64
- /** Accessible label of loading placeholders, announced by screen readers (default `"Loading…"`). */
65
- loadingLabel?: string;
66
11
  }
67
- export declare function usePromptEditor({ content, onContentChange, templates, templateColorMap: userColorMap, isEditing, placeholder, className, onEscape, onKeyDown, onSelectionChange, onSlashCommandMatch, clearSlashCommand, slashCommandActive, onMilestone, containerId, jsonVariables, speed, fileImport, loadingIndicator, loadingLabel, }: UsePromptEditorProps): import("@tiptap/core").Editor | null;
12
+ /**
13
+ * The plain-text prompt editor (`createPromptEditorOptions` from `@pixerate/editor`) as a React
14
+ * hook. Only options baked into extensions recreate the editor; editable state, placeholder,
15
+ * class names and content are applied to the live instance (`syncPromptEditor`).
16
+ */
17
+ export declare function usePromptEditor(props: UsePromptEditorProps): import("@tiptap/core").Editor | null;
@@ -1,67 +1,17 @@
1
1
  import React from "react";
2
- import { Template, ColorGradient, type FileImportOptions } from "@pixerate/editor";
2
+ import { type PromptEditorConfig } from "@pixerate/editor";
3
3
  import { type LoadingIndicatorProps } from "../loading-node/index.js";
4
- export interface UsePromptEditorProps {
5
- /**
6
- * The editor content as plain text. Changes from the parent (e.g. clearing
7
- * after submit) are applied to the editor; echoes of the editor's own
8
- * updates via `onContentChange` are ignored.
9
- */
10
- content: string;
11
- /** Callback fired when the editor content changes (returns plain text) */
12
- onContentChange: (text: string) => void;
13
- /** List of available templates to be suggested and highlighted */
14
- templates?: Template[];
15
- /** Custom gradient color map for templates */
16
- templateColorMap?: Map<string, ColorGradient>;
17
- /** Whether the editor is editable */
18
- isEditing?: boolean;
19
- /** Placeholder text for the editor */
20
- placeholder?: string;
21
- /** Additional CSS classes for the editor container */
22
- className?: string;
23
- /** Callback fired when the Escape key is pressed */
24
- onEscape?: () => void;
25
- /** Custom keydown handler. Return true to prevent default behavior */
26
- onKeyDown?: (event: KeyboardEvent) => boolean;
27
- /** Callback fired when text selection changes */
28
- onSelectionChange?: (selection: {
29
- from: number;
30
- to: number;
31
- } | null) => void;
32
- /** Callback fired when a slash command (e.g., /template) matches */
33
- onSlashCommandMatch?: (match: RegExpMatchArray, from: number, to: number, coords: {
34
- top: number;
35
- left: number;
36
- }) => void;
37
- /** Callback to dismiss/clear the active slash command */
38
- clearSlashCommand?: () => void;
39
- /** Whether a slash command menu is currently active */
40
- slashCommandActive?: boolean;
41
- /**
42
- * Callback fired the first time each milestone is reached while the editor
43
- * is mounted: `used_variable` ({variable}) and `used_magic` (__instruction__).
44
- */
45
- onMilestone?: (milestone: string) => void;
46
- /** DOM element ID of the container, used for positioning popovers */
47
- containerId?: string;
48
- /** Variable names originating from structured JSON output steps */
49
- jsonVariables?: string[];
50
- /** Animation speed for gradient decorations */
51
- speed?: number;
52
- /**
53
- * Import text from .md, .html, .txt and .rtf files dropped onto the editor
54
- * (opt-in). Content is always inserted as plain text. Pasting keeps the
55
- * plain-text paste handler, so pasted files are not imported.
56
- */
57
- fileImport?: Omit<FileImportOptions, "asPlainText"> | boolean;
4
+ export interface UsePromptEditorProps extends PromptEditorConfig {
58
5
  /**
59
6
  * Component drawn inside each `loadingNode` placeholder instead of the default SVG spinner,
60
7
  * e.g. your design system's loader. It receives `state` (`id`, `label`). Read when a
61
8
  * placeholder renders, so changing it does not recreate the editor.
62
9
  */
63
10
  loadingIndicator?: React.ComponentType<LoadingIndicatorProps>;
64
- /** Accessible label of loading placeholders, announced by screen readers (default `"Loading…"`). */
65
- loadingLabel?: string;
66
11
  }
67
- export declare function usePromptEditor({ content, onContentChange, templates, templateColorMap: userColorMap, isEditing, placeholder, className, onEscape, onKeyDown, onSelectionChange, onSlashCommandMatch, clearSlashCommand, slashCommandActive, onMilestone, containerId, jsonVariables, speed, fileImport, loadingIndicator, loadingLabel, }: UsePromptEditorProps): import("@tiptap/core").Editor | null;
12
+ /**
13
+ * The plain-text prompt editor (`createPromptEditorOptions` from `@pixerate/editor`) as a React
14
+ * hook. Only options baked into extensions recreate the editor; editable state, placeholder,
15
+ * class names and content are applied to the live instance (`syncPromptEditor`).
16
+ */
17
+ export declare function usePromptEditor(props: UsePromptEditorProps): import("@tiptap/core").Editor | null;
package/dist/index.cjs CHANGED
@@ -159,9 +159,6 @@ module.exports = __toCommonJS(src_exports);
159
159
  // src/hooks/usePromptEditor.ts
160
160
  var import_react = __toESM(require("react"), 1);
161
161
  var import_react2 = require("@tiptap/react");
162
- var import_starter_kit = __toESM(require("@tiptap/starter-kit"), 1);
163
- var import_extension_placeholder = __toESM(require("@tiptap/extension-placeholder"), 1);
164
- var import_model = require("@tiptap/pm/model");
165
162
  var import_editor = require("@pixerate/editor");
166
163
 
167
164
  // src/loading-node/LoadingIndicator.tsx
@@ -197,249 +194,39 @@ function createReactLoadingNodeView(component) {
197
194
  }
198
195
 
199
196
  // src/hooks/usePromptEditor.ts
200
- var DEFAULT_TEMPLATES = [];
201
- var DEFAULT_COLOR_MAP = /* @__PURE__ */ new Map([
202
- ["default", { from: "#f43f5e", to: "#8b5cf6" }]
203
- ]);
204
- var DEFAULT_CLASS_NAME = "w-full border border-input rounded-md p-3 font-mono text-sm leading-relaxed focus:outline-none focus:ring-2 focus:ring-primary whitespace-pre-wrap break-words";
205
- var normalizeNewlines = (text) => text.replace(/\r\n?/g, "\n");
206
- function usePromptEditor({
207
- content,
208
- onContentChange,
209
- templates = DEFAULT_TEMPLATES,
210
- templateColorMap: userColorMap,
211
- isEditing = true,
212
- placeholder = "Write a prompt, use {{template}}, {variable}, or /command...",
213
- className,
214
- onEscape,
215
- onKeyDown,
216
- onSelectionChange,
217
- onSlashCommandMatch,
218
- clearSlashCommand,
219
- slashCommandActive = false,
220
- onMilestone,
221
- containerId = "editor-container",
222
- jsonVariables,
223
- speed = 2,
224
- fileImport,
225
- loadingIndicator,
226
- loadingLabel
227
- }) {
228
- const fileImportRef = (0, import_react.useRef)(fileImport);
229
- fileImportRef.current = fileImport;
230
- const fileImportEnabled = !!fileImport;
197
+ function usePromptEditor(props) {
198
+ const propsRef = (0, import_react.useRef)(props);
199
+ propsRef.current = props;
200
+ const { loadingIndicator } = props;
231
201
  const loadingIndicatorRef = (0, import_react.useRef)(loadingIndicator);
232
202
  loadingIndicatorRef.current = loadingIndicator;
233
203
  const hasLoadingIndicator = !!loadingIndicator;
234
204
  const loadingNodeView = (0, import_react.useMemo)(
235
- () => hasLoadingIndicator ? createReactLoadingNodeView((props) => {
205
+ () => hasLoadingIndicator ? createReactLoadingNodeView((indicatorProps) => {
236
206
  const Indicator = loadingIndicatorRef.current;
237
- return Indicator ? import_react.default.createElement(Indicator, props) : null;
207
+ return Indicator ? import_react.default.createElement(Indicator, indicatorProps) : null;
238
208
  }) : null,
239
209
  [hasLoadingIndicator]
240
210
  );
241
- const slashCommandActiveRef = (0, import_react.useRef)(slashCommandActive);
242
- slashCommandActiveRef.current = slashCommandActive;
243
- const clearSlashCommandRef = (0, import_react.useRef)(clearSlashCommand);
244
- clearSlashCommandRef.current = clearSlashCommand;
245
- const onEscapeRef = (0, import_react.useRef)(onEscape);
246
- onEscapeRef.current = onEscape;
247
- const onKeyDownRef = (0, import_react.useRef)(onKeyDown);
248
- onKeyDownRef.current = onKeyDown;
249
- const onSelectionChangeRef = (0, import_react.useRef)(onSelectionChange);
250
- onSelectionChangeRef.current = onSelectionChange;
251
- const onSlashCommandMatchRef = (0, import_react.useRef)(onSlashCommandMatch);
252
- onSlashCommandMatchRef.current = onSlashCommandMatch;
253
- const onContentChangeRef = (0, import_react.useRef)(onContentChange);
254
- onContentChangeRef.current = onContentChange;
255
- const onMilestoneRef = (0, import_react.useRef)(onMilestone);
256
- onMilestoneRef.current = onMilestone;
257
- const containerIdRef = (0, import_react.useRef)(containerId);
258
- containerIdRef.current = containerId;
259
- const templateKey = (0, import_react.useMemo)(() => {
260
- return (templates || []).map((t) => `${t.id || t.name}:${t.latestVersion || ""}`).sort().join(",");
261
- }, [templates]);
262
- const colorMapKey = userColorMap ? JSON.stringify(Array.from(userColorMap.entries())) : "";
263
- const resolvedColorMap = (0, import_react.useMemo)(() => {
264
- if (userColorMap) return userColorMap;
265
- const map = /* @__PURE__ */ new Map();
266
- templates.forEach((t) => {
267
- map.set(t.name, { from: "#f43f5e", to: "#8b5cf6" });
268
- });
269
- return map.size > 0 ? map : DEFAULT_COLOR_MAP;
270
- }, [colorMapKey, templateKey]);
271
- const jsonVariablesKey = (jsonVariables || []).join("\0");
272
211
  const reachedMilestonesRef = (0, import_react.useRef)(/* @__PURE__ */ new Set());
273
- const StarterKitExt = import_starter_kit.default?.configure ? import_starter_kit.default : import_starter_kit.default?.default?.configure ? import_starter_kit.default?.default : import_starter_kit.default;
274
- const PlaceholderExt = import_extension_placeholder.default?.configure ? import_extension_placeholder.default : import_extension_placeholder.default?.default?.configure ? import_extension_placeholder.default?.default : import_extension_placeholder.default;
212
+ const configKey = (0, import_editor.promptEditorConfigKey)(props, { hasLoadingNodeView: hasLoadingIndicator });
275
213
  const editor = (0, import_react2.useEditor)(
276
214
  {
277
215
  immediatelyRender: false,
278
- enablePasteRules: false,
279
- enableInputRules: false,
280
- editable: isEditing,
281
- extensions: [
282
- StarterKitExt.configure({
283
- heading: false,
284
- codeBlock: false
285
- }),
286
- PlaceholderExt.configure({ placeholder }),
287
- import_editor.GradientText.configure({
288
- templateColorMap: resolvedColorMap,
289
- speed,
290
- jsonVariables
291
- }),
292
- import_editor.TemplateSuggestions.configure({
293
- templates
294
- }),
295
- import_editor.LoadingNode.configure({
296
- nodeView: loadingNodeView,
297
- ...loadingLabel ? { label: loadingLabel } : {}
298
- }),
299
- ...fileImportEnabled ? [
300
- import_editor.FileImport.configure({
301
- ...typeof fileImportRef.current === "object" ? fileImportRef.current : {},
302
- // Prompt editors only ever receive plain text.
303
- asPlainText: true
304
- })
305
- ] : []
306
- ],
307
- content: (0, import_editor.plainTextToTipTapHtml)(content),
308
- onUpdate: ({ editor: ed }) => {
309
- const plainText = (0, import_editor.getEditorText)(ed);
310
- onContentChangeRef.current?.(plainText);
311
- if (onMilestoneRef.current) {
312
- const reached = reachedMilestonesRef.current;
313
- for (const token of (0, import_editor.tokenizePrompt)(plainText)) {
314
- const milestone = token.type === "variable" ? "used_variable" : token.type === "instruction" ? "used_magic" : null;
315
- if (milestone && !reached.has(milestone)) {
316
- reached.add(milestone);
317
- onMilestoneRef.current(milestone);
318
- }
319
- }
320
- }
321
- const { state, view } = ed;
322
- const { selection } = state;
323
- const { $from, from, to } = selection;
324
- onSelectionChangeRef.current?.({ from, to });
325
- if (onSlashCommandMatchRef.current && clearSlashCommandRef.current) {
326
- const textBeforeCursor = $from?.parent?.textBetween ? $from.parent.textBetween(0, $from.parentOffset) : "";
327
- const slashMatch = textBeforeCursor.match(
328
- /(?:^|\s)\/([a-zA-Z0-9_-]*)$/
329
- );
330
- if (slashMatch) {
331
- const coords = view.coordsAtPos($from.pos);
332
- const containerEl = document.getElementById(containerIdRef.current) || document.getElementById("editor-container") || view.dom.closest?.(".relative");
333
- const containerCoords = containerEl?.getBoundingClientRect();
334
- if (containerCoords) {
335
- onSlashCommandMatchRef.current(
336
- slashMatch,
337
- $from.pos - slashMatch[0].length + (slashMatch[0].startsWith(" ") ? 1 : 0),
338
- $from.pos,
339
- {
340
- top: coords.bottom - containerCoords.top + 5,
341
- left: coords.left - containerCoords.left
342
- }
343
- );
344
- }
345
- } else {
346
- clearSlashCommandRef.current();
347
- }
348
- }
349
- },
350
- onSelectionUpdate: ({ editor: ed }) => {
351
- const { from, to } = ed.state.selection;
352
- onSelectionChangeRef.current?.({ from, to });
353
- },
354
- editorProps: {
355
- attributes: {
356
- class: className || DEFAULT_CLASS_NAME,
357
- role: "textbox",
358
- "aria-label": "Prompt editor"
359
- },
360
- handleKeyDown(view, event) {
361
- if (slashCommandActiveRef.current) {
362
- if (event.key === "ArrowUp" || event.key === "ArrowDown" || event.key === "Enter") {
363
- event.preventDefault();
364
- return true;
365
- }
366
- if (event.key === "Escape") {
367
- clearSlashCommandRef.current?.();
368
- event.preventDefault();
369
- event.stopPropagation();
370
- return true;
371
- }
372
- }
373
- if (onKeyDownRef.current && onKeyDownRef.current(event)) {
374
- return true;
375
- }
376
- if (event.key === "Escape" && onEscapeRef.current) {
377
- onEscapeRef.current();
378
- return true;
379
- }
380
- return false;
381
- },
382
- handlePaste: (view, event) => {
383
- const text = event.clipboardData?.getData("text/plain");
384
- if (!text) return false;
385
- event.preventDefault();
386
- const schema = view.state.schema;
387
- if (!schema) return false;
388
- view.dispatch(
389
- view.state.tr.replaceSelection((0, import_editor.plainTextToSlice)(text, schema))
390
- );
391
- return true;
392
- },
393
- clipboardTextParser: (text, context, _plain, view) => {
394
- const schema = context?.doc?.type?.schema || context?.schema || view?.state?.schema;
395
- if (!schema) return import_model.Slice.empty;
396
- return (0, import_editor.plainTextToSlice)(text, schema);
397
- }
398
- }
216
+ ...(0, import_editor.createPromptEditorOptions)(() => propsRef.current, {
217
+ loadingNodeView,
218
+ reachedMilestones: reachedMilestonesRef.current
219
+ })
399
220
  },
400
- // Only options baked into extensions recreate the editor; editable state,
401
- // placeholder, class names and content are applied to the live instance.
402
- [resolvedColorMap, templateKey, speed, jsonVariablesKey, fileImportEnabled, loadingNodeView, loadingLabel]
221
+ [configKey, loadingNodeView]
403
222
  );
404
- (0, import_react.useEffect)(() => {
405
- if (editor && !editor.isDestroyed) {
406
- editor.setEditable(isEditing);
407
- }
408
- }, [editor, isEditing]);
223
+ const syncedRef = (0, import_react.useRef)(null);
409
224
  (0, import_react.useEffect)(() => {
410
225
  if (!editor || editor.isDestroyed) return;
411
- if (normalizeNewlines(content) === (0, import_editor.getEditorText)(editor)) return;
412
- const { from, to } = editor.state.selection;
413
- editor.commands.setContent((0, import_editor.plainTextToTipTapHtml)(content), false);
414
- const max = editor.state.doc.content.size;
415
- editor.commands.setTextSelection({
416
- from: Math.min(from, max),
417
- to: Math.min(to, max)
418
- });
419
- }, [editor, content]);
420
- (0, import_react.useEffect)(() => {
421
- if (!editor || editor.isDestroyed) return;
422
- editor.setOptions({
423
- editorProps: {
424
- ...editor.options.editorProps,
425
- attributes: {
426
- ...editor.options.editorProps.attributes,
427
- class: className || DEFAULT_CLASS_NAME
428
- }
429
- }
430
- });
431
- }, [editor, className]);
432
- (0, import_react.useEffect)(() => {
433
- if (!editor || editor.isDestroyed) return;
434
- const placeholderExt = editor.extensionManager.extensions.find(
435
- (ext) => ext.name === "placeholder"
436
- );
437
- if (!placeholderExt || placeholderExt.options.placeholder === placeholder) {
438
- return;
439
- }
440
- placeholderExt.options.placeholder = placeholder;
441
- editor.view.dispatch(editor.state.tr);
442
- }, [editor, placeholder]);
226
+ const previous = syncedRef.current?.editor === editor ? syncedRef.current.config : void 0;
227
+ (0, import_editor.syncPromptEditor)(editor, props, previous);
228
+ syncedRef.current = { editor, config: props };
229
+ });
443
230
  return editor;
444
231
  }
445
232
 
package/dist/index.js CHANGED
@@ -99,18 +99,10 @@ import {
99
99
  // src/hooks/usePromptEditor.ts
100
100
  import React, { useMemo, useEffect, useRef } from "react";
101
101
  import { useEditor } from "@tiptap/react";
102
- import StarterKit from "@tiptap/starter-kit";
103
- import Placeholder from "@tiptap/extension-placeholder";
104
- import { Slice } from "@tiptap/pm/model";
105
102
  import {
106
- GradientText,
107
- TemplateSuggestions,
108
- LoadingNode,
109
- plainTextToTipTapHtml,
110
- plainTextToSlice,
111
- getEditorText,
112
- tokenizePrompt,
113
- FileImport
103
+ createPromptEditorOptions,
104
+ promptEditorConfigKey,
105
+ syncPromptEditor
114
106
  } from "@pixerate/editor";
115
107
 
116
108
  // src/loading-node/LoadingIndicator.tsx
@@ -146,249 +138,39 @@ function createReactLoadingNodeView(component) {
146
138
  }
147
139
 
148
140
  // src/hooks/usePromptEditor.ts
149
- var DEFAULT_TEMPLATES = [];
150
- var DEFAULT_COLOR_MAP = /* @__PURE__ */ new Map([
151
- ["default", { from: "#f43f5e", to: "#8b5cf6" }]
152
- ]);
153
- var DEFAULT_CLASS_NAME = "w-full border border-input rounded-md p-3 font-mono text-sm leading-relaxed focus:outline-none focus:ring-2 focus:ring-primary whitespace-pre-wrap break-words";
154
- var normalizeNewlines = (text) => text.replace(/\r\n?/g, "\n");
155
- function usePromptEditor({
156
- content,
157
- onContentChange,
158
- templates = DEFAULT_TEMPLATES,
159
- templateColorMap: userColorMap,
160
- isEditing = true,
161
- placeholder = "Write a prompt, use {{template}}, {variable}, or /command...",
162
- className,
163
- onEscape,
164
- onKeyDown,
165
- onSelectionChange,
166
- onSlashCommandMatch,
167
- clearSlashCommand,
168
- slashCommandActive = false,
169
- onMilestone,
170
- containerId = "editor-container",
171
- jsonVariables,
172
- speed = 2,
173
- fileImport,
174
- loadingIndicator,
175
- loadingLabel
176
- }) {
177
- const fileImportRef = useRef(fileImport);
178
- fileImportRef.current = fileImport;
179
- const fileImportEnabled = !!fileImport;
141
+ function usePromptEditor(props) {
142
+ const propsRef = useRef(props);
143
+ propsRef.current = props;
144
+ const { loadingIndicator } = props;
180
145
  const loadingIndicatorRef = useRef(loadingIndicator);
181
146
  loadingIndicatorRef.current = loadingIndicator;
182
147
  const hasLoadingIndicator = !!loadingIndicator;
183
148
  const loadingNodeView = useMemo(
184
- () => hasLoadingIndicator ? createReactLoadingNodeView((props) => {
149
+ () => hasLoadingIndicator ? createReactLoadingNodeView((indicatorProps) => {
185
150
  const Indicator = loadingIndicatorRef.current;
186
- return Indicator ? React.createElement(Indicator, props) : null;
151
+ return Indicator ? React.createElement(Indicator, indicatorProps) : null;
187
152
  }) : null,
188
153
  [hasLoadingIndicator]
189
154
  );
190
- const slashCommandActiveRef = useRef(slashCommandActive);
191
- slashCommandActiveRef.current = slashCommandActive;
192
- const clearSlashCommandRef = useRef(clearSlashCommand);
193
- clearSlashCommandRef.current = clearSlashCommand;
194
- const onEscapeRef = useRef(onEscape);
195
- onEscapeRef.current = onEscape;
196
- const onKeyDownRef = useRef(onKeyDown);
197
- onKeyDownRef.current = onKeyDown;
198
- const onSelectionChangeRef = useRef(onSelectionChange);
199
- onSelectionChangeRef.current = onSelectionChange;
200
- const onSlashCommandMatchRef = useRef(onSlashCommandMatch);
201
- onSlashCommandMatchRef.current = onSlashCommandMatch;
202
- const onContentChangeRef = useRef(onContentChange);
203
- onContentChangeRef.current = onContentChange;
204
- const onMilestoneRef = useRef(onMilestone);
205
- onMilestoneRef.current = onMilestone;
206
- const containerIdRef = useRef(containerId);
207
- containerIdRef.current = containerId;
208
- const templateKey = useMemo(() => {
209
- return (templates || []).map((t) => `${t.id || t.name}:${t.latestVersion || ""}`).sort().join(",");
210
- }, [templates]);
211
- const colorMapKey = userColorMap ? JSON.stringify(Array.from(userColorMap.entries())) : "";
212
- const resolvedColorMap = useMemo(() => {
213
- if (userColorMap) return userColorMap;
214
- const map = /* @__PURE__ */ new Map();
215
- templates.forEach((t) => {
216
- map.set(t.name, { from: "#f43f5e", to: "#8b5cf6" });
217
- });
218
- return map.size > 0 ? map : DEFAULT_COLOR_MAP;
219
- }, [colorMapKey, templateKey]);
220
- const jsonVariablesKey = (jsonVariables || []).join("\0");
221
155
  const reachedMilestonesRef = useRef(/* @__PURE__ */ new Set());
222
- const StarterKitExt = StarterKit?.configure ? StarterKit : StarterKit?.default?.configure ? StarterKit?.default : StarterKit;
223
- const PlaceholderExt = Placeholder?.configure ? Placeholder : Placeholder?.default?.configure ? Placeholder?.default : Placeholder;
156
+ const configKey = promptEditorConfigKey(props, { hasLoadingNodeView: hasLoadingIndicator });
224
157
  const editor = useEditor(
225
158
  {
226
159
  immediatelyRender: false,
227
- enablePasteRules: false,
228
- enableInputRules: false,
229
- editable: isEditing,
230
- extensions: [
231
- StarterKitExt.configure({
232
- heading: false,
233
- codeBlock: false
234
- }),
235
- PlaceholderExt.configure({ placeholder }),
236
- GradientText.configure({
237
- templateColorMap: resolvedColorMap,
238
- speed,
239
- jsonVariables
240
- }),
241
- TemplateSuggestions.configure({
242
- templates
243
- }),
244
- LoadingNode.configure({
245
- nodeView: loadingNodeView,
246
- ...loadingLabel ? { label: loadingLabel } : {}
247
- }),
248
- ...fileImportEnabled ? [
249
- FileImport.configure({
250
- ...typeof fileImportRef.current === "object" ? fileImportRef.current : {},
251
- // Prompt editors only ever receive plain text.
252
- asPlainText: true
253
- })
254
- ] : []
255
- ],
256
- content: plainTextToTipTapHtml(content),
257
- onUpdate: ({ editor: ed }) => {
258
- const plainText = getEditorText(ed);
259
- onContentChangeRef.current?.(plainText);
260
- if (onMilestoneRef.current) {
261
- const reached = reachedMilestonesRef.current;
262
- for (const token of tokenizePrompt(plainText)) {
263
- const milestone = token.type === "variable" ? "used_variable" : token.type === "instruction" ? "used_magic" : null;
264
- if (milestone && !reached.has(milestone)) {
265
- reached.add(milestone);
266
- onMilestoneRef.current(milestone);
267
- }
268
- }
269
- }
270
- const { state, view } = ed;
271
- const { selection } = state;
272
- const { $from, from, to } = selection;
273
- onSelectionChangeRef.current?.({ from, to });
274
- if (onSlashCommandMatchRef.current && clearSlashCommandRef.current) {
275
- const textBeforeCursor = $from?.parent?.textBetween ? $from.parent.textBetween(0, $from.parentOffset) : "";
276
- const slashMatch = textBeforeCursor.match(
277
- /(?:^|\s)\/([a-zA-Z0-9_-]*)$/
278
- );
279
- if (slashMatch) {
280
- const coords = view.coordsAtPos($from.pos);
281
- const containerEl = document.getElementById(containerIdRef.current) || document.getElementById("editor-container") || view.dom.closest?.(".relative");
282
- const containerCoords = containerEl?.getBoundingClientRect();
283
- if (containerCoords) {
284
- onSlashCommandMatchRef.current(
285
- slashMatch,
286
- $from.pos - slashMatch[0].length + (slashMatch[0].startsWith(" ") ? 1 : 0),
287
- $from.pos,
288
- {
289
- top: coords.bottom - containerCoords.top + 5,
290
- left: coords.left - containerCoords.left
291
- }
292
- );
293
- }
294
- } else {
295
- clearSlashCommandRef.current();
296
- }
297
- }
298
- },
299
- onSelectionUpdate: ({ editor: ed }) => {
300
- const { from, to } = ed.state.selection;
301
- onSelectionChangeRef.current?.({ from, to });
302
- },
303
- editorProps: {
304
- attributes: {
305
- class: className || DEFAULT_CLASS_NAME,
306
- role: "textbox",
307
- "aria-label": "Prompt editor"
308
- },
309
- handleKeyDown(view, event) {
310
- if (slashCommandActiveRef.current) {
311
- if (event.key === "ArrowUp" || event.key === "ArrowDown" || event.key === "Enter") {
312
- event.preventDefault();
313
- return true;
314
- }
315
- if (event.key === "Escape") {
316
- clearSlashCommandRef.current?.();
317
- event.preventDefault();
318
- event.stopPropagation();
319
- return true;
320
- }
321
- }
322
- if (onKeyDownRef.current && onKeyDownRef.current(event)) {
323
- return true;
324
- }
325
- if (event.key === "Escape" && onEscapeRef.current) {
326
- onEscapeRef.current();
327
- return true;
328
- }
329
- return false;
330
- },
331
- handlePaste: (view, event) => {
332
- const text = event.clipboardData?.getData("text/plain");
333
- if (!text) return false;
334
- event.preventDefault();
335
- const schema = view.state.schema;
336
- if (!schema) return false;
337
- view.dispatch(
338
- view.state.tr.replaceSelection(plainTextToSlice(text, schema))
339
- );
340
- return true;
341
- },
342
- clipboardTextParser: (text, context, _plain, view) => {
343
- const schema = context?.doc?.type?.schema || context?.schema || view?.state?.schema;
344
- if (!schema) return Slice.empty;
345
- return plainTextToSlice(text, schema);
346
- }
347
- }
160
+ ...createPromptEditorOptions(() => propsRef.current, {
161
+ loadingNodeView,
162
+ reachedMilestones: reachedMilestonesRef.current
163
+ })
348
164
  },
349
- // Only options baked into extensions recreate the editor; editable state,
350
- // placeholder, class names and content are applied to the live instance.
351
- [resolvedColorMap, templateKey, speed, jsonVariablesKey, fileImportEnabled, loadingNodeView, loadingLabel]
165
+ [configKey, loadingNodeView]
352
166
  );
353
- useEffect(() => {
354
- if (editor && !editor.isDestroyed) {
355
- editor.setEditable(isEditing);
356
- }
357
- }, [editor, isEditing]);
358
- useEffect(() => {
359
- if (!editor || editor.isDestroyed) return;
360
- if (normalizeNewlines(content) === getEditorText(editor)) return;
361
- const { from, to } = editor.state.selection;
362
- editor.commands.setContent(plainTextToTipTapHtml(content), false);
363
- const max = editor.state.doc.content.size;
364
- editor.commands.setTextSelection({
365
- from: Math.min(from, max),
366
- to: Math.min(to, max)
367
- });
368
- }, [editor, content]);
167
+ const syncedRef = useRef(null);
369
168
  useEffect(() => {
370
169
  if (!editor || editor.isDestroyed) return;
371
- editor.setOptions({
372
- editorProps: {
373
- ...editor.options.editorProps,
374
- attributes: {
375
- ...editor.options.editorProps.attributes,
376
- class: className || DEFAULT_CLASS_NAME
377
- }
378
- }
379
- });
380
- }, [editor, className]);
381
- useEffect(() => {
382
- if (!editor || editor.isDestroyed) return;
383
- const placeholderExt = editor.extensionManager.extensions.find(
384
- (ext) => ext.name === "placeholder"
385
- );
386
- if (!placeholderExt || placeholderExt.options.placeholder === placeholder) {
387
- return;
388
- }
389
- placeholderExt.options.placeholder = placeholder;
390
- editor.view.dispatch(editor.state.tr);
391
- }, [editor, placeholder]);
170
+ const previous = syncedRef.current?.editor === editor ? syncedRef.current.config : void 0;
171
+ syncPromptEditor(editor, props, previous);
172
+ syncedRef.current = { editor, config: props };
173
+ });
392
174
  return editor;
393
175
  }
394
176
 
@@ -12,7 +12,8 @@ export interface BrushPanelProps {
12
12
  * grouped by medium and variety, tools apart) and the active brush in the `BrushEditor`: its
13
13
  * facets with a live preview, and "Save brush" into the editor's brush library. The paint
14
14
  * editor adds the brush's own gradient, the sticker stamps, what the brush carries (Load /
15
- * Clean), and import and export of library files. Images picked for an image tip or grain are
15
+ * Clean), and import and export of library files; import also reads brush packs (`.abr`,
16
+ * `.brush`, `.brushset`). Images picked for an image tip or grain are
16
17
  * added to the brush library as sources.
17
18
  */
18
19
  export declare const BrushPanel: React.FC<BrushPanelProps>;
@@ -12,7 +12,8 @@ export interface BrushPanelProps {
12
12
  * grouped by medium and variety, tools apart) and the active brush in the `BrushEditor`: its
13
13
  * facets with a live preview, and "Save brush" into the editor's brush library. The paint
14
14
  * editor adds the brush's own gradient, the sticker stamps, what the brush carries (Load /
15
- * Clean), and import and export of library files. Images picked for an image tip or grain are
15
+ * Clean), and import and export of library files; import also reads brush packs (`.abr`,
16
+ * `.brush`, `.brushset`). Images picked for an image tip or grain are
16
17
  * added to the brush library as sources.
17
18
  */
18
19
  export declare const BrushPanel: React.FC<BrushPanelProps>;
@@ -1138,12 +1138,12 @@ var BrushPanel = ({ controller, thumbnailWidth = 112, thumbnailHeight = 32, clas
1138
1138
  {
1139
1139
  ref: fileRef,
1140
1140
  type: "file",
1141
- accept: ".json,application/json",
1141
+ accept: ".json,.abr,.brush,.brushset,application/json",
1142
1142
  "aria-label": "Import brushes",
1143
1143
  className: "hidden",
1144
1144
  onChange: (e) => {
1145
1145
  const f = e.target.files?.[0];
1146
- if (f) attempt(async () => controller.importBrushes(JSON.parse(await f.text())));
1146
+ if (f) attempt(async () => /\.json$/i.test(f.name) ? controller.importBrushes(JSON.parse(await f.text())) : (0, import_brushes3.importBrushFile)(controller.brushLibrary, f));
1147
1147
  e.target.value = "";
1148
1148
  }
1149
1149
  }
@@ -559,7 +559,7 @@ var PaintToolbar = ({ controller, tool, onToolChange, fileName = "painting", cla
559
559
  // src/paint-editor/BrushPanel.tsx
560
560
  import { useMemo as useMemo3, useRef as useRef4 } from "react";
561
561
  import { brushLoadColor, brushTakesPaint, downloadBytes as downloadBytes2, toggleStickerRef, DEFAULT_PAINT_GRADIENT } from "@pixerate/editor/paint-editor";
562
- import { addBrushSourceFromFile, brushColourHex, brushPreviewColours, PAINT_PROFILE } from "@pixerate/editor/brushes";
562
+ import { addBrushSourceFromFile, importBrushFile, brushColourHex, brushPreviewColours, PAINT_PROFILE } from "@pixerate/editor/brushes";
563
563
 
564
564
  // src/paint-editor/PaintGradientEditor.tsx
565
565
  import { PAINT_GRADIENT_KIT } from "@pixerate/editor/paint-editor";
@@ -661,12 +661,12 @@ var BrushPanel = ({ controller, thumbnailWidth = 112, thumbnailHeight = 32, clas
661
661
  {
662
662
  ref: fileRef,
663
663
  type: "file",
664
- accept: ".json,application/json",
664
+ accept: ".json,.abr,.brush,.brushset,application/json",
665
665
  "aria-label": "Import brushes",
666
666
  className: "hidden",
667
667
  onChange: (e) => {
668
668
  const f = e.target.files?.[0];
669
- if (f) attempt(async () => controller.importBrushes(JSON.parse(await f.text())));
669
+ if (f) attempt(async () => /\.json$/i.test(f.name) ? controller.importBrushes(JSON.parse(await f.text())) : importBrushFile(controller.brushLibrary, f));
670
670
  e.target.value = "";
671
671
  }
672
672
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pixerate/editor-react",
3
- "version": "0.183.1",
3
+ "version": "0.184.0",
4
4
  "description": "React bindings and prompt/rich-text components for @pixerate/editor",
5
5
  "author": "Pixerate",
6
6
  "license": "MIT",
@@ -283,7 +283,7 @@
283
283
  "dependencies": {},
284
284
  "peerDependencies": {
285
285
  "@dagrejs/dagre": "^1.1.8",
286
- "@pixerate/editor": ">=0.268.2 <1.0.0-0",
286
+ "@pixerate/editor": ">=0.269.0 <1.0.0-0",
287
287
  "@tiptap/core": "^2.27.3",
288
288
  "@tiptap/extension-bubble-menu": "^2.27.3",
289
289
  "@tiptap/extension-placeholder": "^2.27.3",
@@ -334,7 +334,7 @@
334
334
  "tsup": "^9.0.0",
335
335
  "typescript": "^5.7.3",
336
336
  "vitest": "^5.0.5",
337
- "@pixerate/editor": "0.268.2"
337
+ "@pixerate/editor": "0.269.0"
338
338
  },
339
339
  "scripts": {
340
340
  "build": "tsup && tsc -p tsconfig.build.json && node ../../scripts/finalize-declarations.mjs dist",