/
helpers.ts
429 lines (405 loc) · 12.9 KB
/
helpers.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
import {flatten, isEqual, orderBy} from 'lodash'
import {
ArraySchemaType,
isPortableTextSpan,
isPortableTextTextBlock,
ObjectField,
ObjectSchemaType,
PortableTextBlock,
PortableTextChild,
PortableTextObject,
PortableTextTextBlock,
SchemaType,
SpanSchemaType,
} from '@sanity/types'
import {
diff_match_patch as DiffMatchPatch,
DIFF_DELETE,
DIFF_EQUAL,
DIFF_INSERT,
} from 'diff-match-patch'
import {
ArrayDiff,
DiffComponent,
DiffComponentOptions,
ObjectDiff,
StringDiffSegment,
} from '../../../types'
import * as TextSymbols from './symbols'
import {InlineSymbolMap, MarkSymbolMap, PortableTextDiff} from './types'
const dmp = new DiffMatchPatch()
export const UNKNOWN_TYPE_NAME = '_UNKOWN_TYPE_'
export function hasPTMemberType(schemaType: ArraySchemaType): boolean {
return schemaType.of.some(isPTSchemaType)
}
const startMarkSymbols = TextSymbols.DECORATOR_SYMBOLS.map((set) => set[0]).concat(
TextSymbols.ANNOTATION_SYMBOLS.map((set) => set[0])
)
const endMarkSymbols = TextSymbols.DECORATOR_SYMBOLS.map((set) => set[1]).concat(
TextSymbols.ANNOTATION_SYMBOLS.map((set) => set[1])
)
const allSymbols = startMarkSymbols
.concat(endMarkSymbols)
.concat(TextSymbols.INLINE_SYMBOLS)
.concat(TextSymbols.CHILD_SYMBOL)
.concat(TextSymbols.SEGMENT_START_SYMBOL)
const symbolRegex = new RegExp(`${allSymbols.join('|')}`, 'g')
const segmentRegex = new RegExp(`${allSymbols.join('|')}|\n`, 'g')
interface BlockSchemaType extends ObjectSchemaType {
diffComponent:
| DiffComponent<ObjectDiff<PortableTextBlock>>
| DiffComponentOptions<ObjectDiff<PortableTextBlock>>
}
export function isPTSchemaType(schemaType: SchemaType): schemaType is BlockSchemaType {
return schemaType.jsonType === 'object' && schemaType.name === 'block'
}
export function isHeader(node: PortableTextBlock): boolean {
return (
isPortableTextTextBlock(node) &&
!!node.style &&
['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(node.style)
)
}
export function findChildDiff(diff: ObjectDiff, child: PortableTextChild): ObjectDiff {
const childrenDiff = diff.fields.children as ArrayDiff
return childrenDiff.items
.filter(
(item: any) =>
item.diff.isChanged && (item.diff.toValue === child || item.diff.fromValue === child)
)
.map((item: any) => item.diff)
.map((childDiff: any) => childDiff as ObjectDiff)[0]
}
export function getChildSchemaType(
fields: ObjectField<SchemaType>[],
child: PortableTextChild
): ObjectSchemaType | undefined {
const childrenField = fields.find((f) => f.name === 'children')
const cSchemaType =
(childrenField &&
childrenField.type &&
childrenField.type.jsonType === 'array' &&
(childrenField.type.of.find((type) => type.name === child._type) as ObjectSchemaType)) ||
undefined
return cSchemaType
}
export function getDecorators(spanSchemaType: SpanSchemaType): {title: string; value: string}[] {
if (spanSchemaType.decorators) {
return orderBy(spanSchemaType.decorators, ['value'], ['asc'])
}
return []
}
export function getAnnotations(spanSchemaType: SpanSchemaType): ObjectSchemaType[] {
if (spanSchemaType.annotations) {
return orderBy(spanSchemaType.annotations, ['name'], ['asc'])
}
return []
}
export function isDecorator(name: string, schemaType: SpanSchemaType): boolean {
return getDecorators(schemaType).some((dec) => dec.value === name)
}
export function blockToSymbolizedText(
diff: ObjectDiff,
block: PortableTextTextBlock | undefined,
decoratorMap: MarkSymbolMap,
annotationMap: MarkSymbolMap,
inlineMap: InlineSymbolMap
): string {
if (!block) {
return ''
}
return block.children
.map((child) => {
let returned = isPortableTextSpan(child) ? child.text?.replace(symbolRegex, '') : '' // Make sure symbols aren't in the text already
if (isPortableTextSpan(child)) {
// Attatch stringdiff segments
const spanDiff = findSpanDiffFromChild(diff, child)
const textDiff = spanDiff?.fields.text
if (
textDiff &&
textDiff.toValue === child.text &&
textDiff.type === 'string' &&
textDiff.action !== 'unchanged'
) {
returned = textDiff.segments
.filter((seg) => seg.action !== 'removed')
.map((seg) => seg.text.replace(symbolRegex, ''))
.join(TextSymbols.SEGMENT_START_SYMBOL)
}
if (child.marks) {
child.marks.forEach((mark) => {
const _isDecorator = !!decoratorMap[mark]
if (_isDecorator) {
returned = `${decoratorMap[mark][0]}${returned}${decoratorMap[mark][1]}`
} else if (annotationMap[mark]) {
returned = `${annotationMap[mark][0]}${returned}${annotationMap[mark][1]}`
}
})
}
} else {
returned = inlineMap[child._key]
}
return `${TextSymbols.CHILD_SYMBOL}${returned}`
})
.join('')
}
export function createPortableTextDiff(
diff: ObjectDiff,
schemaType: ObjectSchemaType
): PortableTextDiff {
const displayValue =
diff.action === 'removed'
? (diff.fromValue as PortableTextTextBlock)
: (diff.toValue as PortableTextTextBlock)
const _diff: PortableTextDiff = {
...diff,
origin: diff,
displayValue,
}
if (displayValue) {
const annotationMap: MarkSymbolMap = {}
const decoratorMap: MarkSymbolMap = {}
const inlineMap: InlineSymbolMap = {}
const spanSchemaType = getChildSchemaType(schemaType.fields, {
_key: 'bogus',
_type: 'span',
}) as SpanSchemaType
if (spanSchemaType) {
getDecorators(spanSchemaType).forEach((dec, index) => {
decoratorMap[dec.value] = TextSymbols.DECORATOR_SYMBOLS[index]
})
}
const allMarkDefs = getAllMarkDefs(_diff.origin)
allMarkDefs.forEach((markDef, index) => {
annotationMap[markDef._key] = TextSymbols.ANNOTATION_SYMBOLS[index]
})
const inlines = getInlineObjects(_diff.origin)
inlines.forEach((inline, index) => {
inlineMap[inline._key] = TextSymbols.INLINE_SYMBOLS[index]
})
const fromText = blockToSymbolizedText(
_diff.origin,
_diff.fromValue as PortableTextTextBlock,
decoratorMap,
annotationMap,
inlineMap
)
const toText = blockToSymbolizedText(
_diff.origin,
_diff.toValue as PortableTextTextBlock,
decoratorMap,
annotationMap,
inlineMap
)
const toPseudoValue = {
...displayValue,
children: [
{
_type: 'span',
_key: 'pseudoSpanKey',
text: toText,
marks: [],
},
],
}
const fromPseudoValue = {
displayValue,
children: [
{
_type: 'span',
_key: 'pseudoSpanKey',
text: fromText,
marks: [],
},
],
}
const pseudoDiff = {
origin: diff,
action: 'changed',
type: 'object',
displayValue: toPseudoValue,
fromValue: fromPseudoValue,
toValue: toPseudoValue,
isChanged: true,
fields: {
children: {
action: 'changed',
type: 'array',
isChanged: true,
items: [
{
diff: {
action: 'changed',
type: 'object',
isChanged: true,
fields: {
text: {
type: 'string',
action: 'changed',
isChanged: true,
fromValue: fromText,
toValue: toText,
segments: buildSegments(fromText, toText).map((seg) => ({
...seg,
...(_diff.action !== 'unchanged' && _diff.annotation
? {annotation: _diff.annotation} // Fallback if we can't find a spesific original diff
: {}),
})),
},
},
fromValue: fromPseudoValue.children[0],
toValue: toPseudoValue.children[0],
},
annotation: null,
fromIndex: 0,
toIndex: 0,
hasMoved: false,
},
],
fromValue: fromPseudoValue.children,
toValue: toPseudoValue.children,
},
},
}
return pseudoDiff as PortableTextDiff
}
throw new Error('Can not display this diff')
}
function buildSegments(fromInput: string, toInput: string): StringDiffSegment[] {
const segments: StringDiffSegment[] = []
const dmpDiffs = dmp.diff_main(fromInput, toInput)
dmp.diff_cleanupEfficiency(dmpDiffs)
let fromIdx = 0
let toIdx = 0
for (const [op, text] of dmpDiffs) {
switch (op) {
case DIFF_EQUAL:
segments.push({
type: 'stringSegment',
action: 'unchanged',
text,
})
fromIdx += text.length
toIdx += text.length
break
case DIFF_DELETE:
segments.push({
type: 'stringSegment',
action: 'removed',
text: fromInput.substring(fromIdx, fromIdx + text.length),
annotation: null,
})
fromIdx += text.length
break
case DIFF_INSERT:
segments.push({
type: 'stringSegment',
action: 'added',
text: toInput.substring(toIdx, toIdx + text.length),
annotation: null,
})
toIdx += text.length
break
default:
// Do nothing
}
}
// Clean up so that marks / symbols are treated as an own segment
return flatten(
segments.map((seg) => {
const newSegments: StringDiffSegment[] = []
if (seg.text.length > 1) {
const markMatches = [...seg.text.matchAll(segmentRegex)]
let lastIndex = -1
markMatches.forEach((match) => {
const index = match.index || 0
if (index > lastIndex) {
newSegments.push({...seg, text: seg.text.substring(lastIndex + 1, index)})
newSegments.push({...seg, text: match[0]})
}
if (match === markMatches[markMatches.length - 1]) {
newSegments.push({...seg, text: seg.text.substring(index + 1)})
}
lastIndex = index
})
if (markMatches.length === 0) {
newSegments.push(seg)
}
} else {
newSegments.push(seg)
}
return newSegments
})
)
}
export function getInlineObjects(diff: ObjectDiff): PortableTextObject[] {
const allChildren = [
...(diff.toValue ? diff.toValue.children.filter((cld: any) => cld._type !== 'span') : []),
]
const previousChildren = diff.fromValue
? diff.fromValue.children.filter((cld: any) => cld._type !== 'span')
: []
previousChildren.forEach((oCld: any) => {
if (!allChildren.some((cld) => oCld._key === cld._key)) {
allChildren.push(oCld)
}
})
return orderBy(allChildren, ['_key'], ['asc']) as PortableTextObject[]
}
export function findSpanDiffFromChild(
diff: ObjectDiff,
child: PortableTextChild
): ObjectDiff | undefined {
// Find span in original diff which has a string segment similar to the one from the input
const candidate =
diff.fields.children &&
diff.fields.children.action !== 'unchanged' &&
diff.fields.children.type === 'array' &&
diff.fields.children.items.find(
(item: any) =>
item.diff &&
item.diff.type === 'object' &&
(item.diff.action === 'removed'
? item.diff.fromValue && item.diff.fromValue._key === child._key
: (item.diff.toValue && item.diff.toValue._key) === child._key)
)
if (candidate) {
return candidate.diff as ObjectDiff
}
return undefined
}
export function findAnnotationDiff(diff: ObjectDiff, markDefKey: string): ObjectDiff | undefined {
return (
((diff.fields.markDefs &&
diff.fields.markDefs.isChanged &&
diff.fields.markDefs.type === 'array' &&
diff.fields.markDefs.items.find(
(item: any) =>
item.diff &&
item.diff.type === 'object' &&
((item.diff.toValue && item.diff.toValue._key && item.diff.toValue._key === markDefKey) ||
(item.diff.fromValue &&
item.diff.fromValue._key &&
item.diff.fromValue._key === markDefKey))
)?.diff) as ObjectDiff) || undefined
)
}
export function isEmptyObject(object: PortableTextChild): boolean {
return (object && isEqual(Object.keys(object), ['_key', '_type'])) || false
}
export function escapeRegExp(text: string): string {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
}
export function getAllMarkDefs(diff: ObjectDiff): PortableTextChild[] {
const allDefs: PortableTextChild[] = [
...(diff.toValue && diff.toValue.markDefs ? diff.toValue.markDefs : []),
]
const oldDefs: PortableTextChild[] =
diff.fromValue && diff.fromValue.markDefs ? diff.fromValue.markDefs : []
oldDefs.forEach((oDef) => {
if (!allDefs.some((def) => oDef._key === def._key)) {
allDefs.push(oDef)
}
})
return orderBy(allDefs, ['_key'], ['asc'])
}