File: page_manager.js

package info (click to toggle)
chromium 138.0.7204.157-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,864 kB
  • sloc: cpp: 34,936,859; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,967; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (316 lines) | stat: -rw-r--r-- 8,867 bytes parent folder | download | duplicates (6)
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
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import {assert} from 'chrome://resources/js/assert.js';
import {FocusOutlineManager} from 'chrome://resources/js/focus_outline_manager.js';

import {Page} from './page.js';

/**
 * PageManager contains a list of root Page objects and handles "navigation"
 * by showing and hiding these pages. On initial load, PageManager can use
 * the path to open the correct hierarchy of pages.
 */
export class PageManager {
  constructor() {
    /**
     * True if page is served from a dialog.
     * @type {boolean}
     */
    this.isDialog = false;

    /**
     * Root pages. Maps lower-case page names to the respective page object.
     * @type {!Map<string, !Page>}
     */
    this.registeredPages = new Map();

    /**
     * Observers will be notified when opening and closing overlays.
     * @private {!Array<!PageManagerObserver>}
     */
    this.observers_ = [];

    /** @private {?Page} */
    this.defaultPage_ = null;
  }

  /**
   * Initializes the complete page.
   * @param {Page} defaultPage The page to be shown when no
   *     page is specified in the path.
   */
  initialize(defaultPage) {
    this.defaultPage_ = defaultPage;

    FocusOutlineManager.forDocument(document);
  }

  /**
   * Registers new page.
   * @param {!Page} page Page to register.
   */
  register(page) {
    this.registeredPages.set(page.name.toLowerCase(), page);
    page.addEventListener(
        'page-hash-changed',
        e => this.onPageHashChanged_(/** @type {!CustomEvent} */ (e)));
    page.initializePage();
  }

  /**
   * Unregisters an existing page.
   * @param {!Page} page Page to unregister.
   */
  unregister(page) {
    this.registeredPages.delete(page.name.toLowerCase());
  }

  /**
   * Shows the default page.
   * @param {boolean=} opt_updateHistory If we should update the history after
   *     showing the page (defaults to true).
   */
  showDefaultPage(opt_updateHistory) {
    assert(
        this.defaultPage_ instanceof Page,
        'PageManager must be initialized with a default page.');
    this.showPageByName(this.defaultPage_.name, opt_updateHistory);
  }

  /**
   * Shows a registered page.
   * @param {string} pageName Page name.
   * @param {boolean=} opt_updateHistory If we should update the history after
   *     showing the page (defaults to true).
   * @param {Object=} opt_propertyBag An optional bag of properties including
   *     replaceState (if history state should be replaced instead of pushed).
   *     hash (a hash state to attach to the page).
   */
  showPageByName(pageName, opt_updateHistory, opt_propertyBag) {
    opt_updateHistory = opt_updateHistory !== false;
    opt_propertyBag = opt_propertyBag || {};

    // Find the currently visible root-level page.
    let rootPage = null;
    for (const page of this.registeredPages.values()) {
      if (page.visible && !page.parentPage) {
        rootPage = page;
        break;
      }
    }

    // Find the target page.
    let targetPage = this.registeredPages.get(pageName.toLowerCase());
    if (!targetPage) {
      targetPage = this.defaultPage_;
    }

    pageName = targetPage.name.toLowerCase();
    const targetPageWasVisible = targetPage.visible;

    // Notify pages if they will be hidden.
    this.registeredPages.forEach(page => {
      if (page.name !== pageName && !this.isAncestorOfPage(page, targetPage)) {
        page.willHidePage();
      }
    });

    // Update the page's hash.
    targetPage.hash = opt_propertyBag.hash || '';

    // Update visibilities to show only the hierarchy of the target page.
    this.registeredPages.forEach(page => {
      page.visible =
          page.name === pageName || this.isAncestorOfPage(page, targetPage);
    });

    // Update the history and current location.
    if (opt_updateHistory) {
      this.updateHistoryState_(!!opt_propertyBag.replaceState);
    }

    // Update focus if any other control was focused on the previous page,
    // or the previous page is not known.
    if (document.activeElement !== document.body &&
        (!rootPage || rootPage.pageDiv.contains(document.activeElement))) {
      targetPage.focus();
    }

    // Notify pages if they were shown.
    this.registeredPages.forEach(page => {
      if (!targetPageWasVisible &&
          (page.name === pageName || this.isAncestorOfPage(page, targetPage))) {
        page.didShowPage();
      }
    });

    // If the target page was already visible, notify it that its hash
    // changed externally.
    if (targetPageWasVisible) {
      targetPage.didChangeHash();
    }

    // Update the document title. Do this after didShowPage was called, in
    // case a page decides to change its title.
    this.updateTitle_();
  }

