BookParser.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  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*20;
  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 center = false;
  33. let bold = false;
  34. let paraIndex = -1;
  35. let paraOffset = 0;
  36. let para = []; /*array of
  37. {
  38. index: Number,
  39. offset: Number, //сумма всех length до этого параграфа
  40. length: Number, //длина text без тегов
  41. text: String //текст параграфа (или title или epigraph и т.д) с вложенными тегами
  42. }
  43. */
  44. const newParagraph = (text, len) => {
  45. paraIndex++;
  46. let p = {
  47. index: paraIndex,
  48. offset: paraOffset,
  49. length: len,
  50. text: text,
  51. };
  52. para[paraIndex] = p;
  53. paraOffset += p.length;
  54. };
  55. const growParagraph = (text, len) => {
  56. let p = para[paraIndex];
  57. if (p) {
  58. paraOffset -= p.length;
  59. if (p.length == 1 && p.text[0] == ' ' && len > 0) {
  60. p.length = 0;
  61. p.text = p.text.substr(1);
  62. }
  63. p.length += len;
  64. p.text += text;
  65. } else {
  66. p = {
  67. index: paraIndex,
  68. offset: paraOffset,
  69. length: len,
  70. text: text
  71. };
  72. }
  73. para[paraIndex] = p;
  74. paraOffset += p.length;
  75. };
  76. const parser = new EasySAXParser();
  77. parser.on('error', (msgError) => {// eslint-disable-line no-unused-vars
  78. });
  79. parser.on('startNode', (elemName, getAttr, isTagEnd, getStrNode) => {// eslint-disable-line no-unused-vars
  80. tag = elemName;
  81. path += '/' + elemName;
  82. if ((tag == 'p' || tag == 'empty-line') && path.indexOf('/FictionBook/body/section') == 0) {
  83. newParagraph(' ', 1);
  84. }
  85. if (tag == 'emphasis' || tag == 'strong') {
  86. growParagraph(`<${tag}>`, 0);
  87. }
  88. if (tag == 'title') {
  89. newParagraph(' ', 1);
  90. bold = true;
  91. center = true;
  92. }
  93. if (tag == 'subtitle') {
  94. newParagraph(' ', 1);
  95. bold = true;
  96. }
  97. });
  98. parser.on('endNode', (elemName, isTagStart, getStrNode) => {// eslint-disable-line no-unused-vars
  99. if (tag == elemName) {
  100. if (tag == 'emphasis' || tag == 'strong') {
  101. growParagraph(`</${tag}>`, 0);
  102. }
  103. if (tag == 'title') {
  104. bold = false;
  105. center = false;
  106. }
  107. if (tag == 'subtitle')
  108. bold = false;
  109. path = path.substr(0, path.length - tag.length - 1);
  110. let i = path.lastIndexOf('/');
  111. if (i >= 0) {
  112. tag = path.substr(i + 1);
  113. } else {
  114. tag = path;
  115. }
  116. }
  117. });
  118. parser.on('textNode', (text) => {
  119. text = text.replace(/&nbsp;|[\t\n\r]/g, ' ');
  120. if (text != ' ' && text.trim() == '')
  121. text = text.trim();
  122. if (text == '')
  123. return;
  124. switch (path) {
  125. case '/FictionBook/description/title-info/author/first-name':
  126. fb2.firstName = text;
  127. break;
  128. case '/FictionBook/description/title-info/author/middle-name':
  129. fb2.middleName = text;
  130. break;
  131. case '/FictionBook/description/title-info/author/last-name':
  132. fb2.lastName = text;
  133. break;
  134. case '/FictionBook/description/title-info/genre':
  135. fb2.genre = text;
  136. break;
  137. case '/FictionBook/description/title-info/date':
  138. fb2.date = text;
  139. break;
  140. case '/FictionBook/description/title-info/book-title':
  141. fb2.bookTitle = text;
  142. break;
  143. case '/FictionBook/description/title-info/id':
  144. fb2.id = text;
  145. break;
  146. }
  147. if (path.indexOf('/FictionBook/description/title-info/annotation') == 0) {
  148. if (!fb2.annotation)
  149. fb2.annotation = '';
  150. if (tag != 'annotation')
  151. fb2.annotation += `<${tag}>${text}</${tag}>`;
  152. else
  153. fb2.annotation += text;
  154. }
  155. let tOpen = (center ? '<center>' : '');
  156. tOpen += (bold ? '<strong>' : '');
  157. let tClose = (center ? '</center>' : '');
  158. tClose += (bold ? '</strong>' : '');
  159. if (path.indexOf('/FictionBook/body/title') == 0) {
  160. newParagraph(`${tOpen}${text}${tClose}`, text.length, true);
  161. }
  162. if (path.indexOf('/FictionBook/body/section') == 0) {
  163. switch (tag) {
  164. case 'p':
  165. growParagraph(`${tOpen}${text}${tClose}`, text.length);
  166. break;
  167. default:
  168. growParagraph(`${tOpen}${text}${tClose}`, text.length);
  169. }
  170. }
  171. });
  172. parser.on('cdata', (data) => {// eslint-disable-line no-unused-vars
  173. });
  174. parser.on('comment', (text) => {// eslint-disable-line no-unused-vars
  175. });
  176. parser.on('progress', async(progress) => {
  177. if (progress > nextPerc) {
  178. await sleep(1);
  179. callback(progress);
  180. nextPerc += 10;
  181. }
  182. });
  183. await parser.parse(data);
  184. this.fb2 = fb2;
  185. this.para = para;
  186. this.textLength = paraOffset;
  187. callback(100);
  188. await sleep(10);
  189. return {fb2};
  190. }
  191. findParaIndex(bookPos) {
  192. let result = undefined;
  193. //дихотомия
  194. let first = 0;
  195. let last = this.para.length - 1;
  196. while (first < last) {
  197. let mid = first + Math.floor((last - first)/2);
  198. if (bookPos <= this.para[mid].offset + this.para[mid].length - 1)
  199. last = mid;
  200. else
  201. first = mid + 1;
  202. }
  203. if (last >= 0) {
  204. const ofs = this.para[last].offset;
  205. if (bookPos >= ofs && bookPos < ofs + this.para[last].length)
  206. result = last;
  207. }
  208. return result;
  209. }
  210. splitToStyle(s) {
  211. let result = [];/*array of {
  212. style: {bold: Boolean, italic: Boolean, center: Boolean},
  213. text: String,
  214. }*/
  215. const parser = new EasySAXParser();
  216. let style = {};
  217. parser.on('textNode', (text) => {
  218. result.push({
  219. style: Object.assign({}, style),
  220. text: text
  221. });
  222. });
  223. parser.on('startNode', (elemName, getAttr, isTagEnd, getStrNode) => {// eslint-disable-line no-unused-vars
  224. switch (elemName) {
  225. case 'strong':
  226. style.bold = true;
  227. break;
  228. case 'emphasis':
  229. style.italic = true;
  230. break;
  231. case 'center':
  232. style.center = true;
  233. break;
  234. }
  235. });
  236. parser.on('endNode', (elemName, isTagStart, getStrNode) => {// eslint-disable-line no-unused-vars
  237. switch (elemName) {
  238. case 'strong':
  239. style.bold = false;
  240. break;
  241. case 'emphasis':
  242. style.italic = false;
  243. break;
  244. case 'center':
  245. style.center = false;
  246. break;
  247. }
  248. });
  249. parser.parse(`<p>${s}</p>`);
  250. return result;
  251. }
  252. splitToSlogi(word) {
  253. let result = [];
  254. const glas = new Set(['а', 'А', 'о', 'О', 'и', 'И', 'е', 'Е', 'ё', 'Ё', 'э', 'Э', 'ы', 'Ы', 'у', 'У', 'ю', 'Ю', 'я', 'Я']);
  255. const soglas = new Set([
  256. 'б', 'в', 'г', 'д', 'ж', 'з', 'й', 'к', 'л', 'м', 'н', 'п', 'р', 'с', 'т', 'ф', 'х', 'ц', 'ч', 'ш', 'щ',
  257. 'Б', 'В', 'Г', 'Д', 'Ж', 'З', 'Й', 'К', 'Л', 'М', 'Н', 'П', 'Р', 'С', 'Т', 'Ф', 'Х', 'Ч', 'Ц', 'Ш', 'Щ'
  258. ]);
  259. const znak = new Set(['ь', 'Ь', 'ъ', 'Ъ', 'й', 'Й']);
  260. const alpha = new Set([...glas, ...soglas, ...znak]);
  261. let slog = '';
  262. let slogLen = 0;
  263. const len = word.length;
  264. word += ' ';
  265. for (let i = 0; i < len; i++) {
  266. slog += word[i];
  267. if (alpha.has(word[i]))
  268. slogLen++;
  269. if (slogLen > 1 && i < len - 2 && (
  270. //гласная, а следом не 2 согласные буквы
  271. (glas.has(word[i]) && !(soglas.has(word[i + 1]) &&
  272. soglas.has(word[i + 2])) && alpha.has(word[i + 1]) && alpha.has(word[i + 2])
  273. ) ||
  274. //предыдущая не согласная буква, текущая согласная, а следом согласная и согласная|гласная буквы
  275. (alpha.has(word[i - 1]) && !soglas.has(word[i - 1]) &&
  276. soglas.has(word[i]) && soglas.has(word[i + 1]) &&
  277. (glas.has(word[i + 2]) || soglas.has(word[i + 2])) &&
  278. alpha.has(word[i + 1]) && alpha.has(word[i + 2])
  279. ) ||
  280. //мягкий или твердый знак или Й
  281. (znak.has(word[i]) && alpha.has(word[i + 1]) && alpha.has(word[i + 2])) ||
  282. (word[i] == '-')
  283. ) &&
  284. //нельзя оставлять окончания на ь, ъ, й
  285. !(znak.has(word[i + 2]) && !alpha.has(word[i + 3]))
  286. ) {
  287. result.push(slog);
  288. slog = '';
  289. slogLen = 0;
  290. }
  291. }
  292. if (slog)
  293. result.push(slog);
  294. return result;
  295. }
  296. parsePara(paraIndex) {
  297. const para = this.para[paraIndex];
  298. if (!this.force &&
  299. para.parsed &&
  300. para.parsed.w === this.w &&
  301. para.parsed.p === this.p &&
  302. para.parsed.wordWrap === this.wordWrap &&
  303. para.parsed.font === this.font
  304. )
  305. return para.parsed;
  306. const parsed = {
  307. w: this.w,
  308. p: this.p,
  309. wordWrap: this.wordWrap,
  310. font: this.font,
  311. };
  312. const lines = []; /* array of
  313. {
  314. begin: Number,
  315. end: Number,
  316. first: Boolean,
  317. last: Boolean,
  318. parts: array of {
  319. style: {bold: Boolean, italic: Boolean, center: Boolean},
  320. text: String,
  321. }
  322. }*/
  323. let parts = this.splitToStyle(para.text);
  324. let line = {begin: para.offset, parts: []};
  325. let partText = '';//накапливаемый кусок со стилем
  326. let str = '';//измеряемая строка
  327. let prevStr = '';
  328. let prevW = 0;
  329. let j = 0;//номер строки
  330. let style = {};
  331. let ofs = 0;
  332. // тут начинается самый замес, перенос по слогам и стилизация
  333. for (const part of parts) {
  334. const words = part.text.split(' ');
  335. style = part.style;
  336. let sp1 = '';
  337. let sp2 = '';
  338. for (let i = 0; i < words.length; i++) {
  339. const word = words[i];
  340. ofs += word.length + (i < words.length - 1 ? 1 : 0);
  341. if (word == '' && i > 0 && i < words.length - 1)
  342. continue;
  343. str += sp1 + word;
  344. let p = (j == 0 ? parsed.p : 0);
  345. let w = this.measureText(str, style) + p;
  346. let wordTail = word;
  347. if (w > parsed.w) {
  348. if (parsed.wordWrap) {//по слогам
  349. let slogi = this.splitToSlogi(word);
  350. if (slogi.length > 1) {
  351. let s = prevStr + sp1;
  352. let ss = sp1;
  353. let pw;
  354. const slogiLen = slogi.length;
  355. for (let k = 0; k < slogiLen - 1; k++) {
  356. let slog = slogi[0];
  357. let ww = this.measureText(s + slog + (slog[slog.length - 1] == '-' ? '' : '-'), style) + p;
  358. if (ww <= parsed.w) {
  359. s += slog;
  360. ss += slog;
  361. } else
  362. break;
  363. pw = ww;
  364. slogi.shift();
  365. }
  366. if (pw) {
  367. prevW = pw;
  368. partText += ss + (ss[ss.length - 1] == '-' ? '' : '-');
  369. wordTail = slogi.join('');
  370. }
  371. }
  372. }
  373. if (partText != '')
  374. line.parts.push({style, text: partText});
  375. if (line.parts.length) {//корявенько, коррекция при переносе, отрефакторить не вышло
  376. let t = line.parts[line.parts.length - 1].text;
  377. if (t[t.length - 1] == ' ') {
  378. line.parts[line.parts.length - 1].text = t.trimRight();
  379. prevW -= this.measureText(' ', style);
  380. }
  381. }
  382. line.end = para.offset + ofs - wordTail.length - 1;
  383. if (line.end - line.begin < 0)
  384. console.error(`Parse error, empty line in paragraph ${paraIndex}`);
  385. line.width = prevW;
  386. line.first = (j == 0);
  387. line.last = false;
  388. lines.push(line);
  389. line = {begin: line.end + 1, parts: []};
  390. partText = '';
  391. sp2 = '';
  392. str = wordTail;
  393. j++;
  394. }
  395. prevStr = str;
  396. partText += sp2 + wordTail;
  397. sp1 = ' ';
  398. sp2 = ' ';
  399. prevW = w;
  400. }
  401. if (partText != '')
  402. line.parts.push({style, text: partText});
  403. partText = '';
  404. }
  405. if (line.parts.length) {//корявенько, коррекция при переносе
  406. let t = line.parts[line.parts.length - 1].text;
  407. if (t[t.length - 1] == ' ') {
  408. line.parts[line.parts.length - 1].text = t.trimRight();
  409. prevW -= this.measureText(' ', style);
  410. }
  411. line.end = para.offset + para.length - 1;
  412. if (line.end - line.begin < 0)
  413. console.error(`Parse error, empty line in paragraph ${paraIndex}`);
  414. line.width = prevW;
  415. line.first = (j == 0);
  416. line.last = true;
  417. lines.push(line);
  418. } else {//подстраховка
  419. if (lines.length) {
  420. line = lines[lines.length - 1];
  421. const end = para.offset + para.length - 1;
  422. if (line.end != end)
  423. console.error(`Parse error, wrong end in paragraph ${paraIndex}`);
  424. line.end = end;
  425. }
  426. }
  427. parsed.lines = lines;
  428. para.parsed = parsed;
  429. return parsed;
  430. }
  431. findLineIndex(bookPos, lines) {
  432. let result = undefined;
  433. //дихотомия
  434. let first = 0;
  435. let last = lines.length - 1;
  436. while (first < last) {
  437. let mid = first + Math.floor((last - first)/2);
  438. if (bookPos <= lines[mid].end)
  439. last = mid;
  440. else
  441. first = mid + 1;
  442. }
  443. if (last >= 0) {
  444. if (bookPos >= lines[last].begin && bookPos <= lines[last].end)
  445. result = last;
  446. }
  447. return result;
  448. }
  449. getLines(bookPos, n) {
  450. const result = [];
  451. let paraIndex = this.findParaIndex(bookPos);
  452. if (paraIndex === undefined)
  453. return result;
  454. if (n > 0) {
  455. let parsed = this.parsePara(paraIndex);
  456. let i = this.findLineIndex(bookPos, parsed.lines);
  457. if (i === undefined)
  458. return result;
  459. while (n > 0) {
  460. result.push(parsed.lines[i]);
  461. i++;
  462. if (i >= parsed.lines.length) {
  463. paraIndex++;
  464. if (paraIndex < this.para.length)
  465. parsed = this.parsePara(paraIndex);
  466. else
  467. return result;
  468. i = 0;
  469. }
  470. n--;
  471. }
  472. } else if (n < 0) {
  473. n = -n;
  474. let parsed = this.parsePara(paraIndex);
  475. let i = this.findLineIndex(bookPos, parsed.lines);
  476. if (i === undefined)
  477. return result;
  478. while (n > 0) {
  479. result.push(parsed.lines[i]);
  480. i--;
  481. if (i < 0) {
  482. paraIndex--;
  483. if (paraIndex >= 0)
  484. parsed = this.parsePara(paraIndex);
  485. else
  486. return result;
  487. i = parsed.lines.length - 1;
  488. }
  489. n--;
  490. }
  491. }
  492. return result;
  493. }
  494. }