File size: 2,892 Bytes
ae4627d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 | var Adjustor = {};
Adjustor.UP = 38;
Adjustor.DOWN = 40;
Adjustor.nudge = function (input, event, format){
// when replacing the nudged value, tells us where to start and
// how far to go (like substr(repl.start, repl.length))
var repl = { start: 0, length: 0 };
// record the original position of the cursor
var cursor = input.selectionStart;
// determine which direction we're nudging
var direction = event.keyCode;
if (direction != Adjustor.UP && direction != Adjustor.DOWN){
return;
}
// since we'll sometimes prevent the cursor from moving, we
// should always prevent the cursor from moving
event.preventDefault();
function parse(){
var value = input.value,
p = cursor,
start;
function isNumeric(value){
return !isNaN(parseInt(value));
}
while (start == undefined){
var left = isNumeric(value[p - 1]),
right = isNumeric(value[p]);
// if there's no digit left or right, bail
if (!left && !right){
return;
}
// if there's no digit left but a digit right, we've found our start
else if (!left && right){
start = p;
}
// if there's a digit left, regardless of a digit right, move left
else if (left){
p--;
}
}
var parsed = parseInt(value.substr(start));
// record the start and the length to replace this value later
repl.start = start;
repl.length = parsed.toString().length;
return parsed;
}
/**
* Replaces the currently matched substring with another value, based on
* the start and length found by parse() (i.e., call that first). Returns
* the new string.
*
* @param string
* @return string
*/
function replace(value){
var min = 0, max;
// determine the maximum value for this...value
if (format == Color.RGB){
max = 255;
} else {
// if we're looking at hue, then there will be no digits to the
// left of the start position
max = /\d/.test(input.value.substr(0, repl.start)) ? 100 : 359;
}
value = Math.max(min, Math.min(max, value));
var chunks = input.value.split("");
chunks.splice(repl.start, repl.length, value);
return chunks.join("");
}
/**
* Provides the offset to add to the current value, based on whether
* we're nudging up or down (which arrow key) and big or small (whether
* the Option key was being held).
*
* @return int
*/
function adjustment(){
return (direction == Adjustor.UP ? 1 : -1) * (event.altKey ? 10 : 1);
}
var parsed = parse();
if (parsed == undefined){
return;
}
input.value = replace(parsed + adjustment());
// put the cursor in the right spot
input.selectionStart = input.selectionEnd = cursor;
return input.value;
};
|