-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsmart-menu.js
110 lines (87 loc) · 2.73 KB
/
smart-menu.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
(function() {
function createMenu(containerId, menuJson) {
$("#"+containerId).html('').append(
$("<nav>").append(
createSubmenu(menuJson, [])
)
);
}
function createSubmenu(menuJson, parents) {
var ul = $("<ul>");
var elems = [];
_.each(menuJson, function(value, key) {
if (key === "_root") return; // special key, used for parent, ignore here.
if (typeof value !== "string")
elems.push([
getSelectionCount(getLinkId(parents, key)),
createLinkElement(parents, key, value._root, true)
.append(createSubmenu(value, parents.concat(key)))
]); //submenu
else
elems.push([
getSelectionCount(getLinkId(parents, key)),
createLinkElement(parents, key, value, false)
]); // link
});
// Order by simple popularity (click count)
elems.sort(function(a, b) { return b[0] - a[0]; });
return ul.append(_.map(elems, function(e) { return e[1]; }));
}
function createLinkElement(parents, text, href, submenu) {
var link = $("<a>")
.on("click")
.attr("href", getHref(href))
.html( (window.smartMenuDebug ? getSelectionCount(getLinkId(parents, text)) + " - " : "") +
text +
(submenu ? " <span class='caret'></a></li>" : "")
);
attachSelectionHandler(link, text, parents, submenu);
return $("<li>").append(link);
}
function getHref(uri) {
return (uri ? uri : "javascript:;");
}
function attachSelectionHandler(link, text, parents, submenu) {
link.on("click", function(e) {
var linkId = getLinkId(parents, text);
console.log("Clicked: ", linkId);
handleClickOn(text, parents);
// return false;
});
}
function handleClickOn(link, parents) {
if (link)
incrementSelectionCount(getLinkId(parents, link));
if (parents.length)
handleClickOn(parents.pop(), parents);
}
function getLinkId(parents, link) {
var sep = ">>";
var links = _.map(parents.concat(link), function(l) {
return l.replace(/\s+/g, "_").replace(/(^_+|\W|_+$)/g, "");
});
return links
.join(">>")
.toLowerCase();
}
function getSelectionCount(linkId) {
var selections = getLocal("SmartMenu", {});
return (selections[linkId] || 0);
}
function incrementSelectionCount(linkId) {
var selections = getLocal("SmartMenu", {});
selections[linkId] = (selections[linkId] || 0) + 1;
setLocal("SmartMenu", selections);
}
function getLocal(key, defaultVal) {
try {
return JSON.parse(localStorage[key]);
} catch (ex) {
return defaultVal;
}
}
function setLocal(key, value) {
localStorage[key] = JSON.stringify(value);
}
window.smartMenu = createMenu;
})();