Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

66
LINES

< > BotCompany Repo | #1016456 // EditRecorder - records text edits compactly

JavaX fragment (include)

sclass EREvent {
}

sclass ERText extends EREvent {
  int startIndex, endIndex;
  S text;
}

sclass ERCaret extends EREvent  {
  int pos;
} 

sclass EditRecorder {
  VF1<EREvent> onEvent;
  
  *() {}
  *(VF1<EREvent> *onEvent) {}
  
  // editor state
  S text = "";
  int caret;
  
  // update the text
  void update(S newText) {
    text = unnull(text);
    newText = unnull(newText);
    S a = text, b = newText;
    int i = lCommonPrefix(a, b);
    a = substring(a, i);
    b = substring(b, i);
    int j = lCommonSuffix(a, b);
    a = substring(a, 0, l(a)-j);
    b = substring(b, 0, l(b)-j);
    
    // Now differing part remains in a and b;
    // i and j give length of unchanged beginning+end
    
    if (empty(a) && empty(b)) ret;

    ERText change = nu(ERText, startIndex := i, endIndex := i+l(a), text := b);

    // Verify the change we made
    assertEquals(newText, replayTextEdit(change, text));
    text = newText;
    
    onEvent(change);
  }
  
  void updateCaret(int pos) {
    if (pos != caret) {
      onEvent(nu(ERCaret, +pos));
      caret = pos;
    }
  }
  
  void onEvent(EREvent e) {
    callF(onEvent, e);
  }
  
  static S replayTextEdit(ERText change, S text) {
    if (change == null) ret text;
    ret substring(text, 0, change.startIndex)
      + change.text
      + substring(text, change.endIndex);
  }
}

download  show line numbers  debug dex  old transpilations   

Travelled to 14 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, irmadwmeruwu, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #1016456
Snippet name: EditRecorder - records text edits compactly
Eternal ID of this version: #1016456/7
Text MD5: 5d1fc7c5ff4adbf53271eafd03b9ec28
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2018-06-18 22:14:22
Source code size: 1408 bytes / 66 lines
Pitched / IR pitched: No / No
Views / Downloads: 470 / 1011
Version history: 6 change(s)
Referenced in: #1034167 - Standard Classes + Interfaces (LIVE, continuation of #1003674)