-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathfreefocus.js
399 lines (327 loc) · 10.1 KB
/
freefocus.js
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
/*
Freefocus 0.11.2
Copyright (c) 2013-2016 Ilia Ablamonov. Licensed under the MIT license.
*/
(function () {
'use strict';
// ==================== Public ===============================================
var freefocus = window.freefocus = {
move: move,
getDimensions: getDimensions,
populateDimensionsCache: populateDimensionsCache,
invalidateDimensionsCache: invalidateDimensionsCache,
setHint: setHint,
clearHint: clearHint,
// Will be set later in code
configuration: undefined
};
function getDimensions(element) {
if (!element) {
console.error('Can\'t get freefocus dimensions for nothing');
return { left: 0, top: 0, width: 0, height: 0 };
}
var box = getElementBox(element, true, false);
return {
left: box.x1,
top: box.y1,
width: box.x2 - box.x1,
height: box.y2 - box.y1
};
}
function populateDimensionsCache(element) {
if (!element) {
console.error('Can\'t populate freefocus cache for nothing');
return;
}
getElementBox(element, true, true);
}
function invalidateDimensionsCache(element) {
if (!element) {
console.error('Can\'t invalidate freefocus cache for nothing');
return;
}
delete element.freefocusDimensions;
}
function clearHint(element) {
if (!element) {
console.error('Can\'t clear freefocus hint for nothing');
return;
}
for (var move in directions) {
element.removeAttribute('data-nav-' + move);
}
}
function setHint(element, hint, overwrite) {
if (!element) {
console.error('Can\'t set freefocus hints for nothing');
return;
}
for (var move in hint) {
if (overwrite !== false || !element.getAttribute('data-nav-' + move)) {
element.setAttribute('data-nav-' + move, hint[move]);
}
}
}
function move(fromElement, direction, candidatesFn) {
var target;
if (!fromElement) {
console.error('Can\'t move freefocus from nothing');
return target;
}
if (!directions[direction]) {
console.error('Unknown freefocus direction "' + direction + '"');
return target;
}
if (!candidatesFn) {
console.error('Can\'t move freefocus without candidates function');
return target;
}
updateFocusPoint(fromElement, direction, configuration.cache);
var targets = findTargetsFromHint(fromElement, direction, candidatesFn);
if (targets) {
if (targets.length <= 1) {
// If targets is empty, return nothing, it's the result of a `none` hint
target = targets[0];
} else {
// Find the nearest target from ones set by hint
var targetsFn = function () { return targets; };
target = findNearestTarget(fromElement, direction, targetsFn);
}
} else {
// If no hint found, find the nearest target from all available candidates
target = findNearestTarget(fromElement, direction, candidatesFn);
}
if (target) {
moveFocusPoint(target, direction, configuration.cache);
}
return target;
}
var directions = {
left: {
toUnified: function (coords) {
return { fwd: -coords.x, ort: -coords.y };
},
fromUnified: function (coords) {
return { x: -coords.fwd, y: -coords.ort };
}
},
right: {
toUnified: function (coords) {
return { fwd: coords.x, ort: coords.y };
},
fromUnified: function (coords) {
return { x: coords.fwd, y: coords.ort };
}
},
up: {
toUnified: function (coords) {
return { fwd: -coords.y, ort: coords.x };
},
fromUnified: function (coords) {
return { x: coords.ort, y: -coords.fwd };
}
},
down: {
toUnified: function (coords) {
return { fwd: coords.y, ort: -coords.x };
},
fromUnified: function (coords) {
return { x: -coords.ort, y: coords.fwd };
}
}
};
var hintSources = [
function (el, direction) {
return el.getAttribute('data-nav-' + direction);
}
];
var configuration = freefocus.configuration = {
maxDistance: Infinity,
cache: false,
directions: directions,
hintSources: hintSources
};
// ==================== Private ==============================================
var focusPoint = {
freefocusId: -1
};
function findTargetsFromHint(element, direction, candidatesFn) {
var hint = firstMatch(hintSources, function (source) {
var hint = source(element, direction);
return hint && hint.trim();
});
if (hint) {
hint = hint.trim();
}
if (!hint) {
return undefined;
}
if (hint === 'none') {
// Empty set => no movement
return [];
}
// Allow to set explicit order by enumerating selectors
return firstMatch(hint.split(/\s*;\s*/), function (hintSelector) {
if (!hintSelector) {
// A `hint` with a trailing `;` creates an empty hintSelector.
return undefined;
}
var candidates = candidatesFn(hintSelector);
if (!candidates.length) {
// Avoid firstMatch ending with an empty array
return undefined;
}
return candidates;
});
}
function findNearestTarget(fromElement, direction, candidatesFn) {
var fromBox = boxInDirection(getElementBox(fromElement, configuration.cache, configuration.cache), direction);
var candidates = candidatesFn();
var minDistance = configuration.maxDistance;
var target;
for (var i = 0, len = candidates.length; i < len; i++) {
var candidate = candidates[i];
// Skip currently focused element
if (candidate === fromElement) {
continue;
}
var toBox = boxInDirection(getElementBox(candidate, configuration.cache, configuration.cache), direction);
// Skip elements that are not in the direction of movement
if (toBox.fwd1 < fromBox.fwd2) {
continue;
}
var dist = distance(fromBox, toBox);
if (dist < minDistance) {
target = candidate;
minDistance = dist;
}
}
return target;
}
function distance(fromBox, toBox) {
var fromPoint = focusPoint.updatedInDirection;
var toPoint = {
fwd: toBox.fwd1,
ort: bound(fromPoint.ort, toBox.ort1, toBox.ort2)
};
var fwdDist = Math.abs(toPoint.fwd - fromPoint.fwd);
var ortDist = Math.abs(toPoint.ort - fromPoint.ort);
// The Euclidian distance between the current focus point position and
// its potential position in the candidate.
// If the two positions have the same coordinate on the axis orthogonal
// to the navigation direction, dotDist is forced to 0 in order to favor
// elements in direction of navigation
var dotDist;
if (toPoint.ort === fromPoint.ort) {
dotDist = 0;
} else {
dotDist = Math.sqrt(fwdDist * fwdDist + ortDist * ortDist);
}
// The overlap between the opposing edges of currently focused element and the candidate.
// Elements are rewarded for having high overlap with the currently focused element.
var overlap = boxOverlap(fromBox, toBox);
return dotDist + fwdDist + 2 * ortDist - Math.sqrt(overlap);
}
function boxOverlap(box1, box2) {
var orts = {
ort1: box1.ort1,
ort2: box1.ort2
};
if (box2.ort1 > orts.ort1)
orts.ort1 = box2.ort1;
if (box2.ort2 < orts.ort2)
orts.ort2 = box2.ort2;
var result = orts.ort2 - orts.ort1;
if (result < 0)
result = 0;
return result;
}
function computeElementBox(el) {
var rect = el.getBoundingClientRect();
return {
x1: rect.left,
y1: rect.top,
x2: rect.right,
y2: rect.bottom
};
}
function getElementBox(element, readCache, writeCache) {
var box;
if (readCache) {
box = element.freefocusDimensions;
}
if (!box) {
box = computeElementBox(element);
}
if (writeCache) {
element.freefocusDimensions = box;
}
return box;
}
function boxInDirection(box, direction) {
var p1 = directions[direction].toUnified({ x: box.x1, y: box.y1 });
var p2 = directions[direction].toUnified({ x: box.x2, y: box.y2 });
return {
fwd1: Math.min(p1.fwd, p2.fwd),
ort1: Math.min(p1.ort, p2.ort),
fwd2: Math.max(p1.fwd, p2.fwd),
ort2: Math.max(p1.ort, p2.ort)
};
}
function boxCoordsToClient(coords, box) {
return {
x: coords.x + box.x1,
y: coords.y + box.y1
};
}
function clientCoordsToBox(coords, box) {
return {
x: coords.x - box.x1,
y: coords.y - box.y1
};
}
function updateFocusPoint(element, direction, cache) {
var box = getElementBox(element, cache, cache);
// If the element wasn't focused by freefocus, calculate it
if (!element.freefocusId || element.freefocusId !== focusPoint.elementId) {
focusPoint.elementId = assignId(element);
focusPoint.box = {
x: (box.x2 - box.x1) / 2,
y: (box.y2 - box.y1) / 2
};
}
focusPoint.updatedInDirection = directions[direction].toUnified(boxCoordsToClient(focusPoint.box, box));
focusPoint.updatedInDirection.fwd = boxInDirection(box, direction).fwd2;
}
function moveFocusPoint(element, direction, cache) {
var box = getElementBox(element, cache, cache);
// Hold reference only for numeric id instead of a full DOM node
focusPoint.elementId = assignId(element);
var boxInDir = boxInDirection(box, direction);
var movedInDirection = {
fwd: boxInDir.fwd1,
ort: bound(focusPoint.updatedInDirection.ort, boxInDir.ort1, boxInDir.ort2)
};
focusPoint.box = clientCoordsToBox(directions[direction].fromUnified(movedInDirection), box);
}
// ==================== Utilities ============================================
function bound(val, min, max) {
return Math.min(Math.max(val, min), max);
}
function firstMatch(array, fn) {
for (var i = 0, len = array.length; i < len; i++) {
var result = fn(array[i]);
if (result) {
return result;
}
}
}
var lastElementId = 0;
function assignId(element) {
var elementId = element.freefocusId;
if (!elementId) {
elementId = element.freefocusId = ++lastElementId;
}
return elementId;
}
})();