@alpaca-editor/core 1.0.3818 → 1.0.3822

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.
@@ -0,0 +1,300 @@
1
+ import {
2
+ useEditContext,
3
+ useModifiedFieldsContext,
4
+ } from "../client/editContext";
5
+ import { findFieldElement } from "../utils";
6
+ import { SuggestedEdit } from "../../types";
7
+ import { useState } from "react";
8
+ import { useEffect } from "react";
9
+ import { classNames } from "primereact/utils";
10
+ import { UserRoundPen } from "lucide-react";
11
+ import * as DiffLib from "diff";
12
+
13
+ export function SuggestionHighlighting({
14
+ suggestion,
15
+ scale,
16
+ iframe,
17
+ }: {
18
+ suggestion: SuggestedEdit;
19
+ scale: number;
20
+ iframe: HTMLIFrameElement;
21
+ }) {
22
+ const editContext = useEditContext();
23
+ const modifiedFields = useModifiedFieldsContext();
24
+ const [ranges, setRanges] = useState<Array<[number, number]>>([]);
25
+ const [textContent, setTextContent] = useState<string>("");
26
+
27
+ useEffect(() => {
28
+ const findRanges = async () => {
29
+ if (!editContext) return;
30
+
31
+ const field = await editContext.itemsRepository.getField({
32
+ item: {
33
+ id: suggestion.itemId,
34
+ language: suggestion.mainItemLanguage,
35
+ version: suggestion.mainItemVersion,
36
+ },
37
+ fieldId: suggestion.fieldId,
38
+ });
39
+
40
+ const modifiedField = modifiedFields?.modifiedFields.find(
41
+ (x) =>
42
+ x.fieldId === field?.id &&
43
+ x.item.id === suggestion.itemId &&
44
+ x.item.language === suggestion.mainItemLanguage &&
45
+ x.item.version === suggestion.mainItemVersion,
46
+ );
47
+
48
+ // Calculate the actual differences between oldValue and newValue
49
+ const oldValue = suggestion.oldValue || field?.rawValue || "";
50
+ const newValue = modifiedField?.value || suggestion.newValue || "";
51
+
52
+ // If values are identical, no need to highlight
53
+ if (oldValue === newValue) {
54
+ setRanges([]);
55
+ return;
56
+ }
57
+
58
+ // Save oldValue for use in the component
59
+ setTextContent(oldValue);
60
+
61
+ // Use the diff library to find the changed parts - using diffChars for more precise matching
62
+ const diffResult = DiffLib.diffChars(oldValue, newValue);
63
+
64
+ const changeRanges: Array<[number, number]> = [];
65
+ let positionInOld = 0;
66
+
67
+ // Process the diff result to find all change ranges
68
+ for (const part of diffResult) {
69
+ if (part.removed) {
70
+ // If a part is removed, highlight it in the original text
71
+ changeRanges.push([positionInOld, positionInOld + part.value.length]);
72
+ positionInOld += part.value.length;
73
+ } else if (part.added) {
74
+ // For added parts, mark the insertion point
75
+ if (changeRanges.length > 0) {
76
+ const lastRange = changeRanges[changeRanges.length - 1];
77
+ if (lastRange && lastRange[1] === positionInOld) {
78
+ // If this addition comes right after a removal, the previous range already covers the position
79
+ continue;
80
+ }
81
+ }
82
+ // Mark the insertion point for new content
83
+ changeRanges.push([positionInOld, positionInOld]);
84
+ } else {
85
+ // Unchanged part, just advance the position
86
+ positionInOld += part.value.length;
87
+ }
88
+ }
89
+
90
+ // Merge adjacent or overlapping ranges
91
+ const mergedRanges: Array<[number, number]> = [];
92
+
93
+ if (changeRanges.length > 0) {
94
+ changeRanges.sort((a, b) => a[0] - b[0]);
95
+
96
+ // Start with the first range
97
+ const firstRange = changeRanges[0];
98
+ if (!firstRange) {
99
+ setRanges([]);
100
+ return;
101
+ }
102
+
103
+ let currentRange: [number, number] = [...firstRange];
104
+
105
+ // Process the rest of the ranges
106
+ for (let i = 1; i < changeRanges.length; i++) {
107
+ const nextRange = changeRanges[i];
108
+
109
+ // Skip undefined ranges
110
+ if (!nextRange) continue;
111
+
112
+ // If the next range starts very close to the end of the current range, merge them
113
+ if (nextRange[0] <= currentRange[1] + 3) {
114
+ // Allow slightly larger gaps (3 chars) for better highlighting
115
+ // Extend the current range
116
+ currentRange[1] = Math.max(currentRange[1], nextRange[1]);
117
+ } else {
118
+ // Save the current range and start a new one
119
+ mergedRanges.push([currentRange[0], currentRange[1]]);
120
+ currentRange = [...nextRange];
121
+ }
122
+ }
123
+
124
+ // Add the last range
125
+ mergedRanges.push([currentRange[0], currentRange[1]]);
126
+ }
127
+
128
+ // Set ranges to highlight the changed parts
129
+ setRanges(mergedRanges);
130
+ };
131
+
132
+ findRanges();
133
+ }, [editContext, modifiedFields?.modifiedFields, suggestion]);
134
+
135
+ if (!editContext) return null;
136
+
137
+ if (!suggestion.fieldId) return null;
138
+
139
+ const fieldElement = findFieldElement(iframe, {
140
+ item: {
141
+ id: suggestion.itemId,
142
+ language: suggestion.mainItemLanguage,
143
+ version: suggestion.mainItemVersion,
144
+ },
145
+ fieldId: suggestion.fieldId,
146
+ });
147
+
148
+ if (!fieldElement) return null;
149
+
150
+ // Process each range and collect all DOM rectangles
151
+ const allRects: Array<DOMRect> = [];
152
+
153
+ ranges.forEach((range) => {
154
+ if (range[0] !== undefined && range[1] !== undefined) {
155
+ // For insertion points (zero-length ranges), expand to include at least one character
156
+ // to make it visible
157
+ const start = range[0];
158
+ const end =
159
+ range[0] === range[1]
160
+ ? Math.min(range[0] + 1, textContent.length)
161
+ : range[1];
162
+
163
+ if (start < end) {
164
+ const startData = getTextNodeAtPosition(fieldElement, start);
165
+ const endData = getTextNodeAtPosition(fieldElement, end);
166
+
167
+ if (startData && endData) {
168
+ try {
169
+ const textRange = document.createRange();
170
+ textRange.setStart(startData.node, startData.offset);
171
+ textRange.setEnd(endData.node, endData.offset);
172
+
173
+ const rangeRects = textRange.getClientRects();
174
+ // Convert DOMRectList to Array
175
+ for (let i = 0; i < rangeRects.length; i++) {
176
+ const rect = rangeRects[i];
177
+ if (rect) {
178
+ allRects.push(rect);
179
+ }
180
+ }
181
+ } catch (e) {
182
+ console.error("Error creating range", e);
183
+ }
184
+ }
185
+ }
186
+ }
187
+ });
188
+
189
+ // If no rects were found, fall back to highlighting the entire field
190
+ if (allRects.length === 0 && ranges.length > 0) {
191
+ const fallbackRect = fieldElement.getBoundingClientRect();
192
+ allRects.push(fallbackRect);
193
+ }
194
+
195
+ const iframeRect = iframe.getBoundingClientRect();
196
+
197
+ return (
198
+ <>
199
+ {allRects.map((rect, index) => (
200
+ <div
201
+ key={index}
202
+ style={{
203
+ position: "absolute",
204
+ top: rect.top * scale,
205
+ left: rect.left * scale,
206
+ width: rect.width * scale,
207
+ height: rect.height * scale,
208
+ pointerEvents: "none",
209
+ }}
210
+ >
211
+ {index === 0 && (
212
+ <div
213
+ className={classNames(
214
+ "pointer-events-auto absolute h-5 w-5 cursor-pointer",
215
+ rect.top * scale < 18 ? "top-0" : "top-[-18px]",
216
+ (rect.left + rect.width) * scale > iframeRect.width - 18
217
+ ? "right-0"
218
+ : "right-[-18px]",
219
+ )}
220
+ onClick={() => {
221
+ editContext.select([suggestion.itemId]);
222
+ editContext.setFocusedField(
223
+ {
224
+ item: {
225
+ id: suggestion.itemId,
226
+ language: suggestion.mainItemLanguage,
227
+ version: suggestion.mainItemVersion,
228
+ },
229
+ fieldId: suggestion.fieldId,
230
+ },
231
+ true,
232
+ );
233
+ }}
234
+ >
235
+ <UserRoundPen
236
+ className="rounded-full bg-emerald-400/70 p-1 text-white"
237
+ size={20}
238
+ />
239
+ </div>
240
+ )}
241
+ {/* <div
242
+ className="bg-emerald-400/30"
243
+ style={{
244
+ width: "100%",
245
+ height: "100%",
246
+ }}
247
+ ></div> */}
248
+ </div>
249
+ ))}
250
+ </>
251
+ );
252
+ }
253
+
254
+ // Improved function to find text node at a given character position
255
+ function getTextNodeAtPosition(
256
+ root: Node,
257
+ targetOffset: number,
258
+ ): { node: Text; offset: number } | null {
259
+ // Handle edge cases
260
+ if (targetOffset < 0) return null;
261
+
262
+ // Get all text nodes in order
263
+ const textNodes: Text[] = [];
264
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, null);
265
+
266
+ let node: Text | null;
267
+ while ((node = walker.nextNode() as Text | null)) {
268
+ if (node) textNodes.push(node);
269
+ }
270
+
271
+ let currentOffset = 0;
272
+ // Walk through all text nodes to find the one containing our target position
273
+ for (const node of textNodes) {
274
+ const nodeLength = node.textContent?.length || 0;
275
+
276
+ // If this node contains our target position
277
+ if (currentOffset + nodeLength >= targetOffset) {
278
+ return {
279
+ node: node,
280
+ offset: targetOffset - currentOffset,
281
+ };
282
+ }
283
+
284
+ currentOffset += nodeLength;
285
+ }
286
+
287
+ // If we've gone through all nodes and haven't found the position
288
+ // Return the last position in the last text node
289
+ if (textNodes.length > 0) {
290
+ const lastNode = textNodes[textNodes.length - 1];
291
+ if (lastNode) {
292
+ return {
293
+ node: lastNode,
294
+ offset: lastNode.textContent?.length || 0,
295
+ };
296
+ }
297
+ }
298
+
299
+ return null;
300
+ }
@@ -5,7 +5,14 @@ import { SuggestedEditComponent } from "./SuggestedEdit";
5
5
  import { Comment as CommentType, SuggestedEdit } from "../../types";
