trretretret commited on
Commit
f7ed3df
·
1 Parent(s): 3607be8

fix getcurrentline

Browse files
Files changed (2) hide show
  1. public/esltool.js +1 -1
  2. public/utils.js +43 -5
public/esltool.js CHANGED
@@ -93,7 +93,7 @@ function getSelectedText() {
93
 
94
  function ask(prompt) {
95
 
96
- let currentLineString = utils.getCurrentBlock(document.activeElement);
97
  let selectText = window.getSelection().toString();
98
  prompt=`${prompt} **${selectText.length >= 1 ? selectText : currentLineString}** `
99
  utils.displayMarkdown(prompt+'...');
 
93
 
94
  function ask(prompt) {
95
 
96
+ let currentLineString = utils.getCurrentLineString(document.activeElement);
97
  let selectText = window.getSelection().toString();
98
  prompt=`${prompt} **${selectText.length >= 1 ? selectText : currentLineString}** `
99
  utils.displayMarkdown(prompt+'...');
public/utils.js CHANGED
@@ -360,11 +360,49 @@ const utils = {
360
 
361
  return currentLine;
362
  },
363
- getCurrentBlock(elem) {
364
- let text=elem.textContent;
365
- const blocks = text.split(/(\n{2,})/);
366
- return blocks[blocks.indexOf('\n\n') + 1];
367
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
368
 
369
  ,
370
  isEditableElement: function isEditableElement(element) {
 
360
 
361
  return currentLine;
362
  },
363
+ getCursorPosition(element) {
364
+ let caretOffset = 0;
365
+ const doc = element.ownerDocument || element.document;
366
+ const win = doc.defaultView || doc.parentWindow;
367
+ let sel;
368
+ if (typeof win.getSelection != "undefined") {
369
+ sel = win.getSelection();
370
+ if (sel.rangeCount > 0) {
371
+ const range = sel.getRangeAt(0);
372
+ const preCaretRange = range.cloneRange();
373
+ preCaretRange.selectNodeContents(element);
374
+ preCaretRange.setEnd(range.endContainer, range.endOffset);
375
+ caretOffset = preCaretRange.toString().length;
376
+ }
377
+ } else if ((sel = doc.selection) && sel.type != "Control") {
378
+ const textRange = sel.createRange();
379
+ const preCaretTextRange = doc.body.createTextRange();
380
+ preCaretTextRange.moveToElementText(element);
381
+ preCaretTextRange.setEndPoint("EndToEnd", textRange);
382
+ caretOffset = preCaretTextRange.text.length;
383
+ }
384
+ console.log('caretOffset:',caretOffset);
385
+ return caretOffset;
386
+ }
387
+
388
+ ,
389
+ getCurrentBlock(elem) {
390
+ elem=elem.parentElement;
391
+ const cursorPosition = this.getCursorPosition(elem);
392
+ const text = elem.innerText;
393
+
394
+ let blockStart = text.indexOf('\n\n', cursorPosition) + 2;
395
+ if (blockStart === 1) { // if we're at the start of the text
396
+ blockStart = 0;
397
+ }
398
+
399
+ let blockEnd = text.lastIndexOf('\n\n', cursorPosition);
400
+ if (blockEnd === -1) { // if we're at the end of the text
401
+ blockEnd = text.length;
402
+ }
403
+
404
+ return text.substring(blockStart, blockEnd).trim();
405
+ }
406
 
407
  ,
408
  isEditableElement: function isEditableElement(element) {