BookParser.js 17 KB

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