6
6
  import { SimpleToolbar } from "../ui/SimpleToolbar";
7
7
  import { SimpleIconButton } from "../ui/SimpleIconButton";
8
- import { FileDiff, MessageCircle, SquarePen } from "lucide-react";
8
+ import {
9
+ FileDiff,
10
+ MessageCircle,
11
+ SquarePen,
12
+ CheckCircle,
13
+ CheckCircle2,
14
+ Eye,
15
+ } from "lucide-react";
9
16
 
10
17
  // Define a union type for feedback items:
11
18
  export type FeedbackItem = CommentType | SuggestedEdit;
@@ -13,13 +20,21 @@ export type FeedbackItem = CommentType | SuggestedEdit;
13
20
  export function Comments() {
14
21
  const editContext = useEditContext();
15
22
  const [feedbackItems, setFeedbackItems] = useState<FeedbackItem[]>([]);
23
+ const [hideAppliedSuggestions, setHideAppliedSuggestions] =
24
+ useState<boolean>(true);
16
25
 
17
26
  useEffect(() => {
18
27
  // Retrieve your list of comments (and ensure there's an array of suggested edits,
19
28
  // for instance from your editContext)
20
29
  const comments: CommentType[] = editContext?.comments || [];
21
30
  const suggestedEdits: SuggestedEdit[] = editContext?.suggestedEdits || [];
22
- const combined: FeedbackItem[] = [...comments, ...suggestedEdits];
31
+
32
+ // Filter out applied suggestions if hideAppliedSuggestions is true
33
+ const filteredSuggestedEdits = hideAppliedSuggestions
34
+ ? suggestedEdits.filter((edit) => edit.status !== "Applied")
35
+ : suggestedEdits;
36
+
37
+ const combined: FeedbackItem[] = [...comments, ...filteredSuggestedEdits];
23
38
 
24
39
  // Sort by creation date. Adjust the comparison as needed if the date properties differ.
25
40
  combined.sort(
@@ -29,7 +44,7 @@ export function Comments() {
29
44
  );
30
45
 
31
46
  setFeedbackItems(combined);
32
- }, [editContext]);
47
+ }, [editContext, hideAppliedSuggestions]);
33
48
 
