BookParser.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. import EasySAXParser from './easysax';
  2. import {sleep} from '../../../share/utils';
  3. export default class BookParser {
  4. constructor() {
  5. // defaults
  6. this.p = 30;// px, отступ параграфа
  7. this.w = 300;// px, ширина страницы
  8. this.wordWrap = false;// перенос по слогам
  9. // заглушка
  10. this.measureText = (text, style) => {// eslint-disable-line no-unused-vars
  11. return text.length*10;
  12. };
  13. }
  14. async parse(data, callback) {
  15. if (!callback)
  16. callback = () => {};
  17. callback(0);
  18. this.data = data;
  19. if (data.indexOf('<FictionBook') < 0) {
  20. throw new Error('Неверный формат файла');
  21. }
  22. //defaults
  23. let fb2 = {
  24. firstName: '',
  25. middleName: '',
  26. lastName: '',
  27. bookTitle: '',
  28. };
  29. let path = '';
  30. let tag = '';
  31. let nextPerc = 0;
  32. let paraIndex = -1;
  33. let paraOffset = 0;
  34. let para = []; /*array of
  35. {
  36. index: Number,
  37. offset: Number, //сумма всех length до этого параграфа
  38. length: Number, //длина text без тегов
  39. text: String //текст параграфа (или title или epigraph и т.д) с вложенными тегами
  40. }
  41. */
  42. const newParagraph = (text, len) => {
  43. paraIndex++;
  44. let p = {
  45. index: paraIndex,
  46. offset: paraOffset,
  47. length: len,
  48. text: text
  49. };
  50. para[paraIndex] = p;
  51. paraOffset += p.length;
  52. };
  53. const growParagraph = (text, len) => {
  54. let p = para[paraIndex];
  55. if (p) {
  56. paraOffset -= p.length;
  57. if (p.text == ' ') {
  58. p.length = 0;
  59. p.text = '';
  60. }
  61. p.length += len;
  62. p.text += text;
  63. } else {
  64. p = {
  65. index: paraIndex,
  66. offset: paraOffset,
  67. length: len,
  68. text: text
  69. };
  70. }
  71. para[paraIndex] = p;
  72. paraOffset += p.length;
  73. };
  74. const parser = new EasySAXParser();
  75. parser.on('error', (msgError) => {// eslint-disable-line no-unused-vars
  76. });
  77. parser.on('startNode', (elemName, getAttr, isTagEnd, getStrNode) => {// eslint-disable-line no-unused-vars
  78. tag = elemName;
  79. path += '/' + elemName;
  80. if ((tag == 'p' || tag == 'empty-line') && path.indexOf('/FictionBook/body/section') == 0) {
  81. newParagraph(' ', 1);
  82. }
  83. });
  84. parser.on('endNode', (elemName, isTagStart, getStrNode) => {// eslint-disable-line no-unused-vars
  85. if (tag == elemName) {
  86. path = path.substr(0, path.length - tag.length - 1);
  87. let i = path.lastIndexOf('/');
  88. if (i >= 0) {
  89. tag = path.substr(i + 1);
  90. } else {
  91. tag = path;
  92. }
  93. }
  94. });
  95. parser.on('textNode', (text) => {
  96. text = text.trim();
  97. switch (path) {
  98. case '/FictionBook/description/title-info/author/first-name':
  99. fb2.firstName = text;
  100. break;
  101. case '/FictionBook/description/title-info/author/middle-name':
  102. fb2.middleName = text;
  103. break;
  104. case '/FictionBook/description/title-info/author/last-name':
  105. fb2.lastName = text;
  106. break;
  107. case '/FictionBook/description/title-info/genre':
  108. fb2.genre = text;
  109. break;
  110. case '/FictionBook/description/title-info/date':
  111. fb2.date = text;
  112. break;
  113. case '/FictionBook/description/title-info/book-title':
  114. fb2.bookTitle = text;
  115. break;
  116. case '/FictionBook/description/title-info/id':
  117. fb2.id = text;
  118. break;
  119. }
  120. if (path.indexOf('/FictionBook/description/title-info/annotation') == 0) {
  121. if (!fb2.annotation)
  122. fb2.annotation = '';
  123. if (tag != 'annotation')
  124. fb2.annotation += `<${tag}>${text}</${tag}>`;
  125. else
  126. fb2.annotation += text;
  127. }
  128. if (text == '')
  129. return;
  130. if (path.indexOf('/FictionBook/body/title') == 0) {
  131. newParagraph(text, text.length);
  132. }
  133. if (text == '')
  134. return;
  135. if (path.indexOf('/FictionBook/body/section') == 0) {
  136. switch (tag) {
  137. case 'p':
  138. growParagraph(text, text.length);
  139. break;
  140. case 'section':
  141. case 'title':
  142. newParagraph(text, text.length);
  143. break;
  144. default:
  145. growParagraph(`<${tag}>${text}</${tag}>`, text.length);
  146. }
  147. }
  148. });
  149. parser.on('cdata', (data) => {// eslint-disable-line no-unused-vars
  150. });
  151. parser.on('comment', (text) => {// eslint-disable-line no-unused-vars
  152. });
  153. parser.on('progress', async(progress) => {
  154. if (progress > nextPerc) {
  155. await sleep(1);
  156. callback(progress);
  157. nextPerc += 10;
  158. }
  159. });
  160. await parser.parse(data);
  161. this.fb2 = fb2;
  162. this.para = para;
  163. callback(100);
  164. await sleep(10);
  165. return {fb2};
  166. }
  167. findParaIndex(bookPos) {
  168. let result = undefined;
  169. //дихотомия
  170. let first = 0;
  171. let last = this.para.length - 1;
  172. while (first < last) {
  173. let mid = first + Math.floor((last - first)/2);
  174. if (bookPos <= this.para[mid].offset + this.para[mid].length - 1)
  175. last = mid;
  176. else
  177. first = mid + 1;
  178. }
  179. if (last >= 0) {
  180. const ofs = this.para[last].offset;
  181. if (bookPos >= ofs && bookPos < ofs + this.para[last].length)
  182. result = last;
  183. }
  184. return result;
  185. }
  186. removeTags(s) {
  187. let result = '';
  188. const parser = new EasySAXParser();
  189. parser.on('textNode', (text) => {
  190. result += text;
  191. });
  192. parser.parse(`<p>${s}</p>`);
  193. return result;
  194. }
  195. parsePara(paraIndex) {
  196. const para = this.para[paraIndex];
  197. if (para.parsed &&
  198. para.parsed.w === this.w &&
  199. para.parsed.p === this.p &&
  200. para.parsed.textAlignJustify === this.textAlignJustify &&
  201. para.parsed.wordWrap === this.wordWrap)
  202. return para.parsed;
  203. const parsed = {
  204. w: this.w,
  205. p: this.p,
  206. textAlignJustify: this.textAlignJustify,
  207. wordWrap: this.wordWrap
  208. };
  209. const lines = [];
  210. /* array of
  211. {
  212. begin: Number,
  213. end: Number,
  214. para: Boolean,
  215. parts: array of {
  216. style: 'bold'|'italic',
  217. text: String,
  218. }
  219. }*/
  220. const text = this.removeTags(para.text);
  221. const words = text.split(' ');
  222. let line = {begin: para.offset, parts: []};
  223. let prevPart = '';
  224. let part = '';
  225. let k = 0;
  226. // тут начинается самый замес, перенос и стилизация
  227. for (let i = 0; i < words.length; i++) {
  228. const word = words[i];
  229. part += word;
  230. if (this.measureText(part) > parsed.w) {
  231. line.parts.push({style: '', text: prevPart});
  232. line.end = line.begin + prevPart.length;//нет -1 !!!
  233. line.para = (k == 0);
  234. lines.push(line);
  235. line = {begin: line.end + 1, parts: []};
  236. part = word;
  237. k++;
  238. }
  239. prevPart = part;
  240. part += ' ';
  241. }
  242. line.parts.push({style: '', text: prevPart});
  243. line.end = line.begin + prevPart.length - 1;
  244. line.para = (k == 0);
  245. lines.push(line);
  246. parsed.lines = lines;
  247. para.parsed = parsed;
  248. return parsed;
  249. }
  250. findLineIndex(bookPos, lines) {
  251. let result = undefined;
  252. //дихотомия
  253. let first = 0;
  254. let last = lines.length - 1;
  255. while (first < last) {
  256. let mid = first + Math.floor((last - first)/2);
  257. if (bookPos <= lines[mid].end)
  258. last = mid;
  259. else
  260. first = mid + 1;
  261. }
  262. if (last >= 0) {
  263. if (bookPos >= lines[last].begin && bookPos <= lines[last].end)
  264. result = last;
  265. }
  266. return result;
  267. }
  268. getLines(bookPos, n) {
  269. const result = [];
  270. let paraIndex = this.findParaIndex(bookPos);
  271. if (paraIndex === undefined)
  272. return result;
  273. if (n > 0) {
  274. let parsed = this.parsePara(paraIndex);
  275. let i = this.findLineIndex(bookPos, parsed.lines);
  276. if (i === undefined)
  277. return result;
  278. while (n > 0) {
  279. result.push(parsed.lines[i]);
  280. i++;
  281. if (i >= parsed.lines.length) {
  282. paraIndex++;
  283. if (paraIndex < this.para.length)
  284. parsed = this.parsePara(paraIndex);
  285. else
  286. return result;
  287. i = 0;
  288. }
  289. n--;
  290. }
  291. } else if (n < 0) {
  292. n = -n;
  293. let parsed = this.parsePara(paraIndex);
  294. let i = this.findLineIndex(bookPos, parsed.lines);
  295. if (i === undefined)
  296. return result;
  297. while (n > 0) {
  298. result.push(parsed.lines[i]);
  299. i--;
  300. if (i < 0) {
  301. paraIndex--;
  302. if (paraIndex >= 0)
  303. parsed = this.parsePara(paraIndex);
  304. else
  305. return result;
  306. i = parsed.lines.length - 1;
  307. }
  308. n--;
  309. }
  310. }
  311. return result;
  312. }
  313. }