BookParser.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  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. if (text != ' ' && text.trim() == '')
  97. text = text.trim();
  98. if (text == '')
  99. return;
  100. switch (path) {
  101. case '/FictionBook/description/title-info/author/first-name':
  102. fb2.firstName = text;
  103. break;
  104. case '/FictionBook/description/title-info/author/middle-name':
  105. fb2.middleName = text;
  106. break;
  107. case '/FictionBook/description/title-info/author/last-name':
  108. fb2.lastName = text;
  109. break;
  110. case '/FictionBook/description/title-info/genre':
  111. fb2.genre = text;
  112. break;
  113. case '/FictionBook/description/title-info/date':
  114. fb2.date = text;
  115. break;
  116. case '/FictionBook/description/title-info/book-title':
  117. fb2.bookTitle = text;
  118. break;
  119. case '/FictionBook/description/title-info/id':
  120. fb2.id = text;
  121. break;
  122. }
  123. if (path.indexOf('/FictionBook/description/title-info/annotation') == 0) {
  124. if (!fb2.annotation)
  125. fb2.annotation = '';
  126. if (tag != 'annotation')
  127. fb2.annotation += `<${tag}>${text}</${tag}>`;
  128. else
  129. fb2.annotation += text;
  130. }
  131. if (path.indexOf('/FictionBook/body/title') == 0) {
  132. newParagraph(text, text.length);
  133. }
  134. if (path.indexOf('/FictionBook/body/section') == 0) {
  135. switch (tag) {
  136. case 'p':
  137. growParagraph(text, text.length);
  138. break;
  139. case 'section':
  140. case 'title':
  141. newParagraph(text, text.length);
  142. break;
  143. default:
  144. growParagraph(`<${tag}>${text}</${tag}>`, text.length);
  145. }
  146. }
  147. });
  148. parser.on('cdata', (data) => {// eslint-disable-line no-unused-vars
  149. });
  150. parser.on('comment', (text) => {// eslint-disable-line no-unused-vars
  151. });
  152. parser.on('progress', async(progress) => {
  153. if (progress > nextPerc) {
  154. await sleep(1);
  155. callback(progress);
  156. nextPerc += 10;
  157. }
  158. });
  159. await parser.parse(data);
  160. this.fb2 = fb2;
  161. this.para = para;
  162. this.textLength = paraOffset;
  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. splitToStyle(s) {
  187. let result = [];/*array of {
  188. style: {bold: Boolean, italic: Boolean},
  189. text: String,
  190. }*/
  191. const parser = new EasySAXParser();
  192. let style = {};
  193. parser.on('textNode', (text) => {
  194. result.push({
  195. style: Object.assign({}, style),
  196. text: text
  197. });
  198. });
  199. parser.on('startNode', (elemName, getAttr, isTagEnd, getStrNode) => {// eslint-disable-line no-unused-vars
  200. if (elemName == 'strong')
  201. style.bold = true;
  202. else if (elemName == 'emphasis')
  203. style.italic = true;
  204. });
  205. parser.on('endNode', (elemName, isTagStart, getStrNode) => {// eslint-disable-line no-unused-vars
  206. if (elemName == 'strong')
  207. style.bold = false;
  208. else if (elemName == 'emphasis')
  209. style.italic = false;
  210. });
  211. parser.parse(`<p>${s}</p>`);
  212. return result;
  213. }
  214. splitToSlogi(word) {
  215. let result = [];
  216. const glas = new Set(['а', 'А', 'о', 'О', 'и', 'И', 'е', 'Е', 'ё', 'Ё', 'э', 'Э', 'ы', 'Ы', 'у', 'У', 'ю', 'Ю', 'я', 'Я']);
  217. const soglas = new Set([
  218. 'б', 'в', 'г', 'д', 'ж', 'з', 'й', 'к', 'л', 'м', 'н', 'п', 'р', 'с', 'т', 'ф', 'х', 'ц', 'ч', 'ш', 'щ',
  219. 'Б', 'В', 'Г', 'Д', 'Ж', 'З', 'Й', 'К', 'Л', 'М', 'Н', 'П', 'Р', 'С', 'Т', 'Ф', 'Х', 'Ч', 'Ц', 'Ш', 'Щ'
  220. ]);
  221. const znak = new Set(['ь', 'Ь', 'ъ', 'Ъ', 'й', 'Й']);
  222. const alpha = new Set([...glas, ...soglas, ...znak]);
  223. let slog = '';
  224. let slogLen = 0;
  225. const len = word.length;
  226. word += ' ';
  227. for (let i = 0; i < len; i++) {
  228. slog += word[i];
  229. if (alpha.has(word[i]))
  230. slogLen++;
  231. if (slogLen > 1 && i < len - 2 && (
  232. //гласная, а следом не 2 согласные буквы
  233. (glas.has(word[i]) && !(soglas.has(word[i + 1]) &&
  234. soglas.has(word[i + 2])) && alpha.has(word[i + 1]) && alpha.has(word[i + 2])
  235. ) ||
  236. //предыдущая не согласная буква, текущая согласная, а следом согласная и согласная|гласная буквы
  237. (alpha.has(word[i - 1]) && !soglas.has(word[i - 1]) &&
  238. soglas.has(word[i]) && soglas.has(word[i + 1]) &&
  239. (glas.has(word[i + 2]) || soglas.has(word[i + 2])) &&
  240. alpha.has(word[i + 1]) && alpha.has(word[i + 2])
  241. ) ||
  242. //мягкий или твердый знак или Й
  243. (znak.has(word[i]) && alpha.has(word[i + 1]) && alpha.has(word[i + 2])) ||
  244. (word[i] == '-')
  245. ) &&
  246. //нельзя оставлять окончания на ь, ъ, й
  247. !(znak.has(word[i + 2]) && !alpha.has(word[i + 3]))
  248. ) {
  249. result.push(slog);
  250. slog = '';
  251. slogLen = 0;
  252. }
  253. }
  254. if (slog)
  255. result.push(slog);
  256. return result;
  257. }
  258. parsePara(paraIndex) {
  259. const para = this.para[paraIndex];
  260. if (para.parsed &&
  261. para.parsed.w === this.w &&
  262. para.parsed.p === this.p &&
  263. para.parsed.wordWrap === this.wordWrap &&
  264. para.parsed.font === this.font
  265. )
  266. return para.parsed;
  267. const parsed = {
  268. w: this.w,
  269. p: this.p,
  270. wordWrap: this.wordWrap,
  271. font: this.font,
  272. };
  273. const lines = []; /* array of
  274. {
  275. begin: Number,
  276. end: Number,
  277. first: Boolean,
  278. last: Boolean,
  279. parts: array of {
  280. style: {bold: Boolean, italic: Boolean},
  281. text: String,
  282. }
  283. }*/
  284. let parts = this.splitToStyle(para.text);
  285. let line = {begin: para.offset, parts: []};
  286. let partText = '';//накапливаемый кусок со стилем
  287. let str = '';//измеряемая строка
  288. let prevStr = '';
  289. let prevW = 0;
  290. let j = 0;//номер строки
  291. let ofs = -1;
  292. // тут начинается самый замес, перенос по слогам и стилизация
  293. for (const part of parts) {
  294. const words = part.text.split(' ');
  295. const style = part.style;
  296. let sp1 = '';
  297. let sp2 = '';
  298. for (let i = 0; i < words.length; i++) {
  299. const word = words[i];
  300. ofs += word.length + (i < words.length - 1 ? 1 : 0);
  301. str += sp1 + word;
  302. sp1 = ' ';
  303. let p = (j == 0 ? parsed.p : 0);
  304. let w = this.measureText(str, style) + p;
  305. let wordTail = word;
  306. if (w > parsed.w) {
  307. if (parsed.wordWrap) {//по слогам
  308. let slogi = this.splitToSlogi(word);
  309. if (slogi.length > 1) {
  310. let s = prevStr + ' ';
  311. let ss = ' ';
  312. let pw;
  313. const slogiLen = slogi.length;
  314. for (let k = 0; k < slogiLen - 1; k++) {
  315. let slog = slogi[0];
  316. let ww = this.measureText(s + slog + (slog[slog.length - 1] == '-' ? '' : '-'), style) + p;
  317. if (ww <= parsed.w) {
  318. s += slog;
  319. ss += slog;
  320. } else
  321. break;
  322. pw = ww;
  323. slogi.shift();
  324. }
  325. if (pw) {
  326. prevW = pw;
  327. partText += ss + (ss[ss.length - 1] == '-' ? '' : '-');
  328. wordTail = slogi.join('');
  329. }
  330. }
  331. }
  332. if (partText != '')
  333. line.parts.push({style, text: partText});
  334. if (line.parts.length) {//корявенько, коррекция при переносе, отрефакторить не вышло
  335. let t = line.parts[line.parts.length - 1].text;
  336. if (t[t.length - 1] == ' ') {
  337. line.parts[line.parts.length - 1].text = t.trimRight();
  338. prevW -= this.measureText(' ');
  339. }
  340. }
  341. line.end = para.offset + ofs - wordTail.length - 1;
  342. line.width = prevW;
  343. line.first = (j == 0);
  344. line.last = false;
  345. lines.push(line);
  346. line = {begin: line.end + 1, parts: []};
  347. partText = '';
  348. sp2 = '';
  349. str = wordTail;
  350. j++;
  351. }
  352. prevStr = str;
  353. partText += sp2 + wordTail;
  354. sp2 = ' ';
  355. prevW = w;
  356. }
  357. if (partText != '')
  358. line.parts.push({style, text: partText});
  359. partText = '';
  360. }
  361. if (line.parts.length) {//корявенько, коррекция при переносе
  362. let t = line.parts[line.parts.length - 1].text;
  363. if (t.trimRight() != t) {
  364. line.parts[line.parts.length - 1].text = t.trimRight();
  365. prevW -= this.measureText(' ');
  366. }
  367. }
  368. line.end = para.offset + para.length - 1;
  369. line.width = prevW;
  370. line.first = (j == 0);
  371. line.last = true;
  372. lines.push(line);
  373. parsed.lines = lines;
  374. para.parsed = parsed;
  375. return parsed;
  376. }
  377. findLineIndex(bookPos, lines) {
  378. let result = undefined;
  379. //дихотомия
  380. let first = 0;
  381. let last = lines.length - 1;
  382. while (first < last) {
  383. let mid = first + Math.floor((last - first)/2);
  384. if (bookPos <= lines[mid].end)
  385. last = mid;
  386. else
  387. first = mid + 1;
  388. }
  389. if (last >= 0) {
  390. if (bookPos >= lines[last].begin && bookPos <= lines[last].end)
  391. result = last;
  392. }
  393. return result;
  394. }
  395. getLines(bookPos, n) {
  396. const result = [];
  397. let paraIndex = this.findParaIndex(bookPos);
  398. if (paraIndex === undefined)
  399. return result;
  400. if (n > 0) {
  401. let parsed = this.parsePara(paraIndex);
  402. let i = this.findLineIndex(bookPos, parsed.lines);
  403. if (i === undefined)
  404. return result;
  405. while (n > 0) {
  406. result.push(parsed.lines[i]);
  407. i++;
  408. if (i >= parsed.lines.length) {
  409. paraIndex++;
  410. if (paraIndex < this.para.length)
  411. parsed = this.parsePara(paraIndex);
  412. else
  413. return result;
  414. i = 0;
  415. }
  416. n--;
  417. }
  418. } else if (n < 0) {
  419. n = -n;
  420. let parsed = this.parsePara(paraIndex);
  421. let i = this.findLineIndex(bookPos, parsed.lines);
  422. if (i === undefined)
  423. return result;
  424. while (n > 0) {
  425. result.push(parsed.lines[i]);
  426. i--;
  427. if (i < 0) {
  428. paraIndex--;
  429. if (paraIndex >= 0)
  430. parsed = this.parsePara(paraIndex);
  431. else
  432. return result;
  433. i = parsed.lines.length - 1;
  434. }
  435. n--;
  436. }
  437. }
  438. return result;
  439. }
  440. }