File size: 2,415 Bytes
cf0f72e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/*
 * Copyright (c) 2017 Martin Donath <martin.donath@squidfunk.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy
 * of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING, SOFTWARE
 * DISTRIBUTED UNDER THE LICENSE IS DISTRIBUTED ON AN "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
 * SEE THE LICENSE FOR THE SPECIFIC LANGUAGE GOVERNING PERMISSIONS AND
 * LIMITATIONS UNDER THE LICENSE.
 */

import inspect from "../util/inspect"

/* ----------------------------------------------------------------------------
 * Class
 * ------------------------------------------------------------------------- */

export class Context {

  /**
   * Create a context stack
   *
   * This is necessary for easy querying of iframes.
   *
   * @constructor
   *
   * @property {string} context_ - Context stack
   */
  constructor() {
    this.stack_ = []
  }

  /**
   * Push a context onto the stack
   *
   * @param {HTMLIFrameElement} context - Context
   *
   * @return {number} Size of stack
   */
  push(context) {
    if (!(context instanceof this.window.Element))
      throw new TypeError(`Invalid element: ${inspect(context)}`)
    if (!(context instanceof this.window.HTMLIFrameElement))
      throw new TypeError(`Invalid element type: ${inspect(context.tagName)}`)

    /* Push context onto stack */
    return this.stack_.push(context)
  }

  /**
   * Pop a context from the stack
   *
   * @return {HTMLIFrameElement} Context
   */
  pop() {
    return this.stack_.pop()
  }

  /**
   * Retrieve window object for current context
   *
   * @return {Window} Window object
   */
  get window() {
    return this.stack_.length
      ? this.stack_[this.stack_.length - 1].contentWindow
      : window
  }

  /**
   * Retrieve document object for current context
   *
   * @return {Document} Document object
   */
  get document() {
    return this.stack_.length
      ? this.stack_[this.stack_.length - 1].contentDocument
      : document
  }
}

/* ----------------------------------------------------------------------------
 * Export default context
 * ------------------------------------------------------------------------- */

const _ = new Context()
export { _ as default }