]> git.openstreetmap.org Git - nominatim-ui.git/blob - src/lib/stores.js
Replace map store with global map state (#291)
[nominatim-ui.git] / src / lib / stores.js
1 import { writable } from 'svelte/store';
2 import { untrack } from 'svelte';
3 import { identifyLinkInQuery } from './helpers.js';
4
5 export const results_store = writable();
6 export const last_api_request_url_store = writable();
7 export const error_store = writable();
8 export const page = writable();
9
10
11 /**
12  * Update the global page state.
13  *
14  * When called without a parameter, then the current window.location is
15  * parsed and the page state is set accordingly. Otherwise the page state
16  * is set from the parameters. 'pagename' is the overall subpage (without
17  * .html extension). 'params' must be an URLSearchParams object and contain
18  * the requested query parameters. It may also be omitted completely for a
19  * link without query parameters.
20  */
21 const default_pagename = Nominatim_Config.Reverse_Only ? 'reverse' : 'search';
22 const pagenames = [
23   default_pagename,
24   'reverse',
25   'details',
26   'deletable',
27   'polygons',
28   'status',
29   'about'
30 ];
31
32 export function refresh_page(pagename, params) {
33   if (typeof pagename === 'undefined') {
34     pagename = window.location.pathname.replace('.html', '').replace(/^.*\//, '');
35
36     if (!pagenames.includes(pagename)) pagename = default_pagename;
37
38     params = new URLSearchParams(window.location.search);
39   } else {
40     if (!pagenames.includes(pagename)) pagename = default_pagename;
41
42     if (typeof params === 'undefined') {
43       params = new URLSearchParams();
44     }
45
46     let param_str = params.toString();
47     if (param_str) {
48       param_str = '?' + param_str;
49     }
50     let new_url = pagename + '.html' + param_str;
51
52     if (window.location.protocol.match(/^http/)) {
53       window.history.pushState([], '', new_url);
54     } else {
55       window.location.href = new_url;
56     }
57   }
58
59   if (pagename === 'search' && params.has('q')) {
60     const arrTypeAndId = identifyLinkInQuery(params.get('q'));
61     if (arrTypeAndId instanceof Array) {
62       pagename = 'details';
63       params = new URLSearchParams();
64       params.set('osmtype', arrTypeAndId[0]);
65       params.set('osmid', arrTypeAndId[1]);
66     }
67   }
68
69   untrack(() => {
70     page.set({ tab: pagename, params: params });
71     last_api_request_url_store.set(null);
72     error_store.set(null);
73   });
74 }