BookParser.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888
  1. import he from 'he';
  2. import sax from '../../../../server/core/BookConverter/sax';
  3. import {sleep} from '../../../share/utils';
  4. const maxImageLineCount = 100;
  5. export default class BookParser {
  6. constructor(settings) {
  7. if (settings) {
  8. this.showInlineImagesInCenter = settings.showInlineImagesInCenter;
  9. }
  10. // defaults
  11. this.p = 30;// px, отступ параграфа
  12. this.w = 300;// px, ширина страницы
  13. this.wordWrap = false;// перенос по слогам
  14. //заглушка
  15. this.measureText = (text, style) => {// eslint-disable-line no-unused-vars
  16. return text.length*20;
  17. };
  18. }
  19. async parse(data, callback) {
  20. if (!callback)
  21. callback = () => {};
  22. callback(0);
  23. if (data.indexOf('<FictionBook') < 0) {
  24. throw new Error('Неверный формат файла');
  25. }
  26. //defaults
  27. let fb2 = {
  28. firstName: '',
  29. middleName: '',
  30. lastName: '',
  31. bookTitle: '',
  32. };
  33. let path = '';
  34. let tag = '';
  35. let center = false;
  36. let bold = false;
  37. let italic = false;
  38. let space = 0;
  39. let inPara = false;
  40. this.binary = {};
  41. let binaryId = '';
  42. let binaryType = '';
  43. let dimPromises = [];
  44. let paraIndex = -1;
  45. let paraOffset = 0;
  46. let para = []; /*array of
  47. {
  48. index: Number,
  49. offset: Number, //сумма всех length до этого параграфа
  50. length: Number, //длина text без тегов
  51. text: String, //текст параграфа с вложенными тегами
  52. cut: Boolean, //параграф - кандидат на сокрытие (cutEmptyParagraphs)
  53. addIndex: Number, //индекс добавляемого пустого параграфа (addEmptyParagraphs)
  54. }
  55. */
  56. const getImageDimensions = (binaryId, binaryType, data) => {
  57. return new Promise (async(resolve, reject) => {
  58. const i = new Image();
  59. let resolved = false;
  60. i.onload = () => {
  61. resolved = true;
  62. this.binary[binaryId] = {
  63. w: i.width,
  64. h: i.height,
  65. type: binaryType,
  66. data
  67. };
  68. resolve();
  69. };
  70. i.onerror = (e) => {
  71. reject(e);
  72. };
  73. i.src = `data:${binaryType};base64,${data}`;
  74. await sleep(30*1000);
  75. if (!resolved)
  76. reject('Не удалось получить размер изображения');
  77. });
  78. };
  79. const getExternalImageDimensions = (src) => {
  80. return new Promise (async(resolve, reject) => {
  81. const i = new Image();
  82. let resolved = false;
  83. i.onload = () => {
  84. resolved = true;
  85. this.binary[src] = {
  86. w: i.width,
  87. h: i.height,
  88. };
  89. resolve();
  90. };
  91. i.onerror = (e) => {
  92. reject(e);
  93. };
  94. i.src = src;
  95. await sleep(30*1000);
  96. if (!resolved)
  97. reject('Не удалось получить размер изображения');
  98. });
  99. };
  100. const newParagraph = (text, len, addIndex) => {
  101. paraIndex++;
  102. let p = {
  103. index: paraIndex,
  104. offset: paraOffset,
  105. length: len,
  106. text: text,
  107. cut: (!addIndex && (len == 1 && text[0] == ' ')),
  108. addIndex: (addIndex ? addIndex : 0),
  109. };
  110. para[paraIndex] = p;
  111. paraOffset += p.length;
  112. };
  113. const growParagraph = (text, len) => {
  114. if (paraIndex < 0) {
  115. newParagraph(' ', 1);
  116. growParagraph(text, len);
  117. return;
  118. }
  119. let p = para[paraIndex];
  120. //добавление пустых (addEmptyParagraphs) параграфов
  121. if (p.length == 1 && p.text[0] == ' ' && len > 0) {
  122. paraIndex--;
  123. paraOffset -= p.length;
  124. for (let i = 0; i < 2; i++) {
  125. newParagraph(' ', 1, i + 1);
  126. }
  127. paraIndex++;
  128. p.index = paraIndex;
  129. p.offset = paraOffset;
  130. para[paraIndex] = p;
  131. paraOffset += p.length;
  132. }
  133. paraOffset -= p.length;
  134. //параграф оказался непустой
  135. if (p.length == 1 && p.text[0] == ' ' && len > 0) {
  136. p.length = 0;
  137. p.text = p.text.substr(1);
  138. p.cut = (len == 1 && text[0] == ' ');
  139. }
  140. p.length += len;
  141. p.text += text;
  142. para[paraIndex] = p;
  143. paraOffset += p.length;
  144. };
  145. const onStartNode = (elemName, tail) => {// eslint-disable-line no-unused-vars
  146. if (elemName == '?xml')
  147. return;
  148. tag = elemName;
  149. path += '/' + elemName;
  150. if (tag == 'binary') {
  151. let attrs = sax.getAttrsSync(tail);
  152. binaryType = (attrs['content-type'] && attrs['content-type'].value ? attrs['content-type'].value : '');
  153. if (binaryType == 'image/jpeg' || binaryType == 'image/png')
  154. binaryId = (attrs.id.value ? attrs.id.value : '');
  155. }
  156. if (tag == 'image') {
  157. let attrs = sax.getAttrsSync(tail);
  158. if (attrs.href && attrs.href.value) {
  159. const href = attrs.href.value;
  160. if (href[0] == '#') {//local
  161. if (inPara && !this.showInlineImagesInCenter)
  162. growParagraph(`<image-inline href="${href}"></image-inline>`, 0);
  163. else
  164. newParagraph(`<image href="${href}">${' '.repeat(maxImageLineCount)}</image>`, maxImageLineCount);
  165. if (inPara && this.showInlineImagesInCenter)
  166. newParagraph(' ', 1);
  167. } else {//external
  168. dimPromises.push(getExternalImageDimensions(href));
  169. newParagraph(`<image href="${href}">${' '.repeat(maxImageLineCount)}</image>`, maxImageLineCount);
  170. }
  171. }
  172. }
  173. if (path.indexOf('/fictionbook/body') == 0) {
  174. if (tag == 'title') {
  175. newParagraph(' ', 1);
  176. bold = true;
  177. center = true;
  178. }
  179. if (tag == 'section') {
  180. newParagraph(' ', 1);
  181. }
  182. if (tag == 'emphasis' || tag == 'strong') {
  183. growParagraph(`<${tag}>`, 0);
  184. }
  185. if ((tag == 'p' || tag == 'empty-line' || tag == 'v')) {
  186. newParagraph(' ', 1);
  187. if (tag == 'p')
  188. inPara = true;
  189. }
  190. if (tag == 'subtitle') {
  191. newParagraph(' ', 1);
  192. bold = true;
  193. }
  194. if (tag == 'epigraph') {
  195. italic = true;
  196. space += 1;
  197. }
  198. if (tag == 'poem') {
  199. newParagraph(' ', 1);
  200. }
  201. if (tag == 'text-author') {
  202. newParagraph(' ', 1);
  203. space += 1;
  204. }
  205. }
  206. };
  207. const onEndNode = (elemName) => {// eslint-disable-line no-unused-vars
  208. if (tag == elemName) {
  209. if (tag == 'binary') {
  210. binaryId = '';
  211. }
  212. if (path.indexOf('/fictionbook/body') == 0) {
  213. if (tag == 'title') {
  214. bold = false;
  215. center = false;
  216. }
  217. if (tag == 'emphasis' || tag == 'strong') {
  218. growParagraph(`</${tag}>`, 0);
  219. }
  220. if (tag == 'p') {
  221. inPara = false;
  222. }
  223. if (tag == 'subtitle') {
  224. bold = false;
  225. }
  226. if (tag == 'epigraph') {
  227. italic = false;
  228. space -= 1;
  229. }
  230. if (tag == 'stanza') {
  231. newParagraph(' ', 1);
  232. }
  233. if (tag == 'text-author') {
  234. space -= 1;
  235. }
  236. }
  237. path = path.substr(0, path.length - tag.length - 1);
  238. let i = path.lastIndexOf('/');
  239. if (i >= 0) {
  240. tag = path.substr(i + 1);
  241. } else {
  242. tag = path;
  243. }
  244. }
  245. };
  246. const onTextNode = (text) => {// eslint-disable-line no-unused-vars
  247. text = he.decode(text);
  248. text = text.replace(/>/g, '&gt;');
  249. text = text.replace(/</g, '&lt;');
  250. if (text != ' ' && text.trim() == '')
  251. text = text.trim();
  252. if (text == '')
  253. return;
  254. text = text.replace(/[\t\n\r]/g, ' ');
  255. switch (path) {
  256. case '/fictionbook/description/title-info/author/first-name':
  257. fb2.firstName = text;
  258. break;
  259. case '/fictionbook/description/title-info/author/middle-name':
  260. fb2.middleName = text;
  261. break;
  262. case '/fictionbook/description/title-info/author/last-name':
  263. fb2.lastName = text;
  264. break;
  265. case '/fictionbook/description/title-info/genre':
  266. fb2.genre = text;
  267. break;
  268. case '/fictionbook/description/title-info/date':
  269. fb2.date = text;
  270. break;
  271. case '/fictionbook/description/title-info/book-title':
  272. fb2.bookTitle = text;
  273. break;
  274. case '/fictionbook/description/title-info/id':
  275. fb2.id = text;
  276. break;
  277. }
  278. if (path.indexOf('/fictionbook/description/title-info/annotation') == 0) {
  279. if (!fb2.annotation)
  280. fb2.annotation = '';
  281. if (tag != 'annotation')
  282. fb2.annotation += `<${tag}>${text}</${tag}>`;
  283. else
  284. fb2.annotation += text;
  285. }
  286. let tOpen = (center ? '<center>' : '');
  287. tOpen += (bold ? '<strong>' : '');
  288. tOpen += (italic ? '<emphasis>' : '');
  289. tOpen += (space ? `<space w="${space}">` : '');
  290. let tClose = (space ? '</space>' : '');
  291. tClose += (italic ? '</emphasis>' : '');
  292. tClose += (bold ? '</strong>' : '');
  293. tClose += (center ? '</center>' : '');
  294. if (path.indexOf('/fictionbook/body/title') == 0) {
  295. growParagraph(`${tOpen}${text}${tClose}`, text.length);
  296. }
  297. if (path.indexOf('/fictionbook/body/section') == 0) {
  298. switch (tag) {
  299. case 'p':
  300. growParagraph(`${tOpen}${text}${tClose}`, text.length);
  301. break;
  302. default:
  303. growParagraph(`${tOpen}${text}${tClose}`, text.length);
  304. }
  305. }
  306. if (binaryId) {
  307. dimPromises.push(getImageDimensions(binaryId, binaryType, text));
  308. }
  309. };
  310. const onProgress = async(prog) => {
  311. await sleep(1);
  312. callback(prog);
  313. };
  314. await sax.parse(data, {
  315. onStartNode, onEndNode, onTextNode, onProgress
  316. });
  317. if (dimPromises.length) {
  318. try {
  319. await Promise.all(dimPromises);
  320. } catch (e) {
  321. //
  322. }
  323. }
  324. this.fb2 = fb2;
  325. this.para = para;
  326. this.textLength = paraOffset;
  327. callback(100);
  328. await sleep(10);
  329. return {fb2};
  330. }
  331. findParaIndex(bookPos) {
  332. let result = undefined;
  333. //дихотомия
  334. let first = 0;
  335. let last = this.para.length - 1;
  336. while (first < last) {
  337. let mid = first + Math.floor((last - first)/2);
  338. if (bookPos <= this.para[mid].offset + this.para[mid].length - 1)
  339. last = mid;
  340. else
  341. first = mid + 1;
  342. }
  343. if (last >= 0) {
  344. const ofs = this.para[last].offset;
  345. if (bookPos >= ofs && bookPos < ofs + this.para[last].length)
  346. result = last;
  347. }
  348. return result;
  349. }
  350. splitToStyle(s) {
  351. let result = [];/*array of {
  352. style: {bold: Boolean, italic: Boolean, center: Boolean, space: Number},
  353. image: {local: Boolean, inline: Boolean, id: String},
  354. text: String,
  355. }*/
  356. let style = {};
  357. let image = {};
  358. const onTextNode = async(text) => {// eslint-disable-line no-unused-vars
  359. result.push({
  360. style: Object.assign({}, style),
  361. image,
  362. text
  363. });
  364. };
  365. const onStartNode = async(elemName, tail) => {// eslint-disable-line no-unused-vars
  366. switch (elemName) {
  367. case 'strong':
  368. style.bold = true;
  369. break;
  370. case 'emphasis':
  371. style.italic = true;
  372. break;
  373. case 'center':
  374. style.center = true;
  375. break;
  376. case 'space': {
  377. let attrs = sax.getAttrsSync(tail);
  378. if (attrs.w && attrs.w.value)
  379. style.space = attrs.w.value;
  380. break;
  381. }
  382. case 'image': {
  383. let attrs = sax.getAttrsSync(tail);
  384. if (attrs.href && attrs.href.value) {
  385. let id = attrs.href.value;
  386. let local = false;
  387. if (id[0] == '#') {
  388. id = id.substr(1);
  389. local = true;
  390. }
  391. image = {local, inline: false, id};
  392. }
  393. break;
  394. }
  395. case 'image-inline': {
  396. let attrs = sax.getAttrsSync(tail);
  397. if (attrs.href && attrs.href.value) {
  398. let id = attrs.href.value;
  399. let local = false;
  400. if (id[0] == '#') {
  401. id = id.substr(1);
  402. local = true;
  403. }
  404. result.push({
  405. style: Object.assign({}, style),
  406. image: {local, inline: true, id},
  407. text: ''
  408. });
  409. }
  410. break;
  411. }
  412. }
  413. };
  414. const onEndNode = async(elemName) => {// eslint-disable-line no-unused-vars
  415. switch (elemName) {
  416. case 'strong':
  417. style.bold = false;
  418. break;
  419. case 'emphasis':
  420. style.italic = false;
  421. break;
  422. case 'center':
  423. style.center = false;
  424. break;
  425. case 'space':
  426. style.space = 0;
  427. break;
  428. case 'image':
  429. image = {};
  430. break;
  431. case 'image-inline':
  432. break;
  433. }
  434. };
  435. sax.parseSync(s, {
  436. onStartNode, onEndNode, onTextNode
  437. });
  438. //длинные слова (или белиберду без пробелов) тоже разобьем
  439. const maxWordLength = this.maxWordLength;
  440. const parts = result;
  441. result = [];
  442. for (const part of parts) {
  443. let p = part;
  444. if (!p.image.id) {
  445. let i = 0;
  446. let spaceIndex = -1;
  447. while (i < p.text.length) {
  448. if (p.text[i] == ' ')
  449. spaceIndex = i;
  450. if (i - spaceIndex >= maxWordLength && i < p.text.length - 1 &&
  451. this.measureText(p.text.substr(spaceIndex + 1, i - spaceIndex), p.style) >= this.w - this.p) {
  452. result.push({style: p.style, image: p.image, text: p.text.substr(0, i + 1)});
  453. p = {style: p.style, image: p.image, text: p.text.substr(i + 1)};
  454. spaceIndex = -1;
  455. i = -1;
  456. }
  457. i++;
  458. }
  459. }
  460. result.push(p);
  461. }
  462. return result;
  463. }
  464. splitToSlogi(word) {
  465. let result = [];
  466. const glas = new Set(['а', 'А', 'о', 'О', 'и', 'И', 'е', 'Е', 'ё', 'Ё', 'э', 'Э', 'ы', 'Ы', 'у', 'У', 'ю', 'Ю', 'я', 'Я']);
  467. const soglas = new Set([
  468. 'б', 'в', 'г', 'д', 'ж', 'з', 'й', 'к', 'л', 'м', 'н', 'п', 'р', 'с', 'т', 'ф', 'х', 'ц', 'ч', 'ш', 'щ',
  469. 'Б', 'В', 'Г', 'Д', 'Ж', 'З', 'Й', 'К', 'Л', 'М', 'Н', 'П', 'Р', 'С', 'Т', 'Ф', 'Х', 'Ч', 'Ц', 'Ш', 'Щ'
  470. ]);
  471. const znak = new Set(['ь', 'Ь', 'ъ', 'Ъ', 'й', 'Й']);
  472. const alpha = new Set([...glas, ...soglas, ...znak]);
  473. let slog = '';
  474. let slogLen = 0;
  475. const len = word.length;
  476. word += ' ';
  477. for (let i = 0; i < len; i++) {
  478. slog += word[i];
  479. if (alpha.has(word[i]))
  480. slogLen++;
  481. if (slogLen > 1 && i < len - 2 && (
  482. //гласная, а следом не 2 согласные буквы
  483. (glas.has(word[i]) && !(soglas.has(word[i + 1]) &&
  484. soglas.has(word[i + 2])) && alpha.has(word[i + 1]) && alpha.has(word[i + 2])
  485. ) ||
  486. //предыдущая не согласная буква, текущая согласная, а следом согласная и согласная|гласная буквы
  487. (alpha.has(word[i - 1]) && !soglas.has(word[i - 1]) &&
  488. soglas.has(word[i]) && soglas.has(word[i + 1]) &&
  489. (glas.has(word[i + 2]) || soglas.has(word[i + 2])) &&
  490. alpha.has(word[i + 1]) && alpha.has(word[i + 2])
  491. ) ||
  492. //мягкий или твердый знак или Й
  493. (znak.has(word[i]) && alpha.has(word[i + 1]) && alpha.has(word[i + 2])) ||
  494. (word[i] == '-')
  495. ) &&
  496. //нельзя оставлять окончания на ь, ъ, й
  497. !(znak.has(word[i + 2]) && !alpha.has(word[i + 3]))
  498. ) {
  499. result.push(slog);
  500. slog = '';
  501. slogLen = 0;
  502. }
  503. }
  504. if (slog)
  505. result.push(slog);
  506. return result;
  507. }
  508. parsePara(paraIndex) {
  509. const para = this.para[paraIndex];
  510. if (!this.force &&
  511. para.parsed &&
  512. para.parsed.w === this.w &&
  513. para.parsed.p === this.p &&
  514. para.parsed.wordWrap === this.wordWrap &&
  515. para.parsed.maxWordLength === this.maxWordLength &&
  516. para.parsed.font === this.font &&
  517. para.parsed.cutEmptyParagraphs === this.cutEmptyParagraphs &&
  518. para.parsed.addEmptyParagraphs === this.addEmptyParagraphs &&
  519. para.parsed.showImages === this.showImages &&
  520. para.parsed.imageHeightLines === this.imageHeightLines
  521. )
  522. return para.parsed;
  523. const parsed = {
  524. w: this.w,
  525. p: this.p,
  526. wordWrap: this.wordWrap,
  527. maxWordLength: this.maxWordLength,
  528. font: this.font,
  529. cutEmptyParagraphs: this.cutEmptyParagraphs,
  530. addEmptyParagraphs: this.addEmptyParagraphs,
  531. showImages: this.showImages,
  532. imageHeightLines: this.imageHeightLines,
  533. visible: !(
  534. (this.cutEmptyParagraphs && para.cut) ||
  535. (para.addIndex > this.addEmptyParagraphs)
  536. )
  537. };
  538. const lines = []; /* array of
  539. {
  540. begin: Number,
  541. end: Number,
  542. first: Boolean,
  543. last: Boolean,
  544. parts: array of {
  545. style: {bold: Boolean, italic: Boolean, center: Boolean},
  546. image: {local: Boolean, inline: Boolean, id: String, imageLine: Number, lineCount: Number, paraIndex: Number},
  547. text: String,
  548. }
  549. }*/
  550. let parts = this.splitToStyle(para.text);
  551. let line = {begin: para.offset, parts: []};
  552. let partText = '';//накапливаемый кусок со стилем
  553. let str = '';//измеряемая строка
  554. let prevStr = '';//строка без крайнего слова
  555. let j = 0;//номер строки
  556. let style = {};
  557. let ofs = 0;//смещение от начала параграфа para.offset
  558. let imgW = 0;
  559. // тут начинается самый замес, перенос по слогам и стилизация, а также изображения
  560. for (const part of parts) {
  561. style = part.style;
  562. //изображения
  563. if (part.image.id && !part.image.inline) {
  564. parsed.visible = this.showImages;
  565. let bin = this.binary[part.image.id];
  566. if (!bin)
  567. bin = {h: 0, w: 0};
  568. let lineCount = this.imageHeightLines;
  569. const c = Math.ceil(bin.h/this.lineHeight);
  570. lineCount = (c < lineCount ? c : lineCount);
  571. let i = 0;
  572. for (; i < lineCount - 1; i++) {
  573. line.end = para.offset + ofs;
  574. line.first = (j == 0);
  575. line.last = false;
  576. line.parts.push({style, text: ' ', image: {
  577. local: part.image.local,
  578. inline: false,
  579. id: part.image.id,
  580. imageLine: i,
  581. lineCount,
  582. paraIndex
  583. }});
  584. lines.push(line);
  585. line = {begin: line.end + 1, parts: []};
  586. ofs++;
  587. j++;
  588. }
  589. line.first = (j == 0);
  590. line.last = true;
  591. line.parts.push({style, text: ' ',
  592. image: {local: part.image.local, inline: false, id: part.image.id, imageLine: i, lineCount, paraIndex}});
  593. continue;
  594. }
  595. if (part.image.id && part.image.inline && this.showImages) {
  596. const bin = this.binary[part.image.id];
  597. if (bin) {
  598. let imgH = (bin.h > this.fontSize ? this.fontSize : bin.h);
  599. imgW += bin.w*imgH/bin.h;
  600. line.parts.push({style, text: '',
  601. image: {local: part.image.local, inline: true, id: part.image.id}});
  602. }
  603. }
  604. let words = part.text.split(' ');
  605. let sp1 = '';
  606. let sp2 = '';
  607. for (let i = 0; i < words.length; i++) {
  608. const word = words[i];
  609. ofs += word.length + (i < words.length - 1 ? 1 : 0);
  610. if (word == '' && i > 0 && i < words.length - 1)
  611. continue;
  612. str += sp1 + word;
  613. let p = (j == 0 ? parsed.p : 0) + imgW;
  614. p = (style.space ? p + parsed.p*style.space : p);
  615. let w = this.measureText(str, style) + p;
  616. let wordTail = word;
  617. if (w > parsed.w && prevStr != '') {
  618. if (parsed.wordWrap) {//по слогам
  619. let slogi = this.splitToSlogi(word);
  620. if (slogi.length > 1) {
  621. let s = prevStr + sp1;
  622. let ss = sp1;
  623. let pw;
  624. const slogiLen = slogi.length;
  625. for (let k = 0; k < slogiLen - 1; k++) {
  626. let slog = slogi[0];
  627. let ww = this.measureText(s + slog + (slog[slog.length - 1] == '-' ? '' : '-'), style) + p;
  628. if (ww <= parsed.w) {
  629. s += slog;
  630. ss += slog;
  631. } else
  632. break;
  633. pw = ww;
  634. slogi.shift();
  635. }
  636. if (pw) {
  637. partText += ss + (ss[ss.length - 1] == '-' ? '' : '-');
  638. wordTail = slogi.join('');
  639. }
  640. }
  641. }
  642. if (partText != '')
  643. line.parts.push({style, text: partText});
  644. if (line.parts.length) {//корявенько, коррекция при переносе, отрефакторить не вышло
  645. let t = line.parts[line.parts.length - 1].text;
  646. if (t[t.length - 1] == ' ') {
  647. line.parts[line.parts.length - 1].text = t.trimRight();
  648. }
  649. }
  650. line.end = para.offset + ofs - wordTail.length - 1 - (i < words.length - 1 ? 1 : 0);
  651. if (line.end - line.begin < 0)
  652. console.error(`Parse error, empty line in paragraph ${paraIndex}`);
  653. line.first = (j == 0);
  654. line.last = false;
  655. lines.push(line);
  656. line = {begin: line.end + 1, parts: []};
  657. partText = '';
  658. sp2 = '';
  659. str = wordTail;
  660. imgW = 0;
  661. j++;
  662. }
  663. prevStr = str;
  664. partText += sp2 + wordTail;
  665. sp1 = ' ';
  666. sp2 = ' ';
  667. }
  668. if (partText != '')
  669. line.parts.push({style, text: partText});
  670. partText = '';
  671. }
  672. if (line.parts.length) {//корявенько, коррекция при переносе
  673. let t = line.parts[line.parts.length - 1].text;
  674. if (t[t.length - 1] == ' ') {
  675. line.parts[line.parts.length - 1].text = t.trimRight();
  676. }
  677. line.end = para.offset + para.length - 1;
  678. if (line.end - line.begin < 0)
  679. console.error(`Parse error, empty line in paragraph ${paraIndex}`);
  680. line.first = (j == 0);
  681. line.last = true;
  682. lines.push(line);
  683. } else {//подстраховка
  684. if (lines.length) {
  685. line = lines[lines.length - 1];
  686. const end = para.offset + para.length - 1;
  687. if (line.end != end)
  688. console.error(`Parse error, wrong end in paragraph ${paraIndex}`);
  689. line.end = end;
  690. }
  691. }
  692. parsed.lines = lines;
  693. para.parsed = parsed;
  694. return parsed;
  695. }
  696. findLineIndex(bookPos, lines) {
  697. let result = undefined;
  698. //дихотомия
  699. let first = 0;
  700. let last = lines.length - 1;
  701. while (first < last) {
  702. let mid = first + Math.floor((last - first)/2);
  703. if (bookPos <= lines[mid].end)
  704. last = mid;
  705. else
  706. first = mid + 1;
  707. }
  708. if (last >= 0) {
  709. if (bookPos >= lines[last].begin && bookPos <= lines[last].end)
  710. result = last;
  711. }
  712. return result;
  713. }
  714. getLines(bookPos, n) {
  715. let result = [];
  716. let paraIndex = this.findParaIndex(bookPos);
  717. if (paraIndex === undefined)
  718. return null;
  719. if (n > 0) {
  720. let parsed = this.parsePara(paraIndex);
  721. let i = this.findLineIndex(bookPos, parsed.lines);
  722. if (i === undefined)
  723. return null;
  724. while (n > 0) {
  725. if (parsed.visible) {
  726. result.push(parsed.lines[i]);
  727. n--;
  728. }
  729. i++;
  730. if (i >= parsed.lines.length) {
  731. paraIndex++;
  732. if (paraIndex < this.para.length)
  733. parsed = this.parsePara(paraIndex);
  734. else
  735. break;
  736. i = 0;
  737. }
  738. }
  739. } else if (n < 0) {
  740. n = -n;
  741. let parsed = this.parsePara(paraIndex);
  742. let i = this.findLineIndex(bookPos, parsed.lines);
  743. if (i === undefined)
  744. return null;
  745. while (n > 0) {
  746. if (parsed.visible) {
  747. result.push(parsed.lines[i]);
  748. n--;
  749. }
  750. i--;
  751. if (i < 0) {
  752. paraIndex--;
  753. if (paraIndex >= 0)
  754. parsed = this.parsePara(paraIndex);
  755. else
  756. break;
  757. i = parsed.lines.length - 1;
  758. }
  759. }
  760. }
  761. if (!result.length)
  762. result = null;
  763. return result;
  764. }
  765. }