/
router.js
545 lines (470 loc) · 14.7 KB
/
router.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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt
// route urls to their virtual pages
// re-route map (for rename)
frappe.provide("frappe.views");
frappe.re_route = { "#login": "" };
frappe.route_titles = {};
frappe.route_flags = {};
frappe.route_history = [];
frappe.view_factory = {};
frappe.view_factories = [];
frappe.route_options = null;
frappe.route_hooks = {};
$(window).on("hashchange", function (e) {
// v1 style routing, route is in hash
if (window.location.hash && !frappe.router.is_app_route(e.currentTarget.pathname)) {
let sub_path = frappe.router.get_sub_path(window.location.hash);
frappe.router.push_state(sub_path);
return false;
}
});
window.addEventListener("popstate", (e) => {
// forward-back button, just re-render based on current route
frappe.router.route();
e.preventDefault();
return false;
});
// routing v2, capture all clicks so that the target is managed with push-state
$("body").on("click", "a", function (e) {
let override = (route) => {
e.preventDefault();
frappe.set_route(route);
return false;
};
const target_element = e.currentTarget;
const href = target_element.getAttribute("href");
const is_on_same_host = target_element.hostname === window.location.hostname;
// click handled, but not by href
if (
target_element.getAttribute("onclick") || // has a handler
e.ctrlKey ||
e.metaKey || // open in a new tab
href === "#" // hash is home
) {
return;
}
if (href === "") {
return override("/app");
}
if (href && href.startsWith("#")) {
// target startswith "#", this is a v1 style route, so remake it.
return override(target_element.hash);
}
if (is_on_same_host && frappe.router.is_app_route(target_element.pathname)) {
// target has "/app, this is a v2 style route.
if (target_element.search) {
frappe.route_options = {};
let params = new URLSearchParams(target_element.search);
for (const [key, value] of params) {
frappe.route_options[key] = value;
}
}
return override(target_element.pathname + target_element.hash);
}
});
frappe.router = {
current_route: null,
routes: {},
factory_views: ["form", "list", "report", "tree", "print", "dashboard"],
list_views: [
"list",
"kanban",
"report",
"calendar",
"tree",
"gantt",
"dashboard",
"image",
"inbox",
"map",
],
list_views_route: {
list: "List",
kanban: "Kanban",
report: "Report",
calendar: "Calendar",
tree: "Tree",
gantt: "Gantt",
dashboard: "Dashboard",
image: "Image",
inbox: "Inbox",
file: "Home",
map: "Map",
},
layout_mapped: {},
is_app_route(path) {
// desk paths must begin with /app or doctype route
if (path.substr(0, 1) === "/") path = path.substr(1);
path = path.split("/");
if (path[0]) {
return path[0] === "app";
}
},
setup() {
// setup the route names by forming slugs of the given doctypes
for (let doctype of frappe.boot.user.can_read) {
this.routes[this.slug(doctype)] = { doctype: doctype };
}
if (frappe.boot.doctype_layouts) {
for (let doctype_layout of frappe.boot.doctype_layouts) {
this.routes[this.slug(doctype_layout.name)] = {
doctype: doctype_layout.document_type,
doctype_layout: doctype_layout.name,
};
}
}
},
async route() {
// resolve the route from the URL or hash
// translate it so the objects are well defined
// and render the page as required
if (!frappe.app) return;
let sub_path = this.get_sub_path();
if (this.re_route(sub_path)) return;
this.current_sub_path = sub_path;
this.current_route = await this.parse();
this.set_history(sub_path);
this.render();
this.set_title(sub_path);
this.trigger("change");
},
async parse(route) {
route = this.get_sub_path_string(route).split("/");
if (!route) return [];
route = $.map(route, this.decode_component);
this.set_route_options_from_url();
return await this.convert_to_standard_route(route);
},
async convert_to_standard_route(route) {
// /app/settings = ["Workspaces", "Settings"]
// /app/private/settings = ["Workspaces", "private", "Settings"]
// /app/user = ["List", "User"]
// /app/user/view/report = ["List", "User", "Report"]
// /app/user/view/tree = ["Tree", "User"]
// /app/user/user-001 = ["Form", "User", "user-001"]
// /app/user/user-001 = ["Form", "User", "user-001"]
// /app/event/view/calendar/default = ["List", "Event", "Calendar", "Default"]
let private_workspace = route[1] && `${route[1]}-${frappe.user.name.toLowerCase()}`;
if (frappe.workspaces[route[0]]) {
// public workspace
route = ["Workspaces", frappe.workspaces[route[0]].title];
} else if (route[0] == "private" && frappe.workspaces[private_workspace]) {
// private workspace
route = ["Workspaces", "private", frappe.workspaces[private_workspace].title];
} else if (this.routes[route[0]]) {
// route
route = await this.set_doctype_route(route);
}
return route;
},
doctype_route_exist(route) {
route = this.get_sub_path_string(route).split("/");
return this.routes[route[0]];
},
set_doctype_route(route) {
let doctype_route = this.routes[route[0]];
return frappe.model.with_doctype(doctype_route.doctype).then(() => {
// doctype route
let meta = frappe.get_meta(doctype_route.doctype);
if (route[1] && route[1] === "view" && route[2]) {
route = this.get_standard_route_for_list(
route,
doctype_route,
meta.force_re_route_to_default_view && meta.default_view
? meta.default_view
: null
);
} else if (route[1] && route[1] !== "view" && !route[2]) {
let docname = route[1];
if (route.length > 2) {
docname = route.slice(1).join("/");
}
route = ["Form", doctype_route.doctype, docname];
} else if (frappe.model.is_single(doctype_route.doctype)) {
route = ["Form", doctype_route.doctype, doctype_route.doctype];
} else if (meta.default_view) {
route = [
"List",
doctype_route.doctype,
this.list_views_route[meta.default_view.toLowerCase()],
];
} else {
route = ["List", doctype_route.doctype, "List"];
}
// reset the layout to avoid using incorrect views
this.doctype_layout = doctype_route.doctype_layout;
return route;
});
},
get_standard_route_for_list(route, doctype_route, default_view) {
let standard_route;
let _route = default_view || route[2] || "";
if (_route.toLowerCase() === "tree") {
standard_route = ["Tree", doctype_route.doctype];
} else {
let new_route = this.list_views_route[_route.toLowerCase()];
let re_route = route[2].toLowerCase() !== new_route.toLowerCase();
if (re_route) {
/**
* In case of force_re_route, the url of the route should change,
* if the _route and route[2] are different, it means there is a default_view
* with force_re_route enabled.
*
* To change the url, to the correct view, the route[2] is changed with default_view
*
* Eg: If default_view is set to Report with force_re_route enabled and user routes
* to List,
* route: [todo, view, list]
* default_view: report
*
* replaces the list to report and re-routes to the new route but should be replaced in
* the history since the list route should not exist in history as we are rerouting it to
* report
*/
frappe.route_flags.replace_route = true;
route[2] = _route.toLowerCase();
this.set_route(route);
}
standard_route = [
"List",
doctype_route.doctype,
this.list_views_route[_route.toLowerCase()],
];
// calendar / kanban / dashboard / folder
if (route[3]) standard_route.push(...route.slice(3, route.length));
}
return standard_route;
},
set_history() {
frappe.route_history.push(this.current_route);
frappe.ui.hide_open_dialog();
},
render() {
if (this.current_route[0]) {
this.render_page();
} else {
// Show home
frappe.views.pageview.show("");
}
},
render_page() {
// create the page generator (factory) object and call `show`
// if there is no generator, render the `Page` object
const route = this.current_route;
const factory = frappe.utils.to_title_case(route[0]);
if (route[1] && frappe.views[factory + "Factory"]) {
route[0] = factory;
// has a view generator, generate!
if (!frappe.view_factory[factory]) {
frappe.view_factory[factory] = new frappe.views[factory + "Factory"]();
}
frappe.view_factory[factory].show();
} else {
// show page
const route_name = frappe.utils.xss_sanitise(route[0]);
if (frappe.views.pageview) {
frappe.views.pageview.show(route_name);
}
}
},
re_route(sub_path) {
if (frappe.re_route[sub_path] !== undefined) {
// after saving a doc, for example,
// "new-doctype-1" and the renamed "TestDocType", both exist in history
// now if we try to go back,
// it doesn't allow us to go back to the one prior to "new-doctype-1"
// Hence if this check is true, instead of changing location hash,
// we just do a back to go to the doc previous to the "new-doctype-1"
const re_route_val = this.get_sub_path(frappe.re_route[sub_path]);
if (re_route_val === this.current_sub_path) {
window.history.back();
} else {
frappe.set_route(re_route_val);
}
return true;
}
},
set_title(sub_path) {
if (frappe.route_titles[sub_path]) {
frappe.utils.set_title(frappe.route_titles[sub_path]);
}
},
set_route() {
// set the route (push state) with given arguments
// example 1: frappe.set_route('a', 'b', 'c');
// example 2: frappe.set_route(['a', 'b', 'c']);
// example 3: frappe.set_route('a/b/c');
let route = Array.from(arguments);
return new Promise((resolve) => {
route = this.get_route_from_arguments(route);
route = this.convert_from_standard_route(route);
let sub_path = this.make_url(route);
// replace each # occurrences in the URL with encoded character except for last
// sub_path = sub_path.replace(/[#](?=.*[#])/g, "%23");
this.push_state(sub_path);
setTimeout(() => {
frappe.after_ajax &&
frappe.after_ajax(() => {
resolve();
});
}, 100);
}).finally(() => (frappe.route_flags = {}));
},
get_route_from_arguments(route) {
if (route.length === 1 && $.isArray(route[0])) {
// called as frappe.set_route(['a', 'b', 'c']);
route = route[0];
}
if (route.length === 1 && route[0] && route[0].includes("/")) {
// called as frappe.set_route('a/b/c')
route = $.map(route[0].split("/"), this.decode_component);
}
if (route && route[0] == "") {
route.shift();
}
if (route && ["desk", "app"].includes(route[0])) {
// we only need subpath, remove "app" (or "desk")
route.shift();
}
return route;
},
convert_from_standard_route(route) {
// ["List", "Sales Order"] => /sales-order
// ["Form", "Sales Order", "SO-0001"] => /sales-order/SO-0001
// ["Tree", "Account"] = /account/view/tree
const view = route[0] ? route[0].toLowerCase() : "";
let new_route = route;
if (view === "list") {
if (route[2] && route[2] !== "list" && !$.isPlainObject(route[2])) {
new_route = [this.slug(route[1]), "view", route[2].toLowerCase()];
// calendar / inbox / file folder
if (route[3]) new_route.push(...route.slice(3, route.length));
} else {
if ($.isPlainObject(route[2])) {
frappe.route_options = route[2];
}
new_route = [this.slug(route[1])];
}
} else if (view === "form") {
new_route = [this.slug(route[1])];
if (route[2]) {
// if not single
new_route.push(route[2]);
}
} else if (view === "tree") {
new_route = [this.slug(route[1]), "view", "tree"];
}
return new_route;
},
slug_parts(route) {
// slug doctype
// if app is part of the route, then first 2 elements are "" and "app"
if (route[0] && this.factory_views.includes(route[0].toLowerCase())) {
route[0] = route[0].toLowerCase();
route[1] = this.slug(route[1]);
}
return route;
},
make_url(params) {
let path_string = $.map(params, function (a) {
if ($.isPlainObject(a)) {
frappe.route_options = a;
return null;
} else {
return encodeURIComponent(String(a));
}
}).join("/");
let private_home = frappe.workspaces[`home-${frappe.user.name.toLowerCase()}`];
let default_page = private_home
? "private/home"
: frappe.workspaces["home"]
? "home"
: Object.keys(frappe.workspaces)[0];
return "/app/" + (path_string || default_page);
},
push_state(url) {
// change the URL and call the router
if (window.location.pathname !== url) {
// push/replace state so the browser looks fine
const method = frappe.route_flags.replace_route ? "replaceState" : "pushState";
history[method](null, null, url);
// now process the route
this.route();
}
},
get_sub_path_string(route) {
// return clean sub_path from hash or url
// supports both v1 and v2 routing
if (!route) {
route = window.location.pathname;
if (route.includes("app#")) {
// to support v1
route = window.location.hash;
}
}
return this.strip_prefix(route);
},
strip_prefix(route) {
if (route.substr(0, 1) == "/") route = route.substr(1); // for /app/sub
if (route.startsWith("app/")) route = route.substr(4); // for desk/sub
if (route == "app") route = route.substr(4); // for /app
if (route.substr(0, 1) == "/") route = route.substr(1);
if (route.substr(0, 1) == "#") route = route.substr(1);
if (route.substr(0, 1) == "!") route = route.substr(1);
return route;
},
get_sub_path(route) {
var sub_path = this.get_sub_path_string(route);
route = $.map(sub_path.split("/"), this.decode_component).join("/");
return route;
},
set_route_options_from_url() {
// set query parameters as frappe.route_options
let query_string = window.location.search;
if (!frappe.route_options) {
frappe.route_options = {};
}
let params = new URLSearchParams(query_string);
for (const [key, value] of params) {
frappe.route_options[key] = value;
}
},
decode_component(r) {
try {
return decodeURIComponent(r);
} catch (e) {
if (e instanceof URIError) {
// legacy: not sure why URIError is ignored.
return r;
} else {
throw e;
}
}
},
slug(name) {
return name.toLowerCase().replace(/ /g, "-");
},
};
// global functions for backward compatibility
frappe.get_route = () => frappe.router.current_route;
frappe.get_route_str = () => frappe.router.current_route.join("/");
frappe.set_route = function () {
return frappe.router.set_route.apply(frappe.router, arguments);
};
frappe.get_prev_route = function () {
if (frappe.route_history && frappe.route_history.length > 1) {
return frappe.route_history[frappe.route_history.length - 2];
} else {
return [];
}
};
frappe.set_re_route = function () {
var tmp = frappe.router.get_sub_path();
frappe.set_route.apply(null, arguments);
frappe.re_route[tmp] = frappe.router.get_sub_path();
};
frappe.has_route_options = function () {
return Boolean(Object.keys(frappe.route_options || {}).length);
};
frappe.utils.make_event_emitter(frappe.router);