34
49
  return (
35
50
  <div className="flex h-full flex-col">
@@ -44,7 +59,7 @@ export function Comments() {
44
59
  />
45
60
  <SimpleIconButton
46
61
  selected={editContext?.showComments}
47
- icon={<MessageCircle size={16} className="p-0.5" />}
62
+ icon={<Eye size={16} className="p-0.5" />}
48
63
  label="Show Comments"
49
64
  onClick={() => {
50
65
  editContext?.setShowComments((x) => !x);
@@ -66,6 +81,24 @@ export function Comments() {
66
81
  editContext?.setShowSuggestedEditsDiff((x) => !x);
67
82
  }}
68
83
  />
84
+ <SimpleIconButton
85
+ selected={hideAppliedSuggestions}
86
+ icon={
87
+ hideAppliedSuggestions ? (
88
+ <CheckCircle2 size={16} className="p-0.5" />
89
+ ) : (
90
+ <CheckCircle size={16} className="p-0.5" />
91
+ )
92
+ }
93
+ label={
94
+ hideAppliedSuggestions
95
+ ? "Show Applied Suggestions"
96
+ : "Hide Applied Suggestions"
97
+ }
98
+ onClick={() => {
99
+ setHideAppliedSuggestions((x) => !x);
100
+ }}
101
+ />
69
102
  </SimpleToolbar>
70
103
 
71
104
  <div className="flex-1 overflow-auto">
@@ -2,7 +2,7 @@
2
2
 
3
3
  import { useEditContext, useEditContextRef } from "../client/editContext";
4
4
 
5
- import { useEffect, useRef, useState } from "react";
5
+ import { useCallback, useEffect, useRef, useState } from "react";
6
6
 
7
7
  import { confirmDialog } from "primereact/confirmdialog";
8
8
  import { getComponentCommands } from "../commands/componentCommands";
@@ -252,26 +252,29 @@ export function ComponentTree({}) {
252
252
  setNodeDictionary(dict);
253
253
  }, [page]);
254
254
 
255
- const handleTreeSelection = (key: string, event: React.MouseEvent) => {
256
- let newKeys = [key];
257
- if (event.ctrlKey) {
258
- if (selectedKeys.includes(key)) {
259
- newKeys = selectedKeys.filter((x) => x !== key);
260
- } else {
261
- newKeys = [...selectedKeys, key];
255
+ const handleTreeSelection = useCallback(
256
+ (key: string, event: React.MouseEvent) => {
257
+ let newKeys = [key];
258
+ if (event.ctrlKey) {
259
+ if (selectedKeys.includes(key)) {
260
+ newKeys = selectedKeys.filter((x) => x !== key);
261
+ } else {
262
+ newKeys = [...selectedKeys, key];
263
+ }
262
264
  }
263
- }
264
265
 
265
- const selectedComponentIds = newKeys
266
- .filter((key) => nodeDictionary[key])
267
- .map((key) => nodeDictionary[key]!.componentId!);
266
+ const selectedComponentIds = newKeys
267
+ .filter((key) => nodeDictionary[key])
268
+ .map((key) => nodeDictionary[key]!.componentId!);
268
269
 
269
- editContextRef.current?.select(selectedComponentIds);
270
+ editContextRef.current?.select(selectedComponentIds);
270
271
 
271
- if (selectedComponentIds.length === 1) {
272
- editContextRef.current?.setScrollIntoView(selectedComponentIds[0]);
273
- }
274
- };
272
+ if (selectedComponentIds.length === 1) {
273
+ editContextRef.current?.setScrollIntoView(selectedComponentIds[0]);
274
+ }
275
+ },
276
+ [selectedKeys, nodeDictionary, editContextRef],
277
+ );
275
278
 
276
279
  // Handle tree context menu
277
280
  const handleTreeContextMenu = (
@@ -333,28 +336,34 @@ export function ComponentTree({}) {
333
336
 
334
337
  // Convert selected keys for PerfectTree
335
338
  const selectedItems = selectedKeys;
339
+ const handleCollapseItem = useCallback(
340
+ (key: string) => {
341
+ // First, get the node we're collapsing
342
+ const nodeToCollapse = nodeDictionary[key];
336
343
 
337
- // Handle expanding nodes
338
- const handleToggle = (key: string) => {
339
- if (expandedKeys.includes(key)) {
340
- handleCollapseItem(key);
341
- } else {
342
- const newExpandedKeys = [...expandedKeys];
343
- newExpandedKeys.push(key);
344
- setExpandedKeys(newExpandedKeys);
345
- }
346
- };
344
+ // Create a new array for expanded keys
345
+ const newExpandedKeys = [...expandedKeys].filter((x) => x !== key);
347
346
 
348
- // Handle collapsing nodes
349
- const handleCollapseItem = (key: string) => {
350
- // First, get the node we're collapsing
351
- const nodeToCollapse = nodeDictionary[key];
347
+ setExpandedKeys(newExpandedKeys);
348
+ },
349
+ [expandedKeys, nodeDictionary],
350
+ );
352
351
 
353
- // Create a new array for expanded keys
354
- const newExpandedKeys = [...expandedKeys].filter((x) => x !== key);
352
+ // Handle expanding nodes
353
+ const handleToggle = useCallback(
354
+ (key: string) => {
355
+ if (expandedKeys.includes(key)) {
356
+ handleCollapseItem(key);
357
+ } else {
358
+ const newExpandedKeys = [...expandedKeys];
359
+ newExpandedKeys.push(key);
360
+ setExpandedKeys(newExpandedKeys);
361
+ }
362
+ },
363
+ [expandedKeys, handleCollapseItem],
364
+ );
355
365
 
356
- setExpandedKeys(newExpandedKeys);
357
- };
366
+ // Handle collapsing nodes
358
367
 
359
368
  const getPlaceholder = (node: CustomTreeNode | null): Placeholder | null => {
360
369
  if (!node) return null;
@@ -419,18 +428,19 @@ export function ComponentTree({}) {
419
428
 
420
429
  // Only create drag object for components with datasourceItem
421
430
  if (!component?.datasourceItem) return;
422
-
423
- editContext!.dragStart({
424
- type: "component",
425
- typeId: component.typeId,
426
- templateId: component.datasourceItem?.templateId,
427
- name: component.name,
428
- component: {
429
- id: component.id,
430
- language: editContext!.page!.item.language,
431
- version: editContext!.page!.item.version,
432
- },
433
- });
431
+ setTimeout(() => {
432
+ editContext!.dragStart({
433
+ type: "component",
434
+ typeId: component.typeId,
435
+ templateId: component.datasourceItem?.templateId,
436
+ name: component.name,
437
+ component: {
438
+ id: component.id,
439
+ language: editContext!.page!.item.language,
440
+ version: editContext!.page!.item.version,
441
+ },
442
+ });
443
+ }, 1);
434
444
  }}
435
445
  onDragEnd={(event) => {
436
446
  editContext!.dragEnd();