aboutsummaryrefslogtreecommitdiff
path: root/src/client/util/History.ts
blob: 0df0ec33778304e82a17e4d302835abd16d0fcfe (plain)
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
/* eslint-disable no-use-before-define */
/* eslint-disable no-empty */
/* eslint-disable no-param-reassign */
import { Doc } from '../../fields/Doc';
import { OmitKeys, ClientUtils } from '../../ClientUtils';
import { DocServer } from '../DocServer';
import { DashboardView } from '../views/DashboardView';

export namespace HistoryUtil {
    export interface DocInitializerList {
        [key: string]: string | number;
    }

    export interface DocUrl {
        type: 'doc';
        docId: string;
        initializers?: {
            [docId: string]: DocInitializerList;
        };
        safe?: boolean;
        readonly?: boolean;
        nro?: boolean;
        sharing?: boolean;
    }

    export type ParsedUrl = DocUrl;

    // const handlers: ((state: ParsedUrl | null) => void)[] = [];
    function onHistory(e: PopStateEvent) {
        if (window.location.pathname !== '/home') {
            const url = (e.state as ParsedUrl) || parseUrl(window.location);
            if (url) {
                switch (url.type) {
                    case 'doc':
                        onDocUrl(url);
                        break;
                    default:
                }
            }
        }
        // for (const handler of handlers) {
        //     handler(e.state);
        // }
    }

    let _lastStatePush = 0;
    export function pushState(state: ParsedUrl) {
        if (Date.now() - _lastStatePush > 1000) {
            history.pushState(state, '', createUrl(state));
        }
        _lastStatePush = Date.now();
    }

    export function replaceState(state: ParsedUrl) {
        history.replaceState(state, '', createUrl(state));
    }

    function copyState(state: ParsedUrl): ParsedUrl {
        return JSON.parse(JSON.stringify(state));
    }

    export function getState(): ParsedUrl {
        const state = copyState(history.state);
        if (state) {
            state.initializers = state.initializers || {};
        }
        return state ?? { initializers: {} };
    }

    // export function addHandler(handler: (state: ParsedUrl | null) => void) {
    //     handlers.push(handler);
    // }

    // export function removeHandler(handler: (state: ParsedUrl | null) => void) {
    //     const index = handlers.indexOf(handler);
    //     if (index !== -1) {
    //         handlers.splice(index, 1);
    //     }
    // }

    const parsers: { [type: string]: (pathname: string[], opts: URLSearchParams) => ParsedUrl | undefined } = {};
    const stringifiers: { [type: string]: (state: ParsedUrl) => string } = {};

    type ParserValue = true | 'none' | 'json' | ((value: string) => string | null | (string | null)[]);

    type Parser = {
        [key: string]: ParserValue;
    };

    function addParser(type: string, requiredFields: Parser, optionalFields: Parser, customParser?: (pathname: string[], opts: URLSearchParams, current: ParsedUrl) => ParsedUrl | null | undefined) {
        function parseValue(parser: ParserValue, value: string | (string | null)[] | null | undefined) {
            if (value === undefined || value === null) {
                return value;
            }
            if (Array.isArray(value)) {
            } else if (parser === true || parser === 'json') {
                value = value === 'undefined' ? undefined : JSON.parse(value);
            } else if (parser === 'none') {
            } else {
                value = parser(value);
            }
            return value;
        }
        parsers[type] = (pathname, opts) => {
            const current: DocUrl & { [key: string]: null | (string | null)[] | string } = { type: 'doc', docId: '' };
            for (const required in requiredFields) {
                if (!opts.has(required)) {
                    return undefined;
                }
                const parser = requiredFields[required];
                const value = parseValue(parser, opts.get(required));
                if (value !== null && value !== undefined) {
                    current[required] = value;
                }
            }
            for (const opt in optionalFields) {
                if (!opts.has(opt)) {
                    continue;
                }
                const parser = optionalFields[opt];
                const value = parseValue(parser, opts.get(opt));
                if (value !== undefined) {
                    current[opt] = value;
                }
            }
            if (customParser) {
                const val = customParser(pathname, opts, current);
                if (val === null) {
                    return undefined;
                }
                if (val === undefined) {
                    return current;
                }
                return val;
            }
            return current;
        };
    }

    function addStringifier(type: string, keys: string[], customStringifier?: (state: ParsedUrl, current: string) => string) {
        stringifiers[type] = state => {
            let path = ClientUtils.prepend(`/${type}`);
            if (customStringifier) {
                path = customStringifier(state, path);
            }
            const queryObj = OmitKeys(state, keys).extract;
            const query = new URLSearchParams();
            Object.keys(queryObj).forEach(key => {
                query.set(key, queryObj[key] === null ? '' : JSON.stringify(queryObj[key]));
            });
            const qstr = query.toString();
            return path + (qstr ? `?${qstr}` : '');
        };
    }

    addParser('doc', {}, { readonly: true, initializers: true, nro: true, sharing: true }, (pathname, opts, current) => {
        if (pathname.length === 2) {
            current.initializers = current.initializers || {};
            const docId = pathname[1];
            current.docId = docId;
        }
        return undefined;
    });
    addStringifier('doc', ['initializers', 'readonly', 'nro'], (state, current) => `${current}/${state.docId}`);

    export function parseUrl(location: Location | URL): ParsedUrl | undefined {
        const pathname = location.pathname.substring(1);
        const { search } = location;
        const opts = new URLSearchParams(search);
        const pathnameSplit = pathname.split('/');

        const type = pathnameSplit[0];

        if (type in parsers) {
            return parsers[type](pathnameSplit, opts);
        }

        return undefined;
    }

    export function createUrl(params: ParsedUrl): string {
        if (params.type in stringifiers) {
            return stringifiers[params.type](params);
        }
        return '';
    }

    export async function initDoc(id: string, initializer: DocInitializerList) {
        const doc = await DocServer.GetRefField(id);
        if (!(doc instanceof Doc)) {
            return;
        }
        Doc.assign(doc, initializer);
    }

    async function onDocUrl(url: DocUrl) {
        const field = await DocServer.GetRefField(url.docId);
        const init = url.initializers;
        if (init) {
            await Promise.all(Object.keys(init).map(id => initDoc(id, init[id])));
        }
        if (field instanceof Doc) {
            DashboardView.openDashboard(field, true);
        }
    }

    window.onpopstate = onHistory;
}