@pixerate/editor 0.1.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/dist/index.js ADDED
@@ -0,0 +1,1082 @@
1
+ // src/grammar/tokens.ts
2
+ var TEMPLATE_REGEX = /{{\s*([^}]+?)\s*}}/g;
3
+ var VARIABLE_REGEX = /(?<!\{)\{([^{}]+)\}(?!\})/g;
4
+ var INSTRUCTION_REGEX = /__(.+?)__/g;
5
+ var templateRegex = TEMPLATE_REGEX;
6
+ var variableRegex = VARIABLE_REGEX;
7
+ var instructionRegex = INSTRUCTION_REGEX;
8
+
9
+ // src/grammar/tokenizer.ts
10
+ function tokenizePrompt(text) {
11
+ if (!text) {
12
+ return [];
13
+ }
14
+ const rawMatches = [];
15
+ const tmplRegex = new RegExp(TEMPLATE_REGEX.source, TEMPLATE_REGEX.flags);
16
+ let match;
17
+ while ((match = tmplRegex.exec(text)) !== null) {
18
+ rawMatches.push({
19
+ type: "template",
20
+ raw: match[0],
21
+ value: match[1].trim(),
22
+ start: match.index,
23
+ end: match.index + match[0].length
24
+ });
25
+ }
26
+ const varRegex = new RegExp(VARIABLE_REGEX.source, VARIABLE_REGEX.flags);
27
+ while ((match = varRegex.exec(text)) !== null) {
28
+ const start = match.index;
29
+ const end = start + match[0].length;
30
+ const overlaps = rawMatches.some(
31
+ (m) => !(end <= m.start || start >= m.end)
32
+ );
33
+ if (!overlaps) {
34
+ rawMatches.push({
35
+ type: "variable",
36
+ raw: match[0],
37
+ value: match[1].trim(),
38
+ start,
39
+ end
40
+ });
41
+ }
42
+ }
43
+ const instRegex = new RegExp(
44
+ INSTRUCTION_REGEX.source,
45
+ INSTRUCTION_REGEX.flags
46
+ );
47
+ while ((match = instRegex.exec(text)) !== null) {
48
+ const start = match.index;
49
+ const end = start + match[0].length;
50
+ const overlaps = rawMatches.some(
51
+ (m) => !(end <= m.start || start >= m.end)
52
+ );
53
+ if (!overlaps) {
54
+ rawMatches.push({
55
+ type: "instruction",
56
+ raw: match[0],
57
+ value: match[1].trim(),
58
+ start,
59
+ end
60
+ });
61
+ }
62
+ }
63
+ rawMatches.sort((a, b) => a.start - b.start);
64
+ const tokens = [];
65
+ let currentIdx = 0;
66
+ for (const m of rawMatches) {
67
+ if (m.start > currentIdx) {
68
+ const textChunk = text.slice(currentIdx, m.start);
69
+ tokens.push({
70
+ type: "text",
71
+ raw: textChunk,
72
+ value: textChunk,
73
+ start: currentIdx,
74
+ end: m.start
75
+ });
76
+ }
77
+ tokens.push({
78
+ type: m.type,
79
+ raw: m.raw,
80
+ value: m.value,
81
+ start: m.start,
82
+ end: m.end
83
+ });
84
+ currentIdx = m.end;
85
+ }
86
+ if (currentIdx < text.length) {
87
+ const textChunk = text.slice(currentIdx);
88
+ tokens.push({
89
+ type: "text",
90
+ raw: textChunk,
91
+ value: textChunk,
92
+ start: currentIdx,
93
+ end: text.length
94
+ });
95
+ }
96
+ return tokens;
97
+ }
98
+
99
+ // src/grammar/resolver.ts
100
+ function getLatestVersion(template) {
101
+ if (!template.versions || template.versions.length === 0) {
102
+ if (template.body !== void 0) {
103
+ return {
104
+ id: template.id || "default",
105
+ version: "1.0",
106
+ body: template.body
107
+ };
108
+ }
109
+ return void 0;
110
+ }
111
+ if (template.latestVersion) {
112
+ const found = template.versions.find(
113
+ (v) => v.version === template.latestVersion
114
+ );
115
+ if (found) return found;
116
+ }
117
+ return template.versions[template.versions.length - 1];
118
+ }
119
+ function resolveTemplates(text, templates = [], options) {
120
+ const templateMap = /* @__PURE__ */ new Map();
121
+ for (const t of templates) {
122
+ templateMap.set(t.name, t);
123
+ }
124
+ const maxDepth = options?.maxDepth ?? 10;
125
+ function resolveRecursive(currentText, visited, depth) {
126
+ if (depth > maxDepth) {
127
+ return "[Template max depth exceeded]";
128
+ }
129
+ let result = currentText;
130
+ const regex = new RegExp(TEMPLATE_REGEX.source, TEMPLATE_REGEX.flags);
131
+ let match;
132
+ while ((match = regex.exec(result)) !== null) {
133
+ const [fullMatch, rawTemplateName] = match;
134
+ const templateName = rawTemplateName.trim();
135
+ if (visited.has(templateName)) {
136
+ return "[Template loop detected]";
137
+ }
138
+ const template = templateMap.get(templateName);
139
+ if (!template) {
140
+ continue;
141
+ }
142
+ let versionBody;
143
+ const boundVersionId = options?.bindings?.[templateName];
144
+ if (boundVersionId && template.versions) {
145
+ const boundVersion = template.versions.find(
146
+ (v) => v.id === boundVersionId || v.version === boundVersionId
147
+ );
148
+ versionBody = boundVersion?.body;
149
+ } else {
150
+ const latest = getLatestVersion(template);
151
+ versionBody = latest?.body ?? template.body;
152
+ }
153
+ if (versionBody === void 0) {
154
+ continue;
155
+ }
156
+ const nextVisited = new Set(visited);
157
+ nextVisited.add(templateName);
158
+ const resolvedBody = resolveRecursive(
159
+ versionBody,
160
+ nextVisited,
161
+ depth + 1
162
+ );
163
+ if (resolvedBody === "[Template loop detected]" || resolvedBody === "[Template max depth exceeded]") {
164
+ return resolvedBody;
165
+ }
166
+ result = result.replace(fullMatch, resolvedBody);
167
+ regex.lastIndex = 0;
168
+ }
169
+ return result;
170
+ }
171
+ return resolveRecursive(text, /* @__PURE__ */ new Set(), 0);
172
+ }
173
+ function resolveVariables(text, values) {
174
+ if (!text) return "";
175
+ return text.replace(
176
+ new RegExp(VARIABLE_REGEX.source, VARIABLE_REGEX.flags),
177
+ (fullMatch, varName) => {
178
+ const key = varName.trim();
179
+ if (Object.prototype.hasOwnProperty.call(values, key)) {
180
+ return String(values[key]);
181
+ }
182
+ return fullMatch;
183
+ }
184
+ );
185
+ }
186
+ function extractTemplateNames(text) {
187
+ if (!text) return [];
188
+ const set = /* @__PURE__ */ new Set();
189
+ const regex = new RegExp(TEMPLATE_REGEX.source, TEMPLATE_REGEX.flags);
190
+ let match;
191
+ while ((match = regex.exec(text)) !== null) {
192
+ set.add(match[1].trim());
193
+ }
194
+ return Array.from(set);
195
+ }
196
+ function extractVariableNames(text) {
197
+ if (!text) return [];
198
+ const set = /* @__PURE__ */ new Set();
199
+ const regex = new RegExp(VARIABLE_REGEX.source, VARIABLE_REGEX.flags);
200
+ let match;
201
+ while ((match = regex.exec(text)) !== null) {
202
+ set.add(match[1].trim());
203
+ }
204
+ return Array.from(set);
205
+ }
206
+ function extractInstructionNames(text) {
207
+ if (!text) return [];
208
+ const set = /* @__PURE__ */ new Set();
209
+ const regex = new RegExp(INSTRUCTION_REGEX.source, INSTRUCTION_REGEX.flags);
210
+ let match;
211
+ while ((match = regex.exec(text)) !== null) {
212
+ set.add(match[1].trim());
213
+ }
214
+ return Array.from(set);
215
+ }
216
+
217
+ // src/grammar/sourcemap.ts
218
+ function resolveTemplatesWithMapping(text, templates = [], templateBindings) {
219
+ if (!templates || templates.length === 0 || !text.includes("{{")) {
220
+ return {
221
+ text,
222
+ map: [
223
+ {
224
+ resolvedStart: 0,
225
+ resolvedEnd: text.length,
226
+ source: "raw",
227
+ rawStart: 0,
228
+ rawEnd: text.length
229
+ }
230
+ ]
231
+ };
232
+ }
233
+ const templateMap = new Map(templates.map((t) => [t.name, t]));
234
+ const regex = /{{\s*([^}]+?)\s*}}/g;
235
+ let match;
236
+ let lastIndex = 0;
237
+ let resolvedText = "";
238
+ const map = [];
239
+ while ((match = regex.exec(text)) !== null) {
240
+ const [fullMatch, rawTemplateName] = match;
241
+ const templateName = rawTemplateName.trim();
242
+ const matchIndex = match.index;
243
+ if (matchIndex > lastIndex) {
244
+ const rawSegment = text.substring(lastIndex, matchIndex);
245
+ map.push({
246
+ resolvedStart: resolvedText.length,
247
+ resolvedEnd: resolvedText.length + rawSegment.length,
248
+ source: "raw",
249
+ rawStart: lastIndex,
250
+ rawEnd: matchIndex
251
+ });
252
+ resolvedText += rawSegment;
253
+ }
254
+ let resolvedBody = fullMatch;
255
+ let isTemplate = false;
256
+ if (templateMap.has(templateName)) {
257
+ const template = templateMap.get(templateName);
258
+ let versionBody;
259
+ const boundVersionId = templateBindings?.[templateName];
260
+ if (boundVersionId && template.versions) {
261
+ const boundVersion = template.versions.find(
262
+ (v) => v.id === boundVersionId || v.version === boundVersionId
263
+ );
264
+ versionBody = boundVersion?.body;
265
+ } else {
266
+ const latestVersion = getLatestVersion(template);
267
+ versionBody = latestVersion?.body ?? template.body;
268
+ }
269
+ if (versionBody !== void 0) {
270
+ resolvedBody = resolveTemplates(versionBody, templates, {
271
+ bindings: templateBindings
272
+ });
273
+ isTemplate = true;
274
+ }
275
+ }
276
+ if (isTemplate) {
277
+ map.push({
278
+ resolvedStart: resolvedText.length,
279
+ resolvedEnd: resolvedText.length + resolvedBody.length,
280
+ source: "template",
281
+ rawStart: matchIndex,
282
+ rawEnd: matchIndex + fullMatch.length,
283
+ templateName
284
+ });
285
+ resolvedText += resolvedBody;
286
+ } else {
287
+ map.push({
288
+ resolvedStart: resolvedText.length,
289
+ resolvedEnd: resolvedText.length + fullMatch.length,
290
+ source: "raw",
291
+ rawStart: matchIndex,
292
+ rawEnd: matchIndex + fullMatch.length
293
+ });
294
+ resolvedText += fullMatch;
295
+ }
296
+ lastIndex = matchIndex + fullMatch.length;
297
+ }
298
+ if (lastIndex < text.length) {
299
+ const rawSegment = text.substring(lastIndex);
300
+ map.push({
301
+ resolvedStart: resolvedText.length,
302
+ resolvedEnd: resolvedText.length + rawSegment.length,
303
+ source: "raw",
304
+ rawStart: lastIndex,
305
+ rawEnd: text.length
306
+ });
307
+ resolvedText += rawSegment;
308
+ }
309
+ return { text: resolvedText, map };
310
+ }
311
+ function mapResolvedOffsetToRaw(resolvedOffset, map) {
312
+ for (let i = 0; i < map.length; i++) {
313
+ const seg = map[i];
314
+ const isLast = i === map.length - 1;
315
+ const inRange = isLast ? resolvedOffset >= seg.resolvedStart && resolvedOffset <= seg.resolvedEnd : resolvedOffset >= seg.resolvedStart && resolvedOffset < seg.resolvedEnd;
316
+ if (inRange) {
317
+ if (seg.source === "raw") {
318
+ return seg.rawStart + (resolvedOffset - seg.resolvedStart);
319
+ } else {
320
+ return seg.rawStart;
321
+ }
322
+ }
323
+ }
324
+ return resolvedOffset;
325
+ }
326
+ function mapRawOffsetToResolved(rawOffset, map) {
327
+ for (let i = 0; i < map.length; i++) {
328
+ const seg = map[i];
329
+ const isLast = i === map.length - 1;
330
+ const inRange = isLast ? rawOffset >= seg.rawStart && rawOffset <= seg.rawEnd : rawOffset >= seg.rawStart && rawOffset < seg.rawEnd;
331
+ if (inRange) {
332
+ if (seg.source === "raw") {
333
+ return seg.resolvedStart + (rawOffset - seg.rawStart);
334
+ } else {
335
+ return seg.resolvedStart;
336
+ }
337
+ }
338
+ }
339
+ return rawOffset;
340
+ }
341
+
342
+ // src/extensions/gradient-text.ts
343
+ import { Mark } from "@tiptap/core";
344
+ import { Plugin } from "@tiptap/pm/state";
345
+ import { Decoration, DecorationSet } from "@tiptap/pm/view";
346
+ var createGradientDecorations = (doc, options) => {
347
+ const decorations = [];
348
+ const speed = options.speed ?? 1;
349
+ const jsonVarSet = options.jsonVariables ? options.jsonVariables instanceof Set ? options.jsonVariables : new Set(options.jsonVariables) : null;
350
+ doc.descendants((node, pos) => {
351
+ if (node.isText) {
352
+ const text = node.text || "";
353
+ let match;
354
+ const tmplRegex = new RegExp(TEMPLATE_REGEX.source, TEMPLATE_REGEX.flags);
355
+ while ((match = tmplRegex.exec(text)) !== null) {
356
+ const templateName = match[1].trim();
357
+ const colors = options.templateColorMap?.get(templateName);
358
+ if (colors) {
359
+ const start = pos + match.index;
360
+ const end = start + match[0].length;
361
+ const { from: colorFrom, to: colorTo } = colors;
362
+ const style = `--bg-size: ${speed * 300}%; --color-from: ${colorFrom}; --color-to: ${colorTo}; caret-color: #111 !important;`;
363
+ decorations.push(
364
+ Decoration.inline(start, end, {
365
+ class: "inline animate-gradient bg-gradient-to-r from-[var(--color-from)] via-[var(--color-to)] to-[var(--color-from)] bg-[length:var(--bg-size)_100%] bg-clip-text text-transparent border border-(--color-to)/20 px-1 py-0.5 rounded-sm cursor-pointer",
366
+ style,
367
+ "data-template": templateName
368
+ })
369
+ );
370
+ }
371
+ }
372
+ const instRegex = new RegExp(
373
+ INSTRUCTION_REGEX.source,
374
+ INSTRUCTION_REGEX.flags
375
+ );
376
+ while ((match = instRegex.exec(text)) !== null) {
377
+ const content = match[1].trim();
378
+ const colors = options.templateColorMap?.get(content) || {
379
+ from: "#ffaa40",
380
+ to: "#9c40ff"
381
+ };
382
+ const start = pos + match.index;
383
+ const end = start + match[0].length;
384
+ const { from: colorFrom, to: colorTo } = colors;
385
+ const style = `--bg-size: ${speed * 300}%; --color-from: ${colorFrom}; --color-to: ${colorTo}; caret-color: #111 !important;`;
386
+ decorations.push(
387
+ Decoration.inline(start, end, {
388
+ class: "italic animate-gradient bg-gradient-to-r from-rose-400 from-50% to-violet-500 to-50% bg-size-[200%_100%] bg-clip-text text-transparent inline-flex items-baseline gap-0.5",
389
+ style
390
+ })
391
+ );
392
+ }
393
+ const varRegex = new RegExp(
394
+ VARIABLE_REGEX.source,
395
+ VARIABLE_REGEX.flags
396
+ );
397
+ while ((match = varRegex.exec(text)) !== null) {
398
+ const variableName = match[1].trim();
399
+ const start = pos + match.index;
400
+ const end = start + match[0].length;
401
+ const isJsonVar = jsonVarSet?.has(variableName);
402
+ decorations.push(
403
+ Decoration.inline(start, end, {
404
+ class: isJsonVar ? "bg-violet-400/40 border-b-4 border-rose-300 dark:border-rose-800 inline-flex items-baseline px-1 py-0 text-foreground/80 gap-0.5 rounded-xs" : "bg-rose-400/40 border-b-4 border-violet-300 dark:border-violet-800 inline-flex items-baseline px-1 py-0 text-foreground/80 gap-0.5 rounded-xs",
405
+ "data-variable": variableName
406
+ })
407
+ );
408
+ }
409
+ }
410
+ });
411
+ return decorations;
412
+ };
413
+ var GradientText = Mark.create({
414
+ name: "gradientText",
415
+ addOptions() {
416
+ return {
417
+ templateColorMap: /* @__PURE__ */ new Map(),
418
+ speed: 1,
419
+ jsonVariables: void 0,
420
+ onTemplateClick: void 0
421
+ };
422
+ },
423
+ renderHTML({ HTMLAttributes }) {
424
+ const defaultColors = {
425
+ from: "#ffaa40",
426
+ to: "#9c40ff"
427
+ };
428
+ const speed = this.options.speed ?? 1;
429
+ const style = `--bg-size: ${speed * 300}%; --color-from: ${defaultColors.from}; --color-to: ${defaultColors.to}; caret-color: #111 !important;`;
430
+ return [
431
+ "span",
432
+ {
433
+ class: "inline animate-gradient bg-gradient-to-r from-[var(--color-from)] via-[var(--color-to)] to-[var(--color-from)] bg-[length:var(--bg-size)_100%] bg-clip-text text-transparent",
434
+ style,
435
+ ...HTMLAttributes
436
+ },
437
+ 0
438
+ ];
439
+ },
440
+ parseHTML() {
441
+ return [
442
+ {
443
+ tag: "span",
444
+ getAttrs: (node) => node.classList.contains("animate-gradient") && node.classList.contains("bg-clip-text") && null
445
+ }
446
+ ];
447
+ },
448
+ addProseMirrorPlugins() {
449
+ const markOptions = this.options;
450
+ return [
451
+ new Plugin({
452
+ state: {
453
+ init(_, { doc }) {
454
+ return DecorationSet.create(
455
+ doc,
456
+ createGradientDecorations(doc, markOptions)
457
+ );
458
+ },
459
+ apply(tr, value) {
460
+ const newDoc = tr.doc;
461
+ if (tr.docChanged) {
462
+ return DecorationSet.create(
463
+ newDoc,
464
+ createGradientDecorations(newDoc, markOptions)
465
+ );
466
+ }
467
+ return value.map(tr.mapping, newDoc);
468
+ }
469
+ },
470
+ props: {
471
+ decorations(state) {
472
+ return this.getState(state);
473
+ },
474
+ handleClickOn(view, pos, _node, _nodePos, event) {
475
+ const decorationSet = this.getState(
476
+ view.state
477
+ );
478
+ const decorations = decorationSet.find(pos, pos + 1);
479
+ for (const decoration of decorations) {
480
+ const decorationWithAttrs = decoration;
481
+ const templateName = decorationWithAttrs.type?.attrs?.["data-template"];
482
+ if (templateName) {
483
+ if (markOptions.onTemplateClick) {
484
+ markOptions.onTemplateClick(templateName, event);
485
+ }
486
+ if (typeof window !== "undefined") {
487
+ window.dispatchEvent(
488
+ new CustomEvent("show-gradient-popover", {
489
+ detail: {
490
+ templateName,
491
+ target: event.target
492
+ }
493
+ })
494
+ );
495
+ }
496
+ return true;
497
+ }
498
+ }
499
+ return false;
500
+ }
501
+ }
502
+ })
503
+ ];
504
+ }
505
+ });
506
+
507
+ // src/extensions/slash-commands.ts
508
+ import { Extension } from "@tiptap/core";
509
+ import { Plugin as Plugin2 } from "@tiptap/pm/state";
510
+ var SlashCommands = Extension.create({
511
+ name: "slashCommands",
512
+ addOptions() {
513
+ return {
514
+ trigger: "/",
515
+ onMatch: void 0,
516
+ onClear: void 0,
517
+ containerId: void 0
518
+ };
519
+ },
520
+ addProseMirrorPlugins() {
521
+ const opts = this.options;
522
+ return [
523
+ new Plugin2({
524
+ view() {
525
+ return {
526
+ update(view) {
527
+ const { state } = view;
528
+ const { selection } = state;
529
+ const { $from } = selection;
530
+ if (!$from.parent.isTextblock) {
531
+ opts.onClear?.();
532
+ return;
533
+ }
534
+ const textBeforeCursor = $from.parent.textBetween(
535
+ 0,
536
+ $from.parentOffset
537
+ );
538
+ const slashMatch = textBeforeCursor.match(
539
+ /(?:^|\s)\/([a-zA-Z0-9_-]*)$/
540
+ );
541
+ if (slashMatch) {
542
+ const matchIndex = slashMatch.index ?? 0;
543
+ const offsetInParent = matchIndex + (slashMatch[0].startsWith(" ") ? 1 : 0);
544
+ const matchFrom = $from.start() + offsetInParent;
545
+ const matchTo = $from.pos;
546
+ const coords = view.coordsAtPos($from.pos);
547
+ let relativeCoords = {
548
+ top: coords.top,
549
+ left: coords.left,
550
+ bottom: coords.bottom,
551
+ right: coords.right
552
+ };
553
+ if (opts.containerId && typeof document !== "undefined") {
554
+ const container = document.getElementById(opts.containerId);
555
+ if (container) {
556
+ const rect = container.getBoundingClientRect();
557
+ relativeCoords = {
558
+ top: coords.bottom - rect.top + 5,
559
+ left: coords.left - rect.left,
560
+ bottom: coords.bottom - rect.top,
561
+ right: coords.right - rect.left
562
+ };
563
+ }
564
+ }
565
+ opts.onMatch?.({
566
+ match: slashMatch,
567
+ query: slashMatch[1] || "",
568
+ from: matchFrom,
569
+ to: matchTo,
570
+ coords: relativeCoords
571
+ });
572
+ } else {
573
+ opts.onClear?.();
574
+ }
575
+ }
576
+ };
577
+ }
578
+ })
579
+ ];
580
+ }
581
+ });
582
+
583
+ // src/extensions/template-suggestions.ts
584
+ import { Extension as Extension2 } from "@tiptap/core";
585
+ import Suggestion from "@tiptap/suggestion";
586
+ var TemplateSuggestions = Extension2.create({
587
+ name: "templateSuggestions",
588
+ addOptions() {
589
+ return {
590
+ templates: [],
591
+ char: "{{",
592
+ onSuggestion: void 0
593
+ };
594
+ },
595
+ addProseMirrorPlugins() {
596
+ const opts = this.options;
597
+ const suggestionConfig = {
598
+ char: opts.char || "{{",
599
+ items: ({ query }) => {
600
+ const lower = query.toLowerCase();
601
+ return (opts.templates || []).filter(
602
+ (t) => t.name.toLowerCase().includes(lower)
603
+ );
604
+ },
605
+ command: ({ editor, range, props }) => {
606
+ editor.chain().focus().deleteRange(range).insertContent(`{{${props.name}}}`).run();
607
+ },
608
+ render: () => {
609
+ return {
610
+ onStart: (props) => {
611
+ opts.onSuggestion?.(props);
612
+ },
613
+ onUpdate: (props) => {
614
+ opts.onSuggestion?.(props);
615
+ },
616
+ onExit: () => {
617
+ opts.onSuggestion?.({
618
+ query: "",
619
+ range: { from: 0, to: 0 },
620
+ items: [],
621
+ command: () => {
622
+ }
623
+ });
624
+ }
625
+ };
626
+ }
627
+ };
628
+ return [
629
+ Suggestion({
630
+ editor: this.editor,
631
+ ...suggestionConfig
632
+ })
633
+ ];
634
+ }
635
+ });
636
+
637
+ // src/extensions/loading-node.ts
638
+ import { Node, mergeAttributes } from "@tiptap/core";
639
+ var LoadingNode = Node.create({
640
+ name: "loadingNode",
641
+ group: "inline",
642
+ inline: true,
643
+ selectable: true,
644
+ atom: true,
645
+ addAttributes() {
646
+ return {
647
+ id: {
648
+ default: null,
649
+ parseHTML: (element) => element.getAttribute("data-id"),
650
+ renderHTML: (attributes) => {
651
+ if (!attributes.id) return {};
652
+ return { "data-id": attributes.id };
653
+ }
654
+ }
655
+ };
656
+ },
657
+ parseHTML() {
658
+ return [
659
+ {
660
+ tag: 'span[data-type="loading"]'
661
+ }
662
+ ];
663
+ },
664
+ renderHTML({ HTMLAttributes }) {
665
+ return [
666
+ "span",
667
+ mergeAttributes(HTMLAttributes, {
668
+ "data-type": "loading",
669
+ class: "inline-flex items-center px-1.5 py-0.5 text-xs text-muted-foreground animate-pulse"
670
+ }),
671
+ "\u23F3"
672
+ ];
673
+ }
674
+ });
675
+
676
+ // src/extensions/SmilieReplacer.ts
677
+ import { Extension as Extension3, textInputRule } from "@tiptap/core";
678
+ var SmilieReplacer = Extension3.create({
679
+ name: "smilieReplacer",
680
+ addInputRules() {
681
+ return [
682
+ textInputRule({ find: /-___- $/, replace: "\u{1F611} " }),
683
+ textInputRule({ find: /:'-\) $/, replace: "\u{1F602} " }),
684
+ textInputRule({ find: /':-\) $/, replace: "\u{1F605} " }),
685
+ textInputRule({ find: /':-D $/, replace: "\u{1F605} " }),
686
+ textInputRule({ find: />:-\) $/, replace: "\u{1F606} " }),
687
+ textInputRule({ find: /-__- $/, replace: "\u{1F611} " }),
688
+ textInputRule({ find: /':-\( $/, replace: "\u{1F613} " }),
689
+ textInputRule({ find: /:'-\( $/, replace: "\u{1F622} " }),
690
+ textInputRule({ find: />:-\( $/, replace: "\u{1F620} " }),
691
+ textInputRule({ find: /O:-\) $/, replace: "\u{1F607} " }),
692
+ textInputRule({ find: /:'\) $/, replace: "\u{1F602} " }),
693
+ textInputRule({ find: /:-D $/, replace: "\u{1F603} " }),
694
+ textInputRule({ find: /':\) $/, replace: "\u{1F605} " }),
695
+ textInputRule({ find: /;-\) $/, replace: "\u{1F609} " }),
696
+ textInputRule({ find: /B-\) $/, replace: "\u{1F60E} " }),
697
+ textInputRule({ find: /:-\* $/, replace: "\u{1F618} " }),
698
+ textInputRule({ find: /:-\) $/, replace: "\u{1F642} " }),
699
+ textInputRule({ find: /-_- $/, replace: "\u{1F611} " }),
700
+ textInputRule({ find: /:-O $/, replace: "\u{1F62E} " }),
701
+ textInputRule({ find: /:-P $/, replace: "\u{1F61B} " }),
702
+ textInputRule({ find: /:-p $/, replace: "\u{1F61B} " }),
703
+ textInputRule({ find: /:-\/ $/, replace: "\u{1F615} " }),
704
+ textInputRule({ find: /:-\( $/, replace: "\u{1F61E} " }),
705
+ textInputRule({ find: /:'\( $/, replace: "\u{1F622} " }),
706
+ textInputRule({ find: /:D $/, replace: "\u{1F603} " }),
707
+ textInputRule({ find: /=D $/, replace: "\u{1F603} " }),
708
+ textInputRule({ find: /;\) $/, replace: "\u{1F609} " }),
709
+ textInputRule({ find: /B\) $/, replace: "\u{1F60E} " }),
710
+ textInputRule({ find: /:\) $/, replace: "\u{1F642} " }),
711
+ textInputRule({ find: /=\) $/, replace: "\u{1F642} " }),
712
+ textInputRule({ find: /:O $/, replace: "\u{1F62E} " }),
713
+ textInputRule({ find: /:P $/, replace: "\u{1F61B} " }),
714
+ textInputRule({ find: /:p $/, replace: "\u{1F61B} " }),
715
+ textInputRule({ find: /:\/ $/, replace: "\u{1F615} " }),
716
+ textInputRule({ find: /:\( $/, replace: "\u{1F61E} " }),
717
+ textInputRule({ find: /<3 $/, replace: "\u2764\uFE0F " }),
718
+ textInputRule({ find: /<\/3 $/, replace: "\u{1F494} " }),
719
+ textInputRule({ find: /\/shrug $/, replace: "\xAF\\_(\u30C4)_/\xAF " })
720
+ ];
721
+ }
722
+ });
723
+
724
+ // src/extensions/ColorHighlighter.ts
725
+ import { Extension as Extension4 } from "@tiptap/core";
726
+ import { Plugin as Plugin3 } from "@tiptap/pm/state";
727
+ import { Decoration as Decoration2, DecorationSet as DecorationSet2 } from "@tiptap/pm/view";
728
+ function findHexColors(doc) {
729
+ const hexColorRegex = /(#[0-9a-fA-F]{3,8})\b/g;
730
+ const decorations = [];
731
+ doc.descendants((node, position) => {
732
+ if (!node.text) return;
733
+ let match;
734
+ while ((match = hexColorRegex.exec(node.text)) !== null) {
735
+ const color = match[0];
736
+ const from = position + match.index;
737
+ const to = from + color.length;
738
+ decorations.push(
739
+ Decoration2.inline(from, to, {
740
+ class: "color-highlight px-1 py-0.5 rounded text-xs font-mono border",
741
+ style: `--color: ${color}; background-color: ${color}20; border-color: ${color}; color: ${color};`
742
+ })
743
+ );
744
+ }
745
+ });
746
+ return DecorationSet2.create(doc, decorations);
747
+ }
748
+ var ColorHighlighter = Extension4.create({
749
+ name: "colorHighlighter",
750
+ addProseMirrorPlugins() {
751
+ return [
752
+ new Plugin3({
753
+ state: {
754
+ init(_, { doc }) {
755
+ return findHexColors(doc);
756
+ },
757
+ apply(transaction, oldState) {
758
+ return transaction.docChanged ? findHexColors(transaction.doc) : oldState;
759
+ }
760
+ },
761
+ props: {
762
+ decorations(state) {
763
+ return this.getState(state);
764
+ }
765
+ }
766
+ })
767
+ ];
768
+ }
769
+ });
770
+
771
+ // src/extensions/FontSize.ts
772
+ import { Extension as Extension5 } from "@tiptap/core";
773
+ import "@tiptap/extension-text-style";
774
+ var FontSize = Extension5.create({
775
+ name: "fontSize",
776
+ addOptions() {
777
+ return {
778
+ types: ["textStyle"]
779
+ };
780
+ },
781
+ addGlobalAttributes() {
782
+ return [
783
+ {
784
+ types: this.options.types,
785
+ attributes: {
786
+ fontSize: {
787
+ default: null,
788
+ parseHTML: (element) => element.style.fontSize.replace(/['"]+/g, ""),
789
+ renderHTML: (attributes) => {
790
+ if (!attributes.fontSize) {
791
+ return {};
792
+ }
793
+ return {
794
+ style: `font-size: ${attributes.fontSize}`
795
+ };
796
+ }
797
+ }
798
+ }
799
+ }
800
+ ];
801
+ },
802
+ addCommands() {
803
+ return {
804
+ setFontSize: (fontSize) => ({ chain }) => chain().setMark("textStyle", { fontSize }).run(),
805
+ unsetFontSize: () => ({ chain }) => chain().setMark("textStyle", { fontSize: null }).removeEmptyTextStyle().run()
806
+ };
807
+ }
808
+ });
809
+
810
+ // src/extensions/rich-text-preset.ts
811
+ import StarterKit from "@tiptap/starter-kit";
812
+ import Color from "@tiptap/extension-color";
813
+ import Highlight from "@tiptap/extension-highlight";
814
+ import Link from "@tiptap/extension-link";
815
+ import TaskList from "@tiptap/extension-task-list";
816
+ import TaskItem from "@tiptap/extension-task-item";
817
+ import TextAlign from "@tiptap/extension-text-align";
818
+ import TextStyle from "@tiptap/extension-text-style";
819
+ import Typography from "@tiptap/extension-typography";
820
+ import Underline from "@tiptap/extension-underline";
821
+ import Placeholder from "@tiptap/extension-placeholder";
822
+ import CharacterCount from "@tiptap/extension-character-count";
823
+ function createRichTextPreset(options = {}) {
824
+ const {
825
+ placeholder = "Start typing...",
826
+ characterLimit,
827
+ openLinksOnClick = false,
828
+ enableSmilies = true,
829
+ enableColorHighlighter = true,
830
+ headingLevels = [1, 2, 3, 4]
831
+ } = options;
832
+ const extensions = [
833
+ StarterKit.configure({
834
+ orderedList: {
835
+ HTMLAttributes: {
836
+ class: "list-decimal pl-4"
837
+ }
838
+ },
839
+ bulletList: {
840
+ HTMLAttributes: {
841
+ class: "list-disc pl-4"
842
+ }
843
+ },
844
+ heading: {
845
+ levels: headingLevels,
846
+ HTMLAttributes: {
847
+ class: "font-bold tracking-tight"
848
+ }
849
+ }
850
+ }),
851
+ TextStyle,
852
+ Color,
853
+ Highlight.configure({ multicolor: true }),
854
+ Underline,
855
+ Typography,
856
+ TextAlign.configure({
857
+ types: ["heading", "paragraph"]
858
+ }),
859
+ Link.configure({
860
+ openOnClick: openLinksOnClick,
861
+ autolink: true,
862
+ defaultProtocol: "https",
863
+ HTMLAttributes: {
864
+ target: "_blank",
865
+ rel: "noopener noreferrer",
866
+ class: "text-blue-500 underline underline-offset-2"
867
+ }
868
+ }),
869
+ TaskList,
870
+ TaskItem.configure({
871
+ nested: true
872
+ }),
873
+ FontSize,
874
+ Placeholder.configure({
875
+ emptyEditorClass: "is-empty",
876
+ placeholder: typeof placeholder === "function" ? placeholder : () => placeholder
877
+ })
878
+ ];
879
+ if (characterLimit) {
880
+ extensions.push(
881
+ CharacterCount.configure({
882
+ limit: characterLimit
883
+ })
884
+ );
885
+ }
886
+ if (enableSmilies) {
887
+ extensions.push(SmilieReplacer);
888
+ }
889
+ if (enableColorHighlighter) {
890
+ extensions.push(ColorHighlighter);
891
+ }
892
+ return extensions;
893
+ }
894
+
895
+ // src/serializers/plain-text.ts
896
+ function escapeHtml(text) {
897
+ if (!text) return "";
898
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
899
+ }
900
+ function plainTextToTipTapHtml(text) {
901
+ if (!text) return "<p></p>";
902
+ if (/<p[\s>]/i.test(text)) {
903
+ return text;
904
+ }
905
+ return text.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n").map((line) => `<p>${escapeHtml(line)}</p>`).join("");
906
+ }
907
+ function htmlToPlainText(html) {
908
+ if (!html) return "";
909
+ if (typeof document !== "undefined") {
910
+ const tempDiv = document.createElement("div");
911
+ tempDiv.innerHTML = html;
912
+ tempDiv.querySelectorAll("br.ProseMirror-trailingBreak").forEach((br) => br.remove());
913
+ tempDiv.querySelectorAll("br").forEach((br) => br.replaceWith("\n"));
914
+ const paragraphs = tempDiv.querySelectorAll("p, div, li, h1, h2, h3, h4, h5, h6");
915
+ if (paragraphs.length > 0) {
916
+ const textParts = [];
917
+ paragraphs.forEach((p) => {
918
+ textParts.push(p.textContent || "");
919
+ });
920
+ return textParts.join("\n");
921
+ }
922
+ return tempDiv.textContent || "";
923
+ }
924
+ return html.replace(/<br\s*\/?>/gi, "\n").replace(/<\/p>/gi, "\n").replace(/<\/div>/gi, "\n").replace(/<\/li>/gi, "\n").replace(/<[^>]+>/g, "").replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#039;/g, "'").trim();
925
+ }
926
+ function getEditorText(editor) {
927
+ if (!editor) return "";
928
+ const html = typeof editor.getHTML === "function" ? editor.getHTML() : "";
929
+ if (html) {
930
+ return htmlToPlainText(html);
931
+ }
932
+ if (typeof editor.getText === "function") {
933
+ try {
934
+ return editor.getText({ blockSeparator: "\n" });
935
+ } catch {
936
+ return editor.getText();
937
+ }
938
+ }
939
+ return "";
940
+ }
941
+
942
+ // src/controller.ts
943
+ import { Editor } from "@tiptap/core";
944
+ import { Slice, Fragment, Node as ProsemirrorNode } from "@tiptap/pm/model";
945
+ var EditorController = class {
946
+ editor;
947
+ plainTextMode;
948
+ onPlainTextChange;
949
+ onTokensChange;
950
+ onSelectionChange;
951
+ constructor(options = {}) {
952
+ const {
953
+ element,
954
+ content,
955
+ plainTextMode = false,
956
+ extensions = [],
957
+ onPlainTextChange,
958
+ onTokensChange,
959
+ onSelectionChange,
960
+ ...editorOptions
961
+ } = options;
962
+ this.plainTextMode = plainTextMode;
963
+ this.onPlainTextChange = onPlainTextChange;
964
+ this.onTokensChange = onTokensChange;
965
+ this.onSelectionChange = onSelectionChange;
966
+ const initialContent = plainTextMode && typeof content === "string" ? plainTextToTipTapHtml(content) : content;
967
+ this.editor = new Editor({
968
+ element: element || void 0,
969
+ content: initialContent,
970
+ extensions,
971
+ ...editorOptions,
972
+ onUpdate: (props) => {
973
+ editorOptions.onUpdate?.(props);
974
+ this.handleUpdate();
975
+ },
976
+ onSelectionUpdate: (props) => {
977
+ editorOptions.onSelectionUpdate?.(props);
978
+ this.handleSelectionUpdate();
979
+ }
980
+ });
981
+ if (plainTextMode) {
982
+ this.enforcePlainTextClipboard();
983
+ }
984
+ }
985
+ enforcePlainTextClipboard() {
986
+ this.editor.setOptions({
987
+ editorProps: {
988
+ ...this.editor.options.editorProps,
989
+ clipboardTextParser: (text, context, _plain, view) => {
990
+ const schema = context?.doc?.type?.schema || context?.schema || view?.state?.schema || this.editor.schema;
991
+ if (!schema) return Slice.empty;
992
+ const blocks = text.replace(/\r\n?/g, "\n").split("\n");
993
+ const nodes = [];
994
+ blocks.forEach((line) => {
995
+ const nodeJson = { type: "paragraph" };
996
+ if (line.length > 0) {
997
+ nodeJson.content = [{ type: "text", text: line }];
998
+ }
999
+ try {
1000
+ const node = ProsemirrorNode.fromJSON(schema, nodeJson);
1001
+ nodes.push(node);
1002
+ } catch {
1003
+ }
1004
+ });
1005
+ return Slice.maxOpen(Fragment.fromArray(nodes));
1006
+ }
1007
+ }
1008
+ });
1009
+ }
1010
+ handleUpdate() {
1011
+ if (this.plainTextMode || this.onPlainTextChange || this.onTokensChange) {
1012
+ const text = this.getPlainText();
1013
+ this.onPlainTextChange?.(text);
1014
+ if (this.onTokensChange) {
1015
+ const tokens = tokenizePrompt(text);
1016
+ this.onTokensChange(tokens);
1017
+ }
1018
+ }
1019
+ }
1020
+ handleSelectionUpdate() {
1021
+ if (this.onSelectionChange) {
1022
+ const { from, to } = this.editor.state.selection;
1023
+ this.onSelectionChange({ from, to });
1024
+ }
1025
+ }
1026
+ getPlainText() {
1027
+ return getEditorText(this.editor);
1028
+ }
1029
+ setPlainText(text, emitUpdate = true) {
1030
+ const html = plainTextToTipTapHtml(text);
1031
+ this.editor.commands.setContent(html, emitUpdate);
1032
+ }
1033
+ insertText(text) {
1034
+ this.editor.commands.insertContent(text);
1035
+ }
1036
+ insertTextAt(pos, text) {
1037
+ this.editor.chain().focus().insertContentAt(pos, text).run();
1038
+ }
1039
+ replaceRange(from, to, text) {
1040
+ this.editor.chain().focus().deleteRange({ from, to }).insertContentAt(from, text).run();
1041
+ }
1042
+ destroy() {
1043
+ this.editor.destroy();
1044
+ }
1045
+ };
1046
+ function createEditor(options = {}) {
1047
+ return new EditorController(options);
1048
+ }
1049
+ export {
1050
+ ColorHighlighter,
1051
+ EditorController,
1052
+ FontSize,
1053
+ GradientText,
1054
+ INSTRUCTION_REGEX,
1055
+ LoadingNode,
1056
+ SlashCommands,
1057
+ SmilieReplacer,
1058
+ TEMPLATE_REGEX,
1059
+ TemplateSuggestions,
1060
+ VARIABLE_REGEX,
1061
+ createEditor,
1062
+ createRichTextPreset,
1063
+ escapeHtml,
1064
+ extractInstructionNames,
1065
+ extractTemplateNames,
1066
+ extractVariableNames,
1067
+ findHexColors,
1068
+ getEditorText,
1069
+ getLatestVersion,
1070
+ htmlToPlainText,
1071
+ instructionRegex,
1072
+ mapRawOffsetToResolved,
1073
+ mapResolvedOffsetToRaw,
1074
+ plainTextToTipTapHtml,
1075
+ resolveTemplates,
1076
+ resolveTemplatesWithMapping,
1077
+ resolveVariables,
1078
+ templateRegex,
1079
+ tokenizePrompt,
1080
+ variableRegex
1081
+ };
1082
+ //# sourceMappingURL=index.js.map