json.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. 'use strict';
  2. const { createReadStream } = require('fs');
  3. const ReadLine = require('readline');
  4. const MAX_LINES = 400;
  5. const MAX_LENGTH = 20000;
  6. exports.template = /* html */`
  7. <section class="asset-json">
  8. <ui-code language="json"></ui-code>
  9. <ui-label class="multiple-warn-tip" value="i18n:ENGINE.assets.multipleWarning"></ui-label>
  10. </section>
  11. `;
  12. exports.style = /* css */`
  13. .asset-json {
  14. flex: 1;
  15. display: flex;
  16. flex-direction: column;
  17. /* it is necessary */
  18. height: 0px;
  19. }
  20. .asset-json[multiple-invalid] > *:not(.multiple-warn-tip) {
  21. display: none!important;
  22. }
  23. .asset-json[multiple-invalid] > .multiple-warn-tip {
  24. display: block;
  25. }
  26. .asset-json .multiple-warn-tip {
  27. display: none;
  28. text-align: center;
  29. color: var(--color-focus-contrast-weakest);
  30. margin-top: 8px;
  31. }
  32. .asset-json > ui-code {
  33. flex: 1;
  34. }
  35. `;
  36. exports.$ = {
  37. container: '.asset-json',
  38. code: 'ui-code',
  39. };
  40. exports.ready = function() {
  41. this.code = this.$.code;
  42. };
  43. exports.update = function(assetList, metaList) {
  44. this.assetList = assetList;
  45. this.metaList = metaList;
  46. this.meta = metaList[0];
  47. this.asset = assetList[0];
  48. if (assetList.length > 1) {
  49. this.$.container.setAttribute('multiple-invalid', '');
  50. return;
  51. } else {
  52. this.$.container.removeAttribute('multiple-invalid');
  53. }
  54. // Displays 400 lines or 20,000 characters
  55. const readStream = createReadStream(this.asset.file, {
  56. encoding: 'utf-8',
  57. });
  58. let remainLines = MAX_LINES;
  59. let remainLength = MAX_LENGTH;
  60. let text = '';
  61. const readLineStream = ReadLine.createInterface({
  62. input: readStream,
  63. setEncoding: 'utf-8',
  64. });
  65. readLineStream.on('line', (line) => {
  66. const lineLength = line.length;
  67. if (lineLength > remainLength) {
  68. line = line.substr(0, remainLength);
  69. remainLength = 0;
  70. } else {
  71. remainLength -= lineLength;
  72. }
  73. remainLines--;
  74. text += `${line}\n`;
  75. if (remainLines <= 0 || remainLength <= 0) {
  76. text += '...\n';
  77. readLineStream.close();
  78. readStream.close();
  79. }
  80. });
  81. readLineStream.on('close', (err) => {
  82. if (err) {
  83. throw err;
  84. }
  85. if (this.code) {
  86. this.code.textContent = text;
  87. }
  88. });
  89. };