  /**
   * Returns the name of the page from the current path.
   * @return {string} Name of the page specified by the current path.
   */
  getPageNameFromPath() {
    const path = location.pathname;
    if (path.length <= 1) {
      return this.defaultPage_.name;
    }

    // Skip starting slash and remove trailing slash (if any).
    return path.slice(1).replace(/\/$/, '');
  }

  /**
   * Gets the level of the page. Root pages (e.g., BrowserOptions) are at
   * level 0.
   * @return {number} How far down this page is from the root page.
   */
  getNestingLevel(page) {
    let level = 0;
    let parent = page.parentPage;
    while (parent) {
      level++;
      parent = parent.parentPage;
    }
    return level;
  }

  /**
   * Checks whether one page is an ancestor of the other page in terms of
   * subpage nesting.
   * @param {Page} potentialAncestor Potential ancestor.
   * @param {Page} potentialDescendent Potential descendent.
   * @return {boolean} True if |potentialDescendent| is nested under
   *     |potentialAncestor|.
   */
  isAncestorOfPage(potentialAncestor, potentialDescendent) {
    let parent = potentialDescendent.parentPage;
    while (parent) {
      if (parent === potentialAncestor) {
        return true;
      }
      parent = parent.parentPage;
    }
    return false;
  }

  /**
   * Called when a page's hash changes. If the page is the topmost visible
   * page, the history state is updated.
   * @param {!CustomEvent} e
   */
  onPageHashChanged_(e) {
    const page = /** @type {!Page} */ (e.target);
    if (page === this.getTopmostVisiblePage()) {
      this.updateHistoryState_(false);
    }
  }

  /**
   * @param {!PageManagerObserver} observer The observer to register.
   */
  addObserver(observer) {
    this.observers_.push(observer);
  }

  /**
   * Returns the topmost visible page.
   * @return {Page}
   * @private
   */
  getTopmostVisiblePage() {
    for (const page of this.registeredPages.values()) {
      if (page.visible) {
        return page;
      }
    }

    return null;
  }

  /**
   * Updates the title to the title of the current page, or of the topmost
   * visible page with a non-empty title.
   * @private
   */
  updateTitle_() {
    let page = this.getTopmostVisiblePage();
    while (page) {
      if (page.title) {
        for (let i = 0; i < this.observers_.length; ++i) {
          this.observers_[i].updateTitle(page.title);
        }
        return;
      }
      page = page.parentPage;
    }
  }

  /**
   * Constructs a new path to push onto the history stack, using observers
   * to update the history.
   * @param {boolean} replace If true, handlers should replace the current
   *     history event rather than create new ones.
   * @private
   */
  updateHistoryState_(replace) {
    if (this.isDialog) {
      return;
    }

    const page = this.getTopmostVisiblePage();
    let path = window.location.pathname + window.location.hash;
    if (path) {
      // Remove trailing slash.
      path = path.slice(1).replace(/\/(?:#|$)/, '');
    }

    // If the page is already in history (the user may have clicked the same
    // link twice, or this is the initial load), do nothing.
    const newPath = (page === this.defaultPage_ ? '' : page.name) + page.hash;
    if (path === newPath) {
      return;
    }

    for (let i = 0; i < this.observers_.length; ++i) {
      this.observers_[i].updateHistory(newPath, replace);
    }
  }

  /** @return {!PageManager} */
  static getInstance() {
    return instance || (instance = new PageManager());
  }
}

/** @type {?PageManager} */
let instance = null;

/**
 * An observer of PageManager.
 */
export class PageManagerObserver {
  /**
   * Called when a new title should be set.
   * @param {string} title The title to set.
   */
  updateTitle(title) {}

  /**
   * Called when a page is navigated to.
   * @param {string} path The path of the page being visited.
   * @param {boolean} replace If true, allow no history events to be created.
   */
  updateHistory(path, replace) {}
}