You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

85 lines
2.1 KiB

  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. * @flow strict
  9. * @emails oncall+draft_js
  10. */
  11. 'use strict';
  12. const invariant = require("fbjs/lib/invariant");
  13. const TEXT_CLIPPING_REGEX = /\.textClipping$/;
  14. const TEXT_TYPES = {
  15. 'text/plain': true,
  16. 'text/html': true,
  17. 'text/rtf': true
  18. }; // Somewhat arbitrary upper bound on text size. Let's not lock up the browser.
  19. const TEXT_SIZE_UPPER_BOUND = 5000;
  20. /**
  21. * Extract the text content from a file list.
  22. */
  23. function getTextContentFromFiles(files: Array<File>, callback: (contents: string) => void): void {
  24. let readCount = 0;
  25. const results = [];
  26. files.forEach(function (
  27. /*blob*/
  28. file) {
  29. readFile(file, function (
  30. /*string*/
  31. text) {
  32. readCount++;
  33. text && results.push(text.slice(0, TEXT_SIZE_UPPER_BOUND));
  34. if (readCount == files.length) {
  35. callback(results.join('\r'));
  36. }
  37. });
  38. });
  39. }
  40. /**
  41. * todo isaac: Do work to turn html/rtf into a content fragment.
  42. */
  43. function readFile(file: File, callback: (contents: string) => void): void {
  44. if (!global.FileReader || file.type && !(file.type in TEXT_TYPES)) {
  45. callback('');
  46. return;
  47. }
  48. if (file.type === '') {
  49. let contents = ''; // Special-case text clippings, which have an empty type but include
  50. // `.textClipping` in the file name. `readAsText` results in an empty
  51. // string for text clippings, so we force the file name to serve
  52. // as the text value for the file.
  53. if (TEXT_CLIPPING_REGEX.test(file.name)) {
  54. contents = file.name.replace(TEXT_CLIPPING_REGEX, '');
  55. }
  56. callback(contents);
  57. return;
  58. }
  59. const reader = new FileReader();
  60. reader.onload = function () {
  61. const result = reader.result;
  62. invariant(typeof result === 'string', 'We should be calling "FileReader.readAsText" which returns a string');
  63. callback(result);
  64. };
  65. reader.onerror = function () {
  66. callback('');
  67. };
  68. reader.readAsText(file);
  69. }
  70. module.exports = getTextContentFromFiles;