BookParser.js 17 KB

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