UNPKG

2.1 kBJavaScriptView Raw
1/**
2 * Copyright (c) Facebook, Inc. and its affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 *
7 * @format
8 *
9 * @emails oncall+draft_js
10 */
11'use strict';
12
13var invariant = require("fbjs/lib/invariant");
14
15var TEXT_CLIPPING_REGEX = /\.textClipping$/;
16var TEXT_TYPES = {
17 'text/plain': true,
18 'text/html': true,
19 'text/rtf': true
20}; // Somewhat arbitrary upper bound on text size. Let's not lock up the browser.
21
22var TEXT_SIZE_UPPER_BOUND = 5000;
23/**
24 * Extract the text content from a file list.
25 */
26
27function getTextContentFromFiles(files, callback) {
28 var readCount = 0;
29 var results = [];
30 files.forEach(function (
31 /*blob*/
32 file) {
33 readFile(file, function (
34 /*string*/
35 text) {
36 readCount++;
37 text && results.push(text.slice(0, TEXT_SIZE_UPPER_BOUND));
38
39 if (readCount == files.length) {
40 callback(results.join('\r'));
41 }
42 });
43 });
44}
45/**
46 * todo isaac: Do work to turn html/rtf into a content fragment.
47 */
48
49
50function readFile(file, callback) {
51 if (!global.FileReader || file.type && !(file.type in TEXT_TYPES)) {
52 callback('');
53 return;
54 }
55
56 if (file.type === '') {
57 var _contents = ''; // Special-case text clippings, which have an empty type but include
58 // `.textClipping` in the file name. `readAsText` results in an empty
59 // string for text clippings, so we force the file name to serve
60 // as the text value for the file.
61
62 if (TEXT_CLIPPING_REGEX.test(file.name)) {
63 _contents = file.name.replace(TEXT_CLIPPING_REGEX, '');
64 }
65
66 callback(_contents);
67 return;
68 }
69
70 var reader = new FileReader();
71
72 reader.onload = function () {
73 var result = reader.result;
74 !(typeof result === 'string') ? process.env.NODE_ENV !== "production" ? invariant(false, 'We should be calling "FileReader.readAsText" which returns a string') : invariant(false) : void 0;
75 callback(result);
76 };
77
78 reader.onerror = function () {
79 callback('');
80 };
81
82 reader.readAsText(file);
83}
84
85module.exports = getTextContentFromFiles;
\No newline at end of file