|
42 | 42 | .on('blur', inactive);
|
43 | 43 | }
|
44 | 44 |
|
| 45 | + function refToHeader (itemRef) { |
| 46 | + return $('.tocify-item[data-unique=' + itemRef + ']').closest('.tocify-header'); |
| 47 | + } |
| 48 | + |
| 49 | + function sortDescending (obj2, obj1) { |
| 50 | + var s1 = parseInt(obj1.id.replace(/[^\d]/g, ''), 10); |
| 51 | + var s2 = parseInt(obj2.id.replace(/[^\d]/g, ''), 10); |
| 52 | + return s1 === s2 ? 0 : s1 < s2 ? -1 : 1; |
| 53 | + } |
| 54 | + |
| 55 | + function resetHeaderLocations () { |
| 56 | + var headers = $(".tocify-header").sort(sortDescending); |
| 57 | + $.each(headers, function (index, item) { |
| 58 | + $(item).insertBefore($("#toc ul:first-child")); |
| 59 | + }); |
| 60 | + } |
| 61 | + |
45 | 62 | function search (event) {
|
46 | 63 | var sections = $('section, #toc .tocify-header');
|
47 | 64 |
|
|
53 | 70 |
|
54 | 71 | if (this.value) {
|
55 | 72 | sections.hide();
|
56 |
| - var results = index.search(this.value); |
| 73 | + // results are sorted by score in descending order |
| 74 | + var tmpResults = index.search(this.value); |
| 75 | + var results = []; |
| 76 | + |
| 77 | + // remove low score matches |
| 78 | + $.each(tmpResults, function (index, item) { |
| 79 | + if (item.score >= 0.0001) results.push(item); |
| 80 | + }); |
| 81 | + |
57 | 82 | if (results.length) {
|
| 83 | + lastRef = null; |
| 84 | + resetHeaderLocations(); |
58 | 85 | $.each(results, function (index, item) {
|
59 |
| - $('#section-' + item.ref).show(); |
60 |
| - $('.tocify-item[data-unique=' + item.ref + ']').closest('.tocify-header').show(); |
| 86 | + var itemRef = item.ref; |
| 87 | + $('#section-' + itemRef).show(); |
| 88 | + // headers must be repositioned in the DOM |
| 89 | + var closestHeader = refToHeader(itemRef); |
| 90 | + if (lastRef) { |
| 91 | + refToHeader(lastRef).insertBefore(closestHeader); |
| 92 | + } |
| 93 | + closestHeader.show(); |
| 94 | + lastRef = itemRef; |
61 | 95 | });
|
| 96 | + |
| 97 | + // position first element. it wasn't positioned above if len > 1 |
| 98 | + if (results.length > 1) { |
| 99 | + var firstRef = results[0].ref; |
| 100 | + var secondRef = results[1].ref |
| 101 | + refToHeader(firstRef).insertBefore(refToHeader(secondRef)); |
| 102 | + } |
| 103 | + |
62 | 104 | highlight.call(this);
|
63 | 105 | } else {
|
64 | 106 | sections.show();
|
|
0 commit comments