Skip to content

Commit

Permalink
Added sticky selection hook.
Browse files Browse the repository at this point in the history
  • Loading branch information
chung-leong committed Apr 17, 2019
1 parent cecc705 commit 88b3ba7
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 1 deletion.
3 changes: 2 additions & 1 deletion index.js
Expand Up @@ -7,7 +7,7 @@ export default {
plant: plant,

use: use,
memo: memo,
memo: memo,
};

export * from './options';
Expand All @@ -16,3 +16,4 @@ export * from './hooks';
export * from './async-rendering-cycle';
export * from './async-rendering-interrupted';
export * from './async-save-buffer';
export * from './sticky-selection';
57 changes: 57 additions & 0 deletions sticky-selection.js
@@ -0,0 +1,57 @@
import { useEffect } from 'react';

function useStickySelection(inputRefs) {
if (!(inputRefs instanceof Array)) {
inputRefs = [ inputRefs ];
}
var inputs = inputRefs.map(function(inputRef) {
var node = inputRef.current;
if (node) {
return {
node: node,
value: node.value,
start: node.selectionStart,
end: node.selectionEnd,
};
}
});

useEffect(function() {
inputs.forEach(function(input) {
if (input) {
var node = input.node;
var previous = input.value;
var current = node.value;
if (previous !== current) {
var start = findNewPosition(input.start, previous, current);
var end = findNewPosition(input.end, previous, current);
if (typeof(start) === 'number' && typeof(end) === 'number') {
node.selectionStart = start;
node.selectionEnd = end;
}
}
}
});
});
}

function findNewPosition(index, previous, current) {
if (typeof(index) === 'number') {
if (typeof(previous) === 'string' && typeof(current) === 'string') {
var before = previous.substr(0, index);
var index1 = current.indexOf(before);
if (index1 !== -1) {
return index1 + before.length;
}
var after = previous.substr(index);
var index2 = current.lastIndexOf(after);
if (index2 !== -1) {
return index2;
}
}
}
}

export {
useStickySelection
};

0 comments on commit 88b3ba7

Please sign in to comment.