-
Notifications
You must be signed in to change notification settings - Fork 43
/
drafty.js
2742 lines (2507 loc) · 69.3 KB
/
drafty.js
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @copyright 2015-2024 Tinode LLC.
* @summary Minimally rich text representation and formatting for Tinode.
* @license Apache 2.0
*
* @file Basic parser and formatter for very simple text markup. Mostly targeted at
* mobile use cases similar to Telegram, WhatsApp, and FB Messenger.
*
* <p>Supports conversion of user keyboard input to formatted text:</p>
* <ul>
* <li>*abc* → <b>abc</b></li>
* <li>_abc_ → <i>abc</i></li>
* <li>~abc~ → <del>abc</del></li>
* <li>`abc` → <tt>abc</tt></li>
* </ul>
* Also supports forms and buttons.
*
* Nested formatting is supported, e.g. *abc _def_* -> <b>abc <i>def</i></b>
* URLs, @mentions, and #hashtags are extracted and converted into links.
* Forms and buttons can be added procedurally.
* JSON data representation is inspired by Draft.js raw formatting.
*
*
* @example
* Text:
* <pre>
* this is *bold*, `code` and _italic_, ~strike~
* combined *bold and _italic_*
* an url: https://www.example.com/abc#fragment and another _www.tinode.co_
* this is a @mention and a #hashtag in a string
* second #hashtag
* </pre>
*
* Sample JSON representation of the text above:
* {
* "txt": "this is bold, code and italic, strike combined bold and italic an url: https://www.example.com/abc#fragment " +
* "and another www.tinode.co this is a @mention and a #hashtag in a string second #hashtag",
* "fmt": [
* { "at":8, "len":4,"tp":"ST" },{ "at":14, "len":4, "tp":"CO" },{ "at":23, "len":6, "tp":"EM"},
* { "at":31, "len":6, "tp":"DL" },{ "tp":"BR", "len":1, "at":37 },{ "at":56, "len":6, "tp":"EM" },
* { "at":47, "len":15, "tp":"ST" },{ "tp":"BR", "len":1, "at":62 },{ "at":120, "len":13, "tp":"EM" },
* { "at":71, "len":36, "key":0 },{ "at":120, "len":13, "key":1 },{ "tp":"BR", "len":1, "at":133 },
* { "at":144, "len":8, "key":2 },{ "at":159, "len":8, "key":3 },{ "tp":"BR", "len":1, "at":179 },
* { "at":187, "len":8, "key":3 },{ "tp":"BR", "len":1, "at":195 }
* ],
* "ent": [
* { "tp":"LN", "data":{ "url":"https://www.example.com/abc#fragment" } },
* { "tp":"LN", "data":{ "url":"http://www.tinode.co" } },
* { "tp":"MN", "data":{ "val":"mention" } },
* { "tp":"HT", "data":{ "val":"hashtag" } }
* ]
* }
*/
'use strict';
// NOTE TO DEVELOPERS:
// Localizable strings should be double quoted "строка на другом языке",
// non-localizable strings should be single quoted 'non-localized'.
const MAX_FORM_ELEMENTS = 8;
const MAX_PREVIEW_ATTACHMENTS = 3;
const MAX_PREVIEW_DATA_SIZE = 64;
const JSON_MIME_TYPE = 'application/json';
const DRAFTY_MIME_TYPE = 'text/x-drafty';
const ALLOWED_ENT_FIELDS = ['act', 'height', 'duration', 'incoming', 'mime', 'name', 'premime', 'preref', 'preview',
'ref', 'size', 'state', 'url', 'val', 'width'
];
// Intl.Segmenter is not available in Firefox 124 and earlier. FF 125 with support for Intl.Segmenter
// was released on April 15, 2024. Polyfill is included in the top package (webapp).
const segmenter = new Intl.Segmenter();
// Regular expressions for parsing inline formats. Javascript does not support lookbehind,
// so it's a bit messy.
const INLINE_STYLES = [
// Strong = bold, *bold text*
{
name: 'ST',
start: /(?:^|[\W_])(\*)[^\s*]/,
end: /[^\s*](\*)(?=$|[\W_])/
},
// Emphesized = italic, _italic text_
{
name: 'EM',
start: /(?:^|\W)(_)[^\s_]/,
end: /[^\s_](_)(?=$|\W)/
},
// Deleted, ~strike this though~
{
name: 'DL',
start: /(?:^|[\W_])(~)[^\s~]/,
end: /[^\s~](~)(?=$|[\W_])/
},
// Code block `this is monospace`
{
name: 'CO',
start: /(?:^|\W)(`)[^`]/,
end: /[^`](`)(?=$|\W)/
}
];
// Relative weights of formatting spans. Greater index in array means greater weight.
const FMT_WEIGHT = ['QQ'];
// RegExps for entity extraction (RF = reference)
const ENTITY_TYPES = [
// URLs
{
name: 'LN',
dataName: 'url',
pack: function(val) {
// Check if the protocol is specified, if not use http
if (!/^[a-z]+:\/\//i.test(val)) {
val = 'http://' + val;
}
return {
url: val
};
},
re: /(?:(?:https?|ftp):\/\/|www\.|ftp\.)[-A-Z0-9+&@#\/%=~_|$?!:,.]*[A-Z0-9+&@#\/%=~_|$]/ig
},
// Mentions @user (must be 2 or more characters)
{
name: 'MN',
dataName: 'val',
pack: function(val) {
return {
val: val.slice(1)
};
},
re: /\B@([\p{L}\p{N}][._\p{L}\p{N}]*[\p{L}\p{N}])/ug
},
// Hashtags #hashtag, like metion 2 or more characters.
{
name: 'HT',
dataName: 'val',
pack: function(val) {
return {
val: val.slice(1)
};
},
re: /\B#([\p{L}\p{N}][._\p{L}\p{N}]*[\p{L}\p{N}])/ug
}
];
// HTML tag name suggestions
const FORMAT_TAGS = {
AU: {
html_tag: 'audio',
md_tag: undefined,
isVoid: false
},
BN: {
html_tag: 'button',
md_tag: undefined,
isVoid: false
},
BR: {
html_tag: 'br',
md_tag: '\n',
isVoid: true
},
CO: {
html_tag: 'tt',
md_tag: '`',
isVoid: false
},
DL: {
html_tag: 'del',
md_tag: '~',
isVoid: false
},
EM: {
html_tag: 'i',
md_tag: '_',
isVoid: false
},
EX: {
html_tag: '',
md_tag: undefined,
isVoid: true
},
FM: {
html_tag: 'div',
md_tag: undefined,
isVoid: false
},
HD: {
html_tag: '',
md_tag: undefined,
isVoid: false
},
HL: {
html_tag: 'span',
md_tag: undefined,
isVoid: false
},
HT: {
html_tag: 'a',
md_tag: undefined,
isVoid: false
},
IM: {
html_tag: 'img',
md_tag: undefined,
isVoid: false
},
LN: {
html_tag: 'a',
md_tag: undefined,
isVoid: false
},
MN: {
html_tag: 'a',
md_tag: undefined,
isVoid: false
},
RW: {
html_tag: 'div',
md_tag: undefined,
isVoid: false,
},
QQ: {
html_tag: 'div',
md_tag: undefined,
isVoid: false
},
ST: {
html_tag: 'b',
md_tag: '*',
isVoid: false
},
VC: {
html_tag: 'div',
md_tag: undefined,
isVoid: false
},
VD: {
html_tag: 'video',
md_tag: undefined,
isVoid: false
}
};
// Convert base64-encoded string into Blob.
function base64toObjectUrl(b64, contentType, logger) {
if (!b64) {
return null;
}
try {
const bin = atob(b64);
const length = bin.length;
const buf = new ArrayBuffer(length);
const arr = new Uint8Array(buf);
for (let i = 0; i < length; i++) {
arr[i] = bin.charCodeAt(i);
}
return URL.createObjectURL(new Blob([buf], {
type: contentType
}));
} catch (err) {
if (logger) {
logger("Drafty: failed to convert object.", err.message);
}
}
return null;
}
function base64toDataUrl(b64, contentType) {
if (!b64) {
return null;
}
contentType = contentType || 'image/jpeg';
return 'data:' + contentType + ';base64,' + b64;
}
// Helpers for converting Drafty to HTML.
const DECORATORS = {
// Visial styles
ST: {
open: _ => '<b>',
close: _ => '</b>'
},
EM: {
open: _ => '<i>',
close: _ => '</i>'
},
DL: {
open: _ => '<del>',
close: _ => '</del>'
},
CO: {
open: _ => '<tt>',
close: _ => '</tt>'
},
// Line break
BR: {
open: _ => '<br/>',
close: _ => ''
},
// Hidden element
HD: {
open: _ => '',
close: _ => ''
},
// Highlighted element.
HL: {
open: _ => '<span style="color:teal">',
close: _ => '</span>'
},
// Link (URL)
LN: {
open: (data) => {
return '<a href="' + data.url + '">';
},
close: _ => '</a>',
props: (data) => {
return data ? {
href: data.url,
target: '_blank'
} : null;
},
},
// Mention
MN: {
open: (data) => {
return '<a href="#' + data.val + '">';
},
close: _ => '</a>',
props: (data) => {
return data ? {
id: data.val
} : null;
},
},
// Hashtag
HT: {
open: (data) => {
return '<a href="#' + data.val + '">';
},
close: _ => '</a>',
props: (data) => {
return data ? {
id: data.val
} : null;
},
},
// Button
BN: {
open: _ => '<button>',
close: _ => '</button>',
props: (data) => {
return data ? {
'data-act': data.act,
'data-val': data.val,
'data-name': data.name,
'data-ref': data.ref
} : null;
},
},
// Audio recording
AU: {
open: (data) => {
const url = data.ref || base64toObjectUrl(data.val, data.mime, Drafty.logger);
return '<audio controls src="' + url + '">';
},
close: _ => '</audio>',
props: (data) => {
if (!data) return null;
return {
// Embedded data or external link.
src: data.ref || base64toObjectUrl(data.val, data.mime, Drafty.logger),
'data-preload': data.ref ? 'metadata' : 'auto',
'data-duration': data.duration,
'data-name': data.name,
'data-size': data.val ? ((data.val.length * 0.75) | 0) : (data.size | 0),
'data-mime': data.mime,
};
}
},
// Image
IM: {
open: data => {
// Don't use data.ref for preview: it's a security risk.
const tmpPreviewUrl = base64toDataUrl(data._tempPreview, data.mime);
const previewUrl = base64toObjectUrl(data.val, data.mime, Drafty.logger);
const downloadUrl = data.ref || previewUrl;
return (data.name ? '<a href="' + downloadUrl + '" download="' + data.name + '">' : '') +
'<img src="' + (tmpPreviewUrl || previewUrl) + '"' +
(data.width ? ' width="' + data.width + '"' : '') +
(data.height ? ' height="' + data.height + '"' : '') + ' border="0" />';
},
close: data => {
return (data.name ? '</a>' : '');
},
props: data => {
if (!data) return null;
return {
// Temporary preview, or permanent preview, or external link.
src: base64toDataUrl(data._tempPreview, data.mime) ||
data.ref || base64toObjectUrl(data.val, data.mime, Drafty.logger),
title: data.name,
alt: data.name,
'data-width': data.width,
'data-height': data.height,
'data-name': data.name,
'data-size': data.ref ? (data.size | 0) : (data.val ? ((data.val.length * 0.75) | 0) : (data.size | 0)),
'data-mime': data.mime,
};
},
},
// Form - structured layout of elements.
FM: {
open: _ => '<div>',
close: _ => '</div>'
},
// Row: logic grouping of elements
RW: {
open: _ => '<div>',
close: _ => '</div>'
},
// Quoted block.
QQ: {
open: _ => '<div>',
close: _ => '</div>',
props: (data) => {
return data ? {} : null;
},
},
// Video call
VC: {
open: _ => '<div>',
close: _ => '</div>',
props: data => {
if (!data) return {};
return {
'data-duration': data.duration,
'data-state': data.state,
};
}
},
// Video.
VD: {
open: data => {
const tmpPreviewUrl = base64toDataUrl(data._tempPreview, data.mime);
const previewUrl = data.ref || base64toObjectUrl(data.preview, data.premime || 'image/jpeg', Drafty.logger);
return '<img src="' + (tmpPreviewUrl || previewUrl) + '"' +
(data.width ? ' width="' + data.width + '"' : '') +
(data.height ? ' height="' + data.height + '"' : '') + ' border="0" />';
},
close: _ => '',
props: data => {
if (!data) return null;
const poster = data.preref || base64toObjectUrl(data.preview, data.premime || 'image/jpeg', Drafty.logger);
return {
// Embedded data or external link.
src: poster,
'data-src': data.ref || base64toObjectUrl(data.val, data.mime, Drafty.logger),
'data-width': data.width,
'data-height': data.height,
'data-preload': data.ref ? 'metadata' : 'auto',
'data-preview': poster,
'data-duration': data.duration | 0,
'data-name': data.name,
'data-size': data.ref ? (data.size | 0) : (data.val ? ((data.val.length * 0.75) | 0) : (data.size | 0)),
'data-mime': data.mime,
};
}
},
};
/**
* The main object which performs all the formatting actions.
* @class Drafty
* @constructor
*/
const Drafty = function() {
this.txt = '';
this.fmt = [];
this.ent = [];
}
/**
* Initialize Drafty document to a plain text string.
*
* @param {string} plainText - string to use as Drafty content.
*
* @returns new Drafty document or null is plainText is not a string or undefined.
*/
Drafty.init = function(plainText) {
if (typeof plainText == 'undefined') {
plainText = '';
} else if (typeof plainText != 'string') {
return null;
}
return {
txt: plainText
};
}
/**
* Parse plain text into Drafty document.
* @memberof Drafty
* @static
*
* @param {string} content - plain-text content to parse.
* @return {Drafty} parsed document or null if the source is not plain text.
*/
Drafty.parse = function(content) {
// Make sure we are parsing strings only.
if (typeof content != 'string') {
return null;
}
// Split text into lines. It makes further processing easier.
const lines = content.split(/\r?\n/);
// Holds entities referenced from text
const entityMap = [];
const entityIndex = {};
// Processing lines one by one, hold intermediate result in blx.
const blx = [];
lines.forEach((line) => {
let spans = [];
let entities;
// Find formatted spans in the string.
// Try to match each style.
INLINE_STYLES.forEach((tag) => {
// Each style could be matched multiple times.
spans = spans.concat(spannify(line, tag.start, tag.end, tag.name));
});
let block;
if (spans.length == 0) {
block = {
txt: line
};
} else {
// Sort spans by style occurence early -> late, then by length: first long then short.
spans.sort((a, b) => {
const diff = a.at - b.at;
return diff != 0 ? diff : b.end - a.end;
});
// Convert an array of possibly overlapping spans into a tree.
spans = toSpanTree(spans);
// Build a tree representation of the entire string, not
// just the formatted parts.
const chunks = chunkify(line, 0, line.length, spans);
const drafty = draftify(chunks, 0);
block = {
txt: drafty.txt,
fmt: drafty.fmt
};
}
// Extract entities from the cleaned up string.
entities = extractEntities(block.txt);
if (entities.length > 0) {
const ranges = [];
for (let i in entities) {
// {offset: match['index'], unique: match[0], len: match[0].length, data: ent.packer(), type: ent.name}
const entity = entities[i];
let index = entityIndex[entity.unique];
if (!index) {
index = entityMap.length;
entityIndex[entity.unique] = index;
entityMap.push({
tp: entity.type,
data: entity.data
});
}
ranges.push({
at: entity.offset,
len: entity.len,
key: index
});
}
block.ent = ranges;
}
blx.push(block);
});
const result = {
txt: ''
};
// Merge lines and save line breaks as BR inline formatting.
if (blx.length > 0) {
result.txt = blx[0].txt;
result.fmt = (blx[0].fmt || []).concat(blx[0].ent || []);
if (result.fmt.length) {
const segments = segmenter.segment(result.txt);
for (const ele of result.fmt) {
({
at: ele.at,
len: ele.len
} =
toGraphemeValues(ele, segments, result.txt));
}
}
for (let i = 1; i < blx.length; i++) {
const block = blx[i];
const offset = stringToGraphemes(result.txt).length + 1;
result.fmt.push({
tp: 'BR',
len: 1,
at: offset - 1
});
let segments = {};
result.txt += ' ' + block.txt;
if (block.fmt) {
segments = segmenter.segment(block.txt);
result.fmt = result.fmt.concat(
block.fmt.map((s) => {
const {
at: correctAt,
len: correctLen
} =
toGraphemeValues(s, segments, block.txt);
s.at = correctAt + offset;
s.len = correctLen;
return s;
})
);
}
if (block.ent) {
if (isEmptyObject(segments)) {
segments = segmenter.segment(block.txt);
}
result.fmt = result.fmt.concat(
block.ent.map((s) => {
const {
at: correctAt,
len: correctLen
} =
toGraphemeValues(s, segments, block.txt);
s.at = correctAt + offset;
s.len = correctLen;
return s;
})
);
}
}
if (result.fmt.length == 0) {
delete result.fmt;
}
if (entityMap.length > 0) {
result.ent = entityMap;
}
}
return result;
}
/**
* Append one Drafty document to another.
*
* @param {Drafty} first - Drafty document to append to.
* @param {Drafty|string} second - Drafty document or string being appended.
*
* @return {Drafty} first document with the second appended to it.
*/
Drafty.append = function(first, second) {
if (!first) {
return second;
}
if (!second) {
return first;
}
first.txt = first.txt || '';
const len = stringToGraphemes(first.txt).length;
if (typeof second == 'string') {
first.txt += second;
} else if (second.txt) {
first.txt += second.txt;
}
if (Array.isArray(second.fmt)) {
first.fmt = first.fmt || [];
if (Array.isArray(second.ent)) {
first.ent = first.ent || [];
}
second.fmt.forEach(src => {
const fmt = {
at: (src.at | 0) + len,
len: src.len | 0
};
// Special case for the outside of the normal rendering flow styles.
if (src.at == -1) {
fmt.at = -1;
fmt.len = 0;
}
if (src.tp) {
fmt.tp = src.tp;
} else {
fmt.key = first.ent.length;
first.ent.push(second.ent[src.key || 0]);
}
first.fmt.push(fmt);
});
}
return first;
}
/**
* Description of an image to attach.
* @typedef {Object} ImageDesc
* @memberof Drafty
*
* @property {string} mime - mime-type of the image, e.g. "image/png".
* @property {string} refurl - reference to the content. Could be null/undefined.
* @property {string} bits - base64-encoded image content. Could be null/undefined.
* @property {string} preview - base64-encoded thumbnail of the image.
* @property {integer} width - width of the image.
* @property {integer} height - height of the image.
* @property {string} filename - file name suggestion for downloading the image.
* @property {integer} size - size of the image in bytes. Treat is as an untrusted hint.
* @property {string} _tempPreview - base64-encoded image preview used during upload process; not serializable.
* @property {Promise} urlPromise - Promise which returns content URL when resolved.
*/
/**
* Insert inline image into Drafty document.
* @memberof Drafty
* @static
*
* @param {Drafty} content - document to add image to.
* @param {integer} at - index where the object is inserted. The length of the image is always 1.
* @param {ImageDesc} imageDesc - object with image paramenets and data.
*
* @return {Drafty} updated document.
*/
Drafty.insertImage = function(content, at, imageDesc) {
content = content || {
txt: ' '
};
content.ent = content.ent || [];
content.fmt = content.fmt || [];
content.fmt.push({
at: at | 0,
len: 1,
key: content.ent.length
});
const ex = {
tp: 'IM',
data: {
mime: imageDesc.mime,
ref: imageDesc.refurl,
val: imageDesc.bits || imageDesc.preview,
width: imageDesc.width,
height: imageDesc.height,
name: imageDesc.filename,
size: imageDesc.size | 0,
}
};
if (imageDesc.urlPromise) {
ex.data._tempPreview = imageDesc._tempPreview;
ex.data._processing = true;
imageDesc.urlPromise.then(
url => {
ex.data.ref = url;
ex.data._tempPreview = undefined;
ex.data._processing = undefined;
},
_ => {
// Catch the error, otherwise it will appear in the console.
ex.data._processing = undefined;
}
);
}
content.ent.push(ex);
return content;
}
/**
* Description of a video to attach.
* @typedef {Object} VideoDesc
* @memberof Drafty
*
* @property {string} mime - mime-type of the video, e.g. "video/mpeg".
* @property {string} refurl - reference to the content. Could be null/undefined.
* @property {string} bits - in-band base64-encoded image data. Could be null/undefined.
* @property {string} preview - base64-encoded screencapture from the video. Could be null/undefined.
* @property {string} preref - reference to screencapture from the video. Could be null/undefined.
* @property {integer} width - width of the video.
* @property {integer} height - height of the video.
* @property {integer} duration - duration of the video.
* @property {string} filename - file name suggestion for downloading the video.
* @property {integer} size - size of the video in bytes. Treat is as an untrusted hint.
* @property {string} _tempPreview - base64-encoded screencapture used during upload process; not serializable.
* @property {Promise} urlPromise - array of two promises, which return URLs of video and preview uploads correspondingly
* (either could be null).
*/
/**
* Insert inline image into Drafty document.
* @memberof Drafty
* @static
*
* @param {Drafty} content - document to add video to.
* @param {integer} at - index where the object is inserted. The length of the video is always 1.
* @param {VideoDesc} videoDesc - object with video paramenets and data.
*
* @return {Drafty} updated document.
*/
Drafty.insertVideo = function(content, at, videoDesc) {
content = content || {
txt: ' '
};
content.ent = content.ent || [];
content.fmt = content.fmt || [];
content.fmt.push({
at: at | 0,
len: 1,
key: content.ent.length
});
const ex = {
tp: 'VD',
data: {
mime: videoDesc.mime,
ref: videoDesc.refurl,
val: videoDesc.bits,
preref: videoDesc.preref,
preview: videoDesc.preview,
width: videoDesc.width,
height: videoDesc.height,
duration: videoDesc.duration | 0,
name: videoDesc.filename,
size: videoDesc.size | 0,
}
};
if (videoDesc.urlPromise) {
ex.data._tempPreview = videoDesc._tempPreview;
ex.data._processing = true;
videoDesc.urlPromise.then(
urls => {
ex.data.ref = urls[0];
ex.data.preref = urls[1];
ex.data._tempPreview = undefined;
ex.data._processing = undefined;
},
_ => {
// Catch the error, otherwise it will appear in the console.
ex.data._processing = undefined;
}
);
}
content.ent.push(ex);
return content;
}
/**
* Description of an audio recording to attach.
* @typedef {Object} AudioDesc
* @memberof Drafty
*
* @property {string} mime - mime-type of the audio, e.g. "audio/ogg".
* @property {string} refurl - reference to the content. Could be null/undefined.
* @property {string} bits - base64-encoded audio content. Could be null/undefined.
* @property {integer} duration - duration of the record in milliseconds.
* @property {string} preview - base64 encoded short array of amplitude values 0..100.
* @property {string} filename - file name suggestion for downloading the audio.
* @property {integer} size - size of the recording in bytes. Treat is as an untrusted hint.
* @property {Promise} urlPromise - Promise which returns content URL when resolved.
*/
/**
* Insert audio recording into Drafty document.
* @memberof Drafty
* @static
*
* @param {Drafty} content - document to add audio record to.
* @param {integer} at - index where the object is inserted. The length of the record is always 1.
* @param {AudioDesc} audioDesc - object with the audio paramenets and data.
*
* @return {Drafty} updated document.
*/
Drafty.insertAudio = function(content, at, audioDesc) {
content = content || {
txt: ' '
};
content.ent = content.ent || [];
content.fmt = content.fmt || [];
content.fmt.push({
at: at | 0,
len: 1,
key: content.ent.length
});
const ex = {
tp: 'AU',
data: {
mime: audioDesc.mime,
val: audioDesc.bits,
duration: audioDesc.duration | 0,
preview: audioDesc.preview,
name: audioDesc.filename,
size: audioDesc.size | 0,
ref: audioDesc.refurl
}
};
if (audioDesc.urlPromise) {
ex.data._processing = true;
audioDesc.urlPromise.then(
url => {
ex.data.ref = url;
ex.data._processing = undefined;
},
_ => {
// Catch the error, otherwise it will appear in the console.
ex.data._processing = undefined;
}
);
}
content.ent.push(ex);
return content;
}
/**
* Create a (self-contained) video call Drafty document.
* @memberof Drafty
* @static
* @param {boolean} audioOnly <code>true</code> if the call is initially audio-only.
* @returns Video Call drafty document.
*/
Drafty.videoCall = function(audioOnly) {
const content = {
txt: ' ',
fmt: [{
at: 0,
len: 1,
key: 0
}],
ent: [{
tp: 'VC',
data: {
aonly: audioOnly
},
}]
};
return content;
}
/**
* Update video call (VC) entity with the new status and duration.
* @memberof Drafty
* @static
*
* @param {Drafty} content - VC document to update.
* @param {object} params - new video call parameters.
* @param {string} params.state - state of video call.
* @param {number} params.duration - duration of the video call in milliseconds.
*
* @returns the same document with update applied.
*/
Drafty.updateVideoCall = function(content, params) {
// The video element could be just a format or a format + entity.
// Must ensure it's the latter first.
const fmt = ((content || {}).fmt || [])[0];
if (!fmt) {
// Unrecognized content.
return content;
}
let ent;