├── .gitignore ├── assets ├── native-inert-1.png ├── native-inert-2.png ├── native-inert-3.png ├── native-inert-4.png ├── polyfill-inert-1.png ├── polyfill-inert-2.png ├── polyfill-inert-3.png └── polyfill-inert-4.png ├── .npmignore ├── .babelrc ├── .clang-format ├── tsconfig.json ├── rollup.config.js ├── demo ├── x-a.js ├── x-b.js ├── x-trap-focus.js ├── ce.html └── index.html ├── .travis.yml ├── tslint.json ├── test ├── helpers │ └── fixture.js ├── index.html ├── shadow.js └── basic.js ├── package.json ├── README.md ├── LICENSE └── src └── blocking-elements.ts /.gitignore: -------------------------------------------------------------------------------- 1 | dist/** 2 | node_modules 3 | *.tgz 4 | -------------------------------------------------------------------------------- /assets/native-inert-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PolymerLabs/blocking-elements/HEAD/assets/native-inert-1.png -------------------------------------------------------------------------------- /assets/native-inert-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PolymerLabs/blocking-elements/HEAD/assets/native-inert-2.png -------------------------------------------------------------------------------- /assets/native-inert-3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PolymerLabs/blocking-elements/HEAD/assets/native-inert-3.png -------------------------------------------------------------------------------- /assets/native-inert-4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PolymerLabs/blocking-elements/HEAD/assets/native-inert-4.png -------------------------------------------------------------------------------- /assets/polyfill-inert-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PolymerLabs/blocking-elements/HEAD/assets/polyfill-inert-1.png -------------------------------------------------------------------------------- /assets/polyfill-inert-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PolymerLabs/blocking-elements/HEAD/assets/polyfill-inert-2.png -------------------------------------------------------------------------------- /assets/polyfill-inert-3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PolymerLabs/blocking-elements/HEAD/assets/polyfill-inert-3.png -------------------------------------------------------------------------------- /assets/polyfill-inert-4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PolymerLabs/blocking-elements/HEAD/assets/polyfill-inert-4.png -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | *.tgz 2 | test/** 3 | demo/** 4 | .babelrc 5 | .clang-format 6 | .travis.yml 7 | rollup.config.js 8 | tsconfig.json 9 | tslint.json 10 | -------------------------------------------------------------------------------- /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | [ 4 | "@babel/preset-env", 5 | { 6 | "modules": false 7 | } 8 | ] 9 | ] 10 | } 11 | -------------------------------------------------------------------------------- /.clang-format: -------------------------------------------------------------------------------- 1 | BasedOnStyle: Google 2 | AlignAfterOpenBracket: AlwaysBreak 3 | AllowAllParametersOfDeclarationOnNextLine: false 4 | AllowShortBlocksOnASingleLine: false 5 | AllowShortCaseLabelsOnASingleLine: false 6 | AllowShortFunctionsOnASingleLine: None 7 | AllowShortIfStatementsOnASingleLine: false 8 | AllowShortLoopsOnASingleLine: false 9 | BinPackArguments: false 10 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es2017", 4 | "module": "es2015", 5 | "outDir": "./dist", 6 | 7 | "strict": true, 8 | "noUnusedLocals": true, 9 | "noUnusedParameters": true, 10 | "preserveConstEnums": true, 11 | 12 | "lib": [ 13 | "dom", 14 | "esnext" 15 | ], 16 | 17 | "declaration": true, 18 | "sourceMap": true, 19 | "pretty": true 20 | }, 21 | 22 | "include": [ 23 | "src/*.ts" 24 | ] 25 | } 26 | -------------------------------------------------------------------------------- /rollup.config.js: -------------------------------------------------------------------------------- 1 | import babel from 'rollup-plugin-babel'; 2 | import commonjs from 'rollup-plugin-commonjs'; 3 | import resolve from 'rollup-plugin-node-resolve'; 4 | import {uglify} from 'rollup-plugin-uglify'; 5 | 6 | export default [{ 7 | input: 'dist/blocking-elements.js', 8 | output: { 9 | file: 'dist/blocking-elements.min.js', 10 | format: 'iife', 11 | }, 12 | plugins: [ 13 | resolve(), 14 | commonjs(), 15 | babel({ 16 | exclude: 'node_modules/**', // only transpile our source code 17 | }), 18 | uglify({ 19 | output: { 20 | comments: function(node, comment) { 21 | const text = comment.value; 22 | // comment2 is a /* style comment. 23 | if (comment.type === 'comment2' && text.includes('@license')) { 24 | // We only want to include each license once. Note we put the Set on 25 | // "this" because we can't access module-scoped variables, since 26 | // isn't really a module. 27 | this.uniqueLicenses = this.uniqueLicenses || new Set(); 28 | if (!this.uniqueLicenses.has(text)) { 29 | this.uniqueLicenses.add(text); 30 | return true; 31 | } 32 | } 33 | return false; 34 | } 35 | } 36 | }), 37 | ], 38 | }]; 39 | -------------------------------------------------------------------------------- /demo/x-a.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @license 3 | * Copyright 2016 Google Inc. All rights reserved. 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | import './x-trap-focus.js'; 16 | 17 | const template = document.createElement('template'); 18 | template.innerHTML = ` 19 | 27 | 28 | 29 | 30 | `; 31 | 32 | class XA extends HTMLElement { 33 | connectedCallback() { 34 | const clone = document.importNode(template.content, true); 35 | this.attachShadow({ 36 | mode: 'open' 37 | }).appendChild(clone); 38 | } 39 | } 40 | customElements.define('x-a', XA); -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | dist: xenial 2 | language: node_js 3 | node_js: 'node' 4 | env: 5 | global: 6 | - secure: VpPRx1TJb2Kw3+Em4ViH3H2CRHwM+mzliygcWc+kH0k9+iYnKfTOfI+ZsrzE5joCy7qZPAQgNKduvZ9/oDAZrGx/byhFcu5a+/I4sJPQP7kHXVtGK5+WN3Db8uKGkTc5J2539qAhYLmER+gRhazz2c7QQL6zS4cfkYArprEXANJk6neW+kyRN0TYl0YZVp2vW6ZqRxgCv7UDma2u/DIq37Z2T+CzAOYOoZccIWMN4qeEucZZDLf15c+MuTC2sq+BR9t4360Lj4Cp6WPOm5MWpo2pYFHTWOCEviVlzumQh4V9Xb5OXpASoZ7mTHiqXhgkmIWhk527A3GOo2VYPmOH7s/C3VbMabgJhmQVOIIg/IwRnIeTOLbPyOaQFmz2fA9s799noUV7PSCelBISacn0OtYfE6HcWWzICRv7ji6P/lTPOMBarxfqBQx3tgDoGEe019qxEoA3XT6T36MBntg7SKLNu/3Ankt0euC8x65v/zOLpnDfjbzBcgz8p4XCThpwNJNobo0ZMwljHqBqrsd2CDAWixCuVbKoUwuzn8PusG8HYZKCDOUsiRi42Ub0mcubJpqZTx3mcmgb/iAJAf/6s4iropqzpzeAM4sX/CwS/HaqdRa/KW/6jCBVLJApvGOJ862GXpUh7AKgIi0VW1zfMolBSyFEJNV4wFhGfFqsZ3M= 7 | - secure: WBh01y8vwu3zyIB2xMB2tqb2jRR0ACtNiBs8EMhLaGj3zpr8HnibpxkanrrQ/h00JSFcfMhqvYVN0u0lm5gh0e5lXvUcSRk3IcBUkVbPk9AbzCy7owEOZGsNUyAk1NzOt+OKXIhY6Eyuz7EkKyFlEsOIvzl2b6Vo5pnU/8MT5msj0RoHlotWSmt+9x7LFZmTV7CuY/Br9DDneyDbXBxiivrowhRobVBm7IHt7ozlLM9wgeWYJl/GfTckYWQHsR77N9Fqw4t4DlemwPP+d8jNfnUEbqaPkXhuUps6zQGp41YwkowoTYHCfSpzMT2K0Cz+ubJAZepN80aqMU6n6Mgc+1sv85BumarOGwZhusjNYRao4qqu7hy1BzfsFAFdC+hQpsrns/hS+E5ThEwzq+4HykXpPaS5iu8rGdrHJmYI8yDG19qnfGV3k5TcEbr3lmzIyFuk8wAwKBgHQBfrDvJrjzuB3bdi4PbdzXqaeBK2lNRSTfCFJvL9FPT2n1WR1VxBZv+nKtAZBgiQcHOewYZyrMiaF+Rsqi847Xl63P0OhDnYBYqldD0Jq9zZ9Cl5YCowrSC9Xfw8dPEh0hDxDXZDiZZLTS+CNzOHQiMkr1moh1JapW/QAUe8YePbiczVBZO10IAeOYPfhce2V8Cl+ooCPFJOXJMIiiBxB0Va+W7DZ8A= 8 | -------------------------------------------------------------------------------- /demo/x-b.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @license 3 | * Copyright 2016 Google Inc. All rights reserved. 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | import './x-trap-focus.js'; 16 | import './x-a.js'; 17 | 18 | const template = document.createElement('template'); 19 | template.innerHTML = ` 20 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | `; 35 | 36 | class XB extends HTMLElement { 37 | connectedCallback() { 38 | const clone = document.importNode(template.content, true); 39 | this.attachShadow({ 40 | mode: 'open' 41 | }).appendChild(clone); 42 | } 43 | } 44 | customElements.define('x-b', XB); 45 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "rules": { 3 | "arrow-parens": true, 4 | "class-name": true, 5 | "indent": [ 6 | true, 7 | "spaces", 8 | 2 9 | ], 10 | "prefer-const": true, 11 | "no-duplicate-variable": true, 12 | "no-eval": true, 13 | "no-internal-module": true, 14 | "no-parameter-properties": true, 15 | "no-trailing-whitespace": true, 16 | "no-var-keyword": true, 17 | "no-any": true, 18 | "no-unnecessary-type-assertion": true, 19 | "one-line": [ 20 | true, 21 | "check-open-brace", 22 | "check-whitespace" 23 | ], 24 | "quotemark": [ 25 | true, 26 | "single", 27 | "avoid-escape" 28 | ], 29 | "semicolon": [ 30 | true, 31 | "always" 32 | ], 33 | "trailing-comma": [ 34 | true, 35 | "multiline" 36 | ], 37 | "triple-equals": [ 38 | true, 39 | "allow-null-check" 40 | ], 41 | "typedef-whitespace": [ 42 | true, 43 | { 44 | "call-signature": "nospace", 45 | "index-signature": "nospace", 46 | "parameter": "nospace", 47 | "property-declaration": "nospace", 48 | "variable-declaration": "nospace" 49 | } 50 | ], 51 | "variable-name": [ 52 | true, 53 | "ban-keywords" 54 | ], 55 | "whitespace": [ 56 | true, 57 | "check-branch", 58 | "check-decl", 59 | "check-operator", 60 | "check-separator", 61 | "check-type" 62 | ] 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /test/helpers/fixture.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @license 3 | * Copyright 2018 Google Inc. All rights reserved. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | window.Fixture = function Fixture() { 19 | if (!(this instanceof Fixture)) { 20 | throw new TypeError('Cannot call a class as a function'); 21 | } 22 | 23 | this._fixture = undefined; 24 | 25 | /** 26 | * Stick the html into a `
`. 27 | * @param {!string} html 28 | * @return {Element|NodeList|null} 29 | */ 30 | this.load = function(html) { 31 | this._fixture = document.createElement('div'); 32 | this._fixture.id = 'fixture'; 33 | document.body.appendChild(this._fixture); 34 | this._fixture.innerHTML = html; 35 | var children = this._fixture.children; 36 | return children.length === 1 ? children[0] : children; 37 | }; 38 | 39 | /** 40 | * Remove the current fixture and delete it. 41 | */ 42 | this.destroy = function() { 43 | document.body.removeChild(this._fixture); 44 | this._fixture = undefined; 45 | }; 46 | return this; 47 | }; 48 | -------------------------------------------------------------------------------- /demo/x-trap-focus.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @license 3 | * Copyright 2016 Google Inc. All rights reserved. 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | const template = document.createElement('template'); 16 | template.innerHTML = ` 17 | 34 | 37 | `; 38 | 39 | class XTrapFocus extends HTMLElement { 40 | connectedCallback() { 41 | const clone = document.importNode(template.content, true); 42 | clone.querySelector('#toggle').addEventListener('change', this._toggleTrap.bind(this)); 43 | this.attachShadow({ 44 | mode: 'open' 45 | }).appendChild(clone); 46 | } 47 | 48 | _toggleTrap(evt) { 49 | this.classList[evt.target.checked ? 'add' : 'remove']('blocking'); 50 | document.$blockingElements[evt.target.checked ? 'push' : 'remove'](this); 51 | } 52 | } 53 | customElements.define('x-trap-focus', XTrapFocus); -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "blocking-elements", 3 | "version": "0.1.1", 4 | "description": "A polyfill for the proposed blocking elements stack API", 5 | "main": "dist/blocking-elements.js", 6 | "module": "dist/blocking-elements.js", 7 | "author": "Valdrin Koshi ", 8 | "license": "Apache-2.0", 9 | "repository": { 10 | "type": "git", 11 | "url": "git+https://github.com/PolymerLabs/blocking-elements.git" 12 | }, 13 | "keywords": [ 14 | "blocking-elements", 15 | "polyfill", 16 | "browser" 17 | ], 18 | "bugs": { 19 | "url": "https://github.com/PolymerLabs/blocking-elements/issues" 20 | }, 21 | "homepage": "https://github.com/PolymerLabs/blocking-elements#readme", 22 | "scripts": { 23 | "lint": "tslint --project ./", 24 | "test": "npm run lint && npm run build && easy-sauce", 25 | "format": "clang-format --style=file -i src/*.ts", 26 | "prepack": "npm run build", 27 | "build": "rm -rf dist/* && tsc && rollup -c" 28 | }, 29 | "devDependencies": { 30 | "@babel/core": "^7.5.5", 31 | "@babel/preset-env": "^7.5.5", 32 | "@webcomponents/webcomponentsjs": "^2.2.10", 33 | "babel-polyfill": "^6.26.0", 34 | "chai": "^4.0.2", 35 | "clang-format": "^1.2.4", 36 | "easy-sauce": "^0.4.1", 37 | "mocha": "^6.2.0", 38 | "rollup": "^1.17.0", 39 | "rollup-plugin-babel": "^4.3.3", 40 | "rollup-plugin-commonjs": "^10.0.1", 41 | "rollup-plugin-node-resolve": "^5.2.0", 42 | "rollup-plugin-uglify": "^6.0.2", 43 | "tslint": "^5.18.0", 44 | "typescript": "^3.5.3", 45 | "wicg-inert": "^2.1.2" 46 | }, 47 | "easySauce": { 48 | "testPath": "/test/", 49 | "port": "8080", 50 | "service": "sauce-connect", 51 | "max-duration": 300, 52 | "platforms": [ 53 | [ 54 | "Windows 10", 55 | "chrome", 56 | "latest" 57 | ], 58 | [ 59 | "Linux", 60 | "firefox", 61 | "latest" 62 | ], 63 | [ 64 | "Windows 10", 65 | "microsoftedge", 66 | "latest" 67 | ] 68 | ] 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /test/index.html: -------------------------------------------------------------------------------- 1 | 2 | 11 | 12 | 13 | 14 | 15 | Tests 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 | 30 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | -------------------------------------------------------------------------------- /demo/ce.html: -------------------------------------------------------------------------------- 1 | 13 | 14 | 15 | 16 | 17 | 18 | blockingElements polyfill test page 19 | 20 | 21 | 22 | 23 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | inert x-trap-focus 36 | 37 | 38 | 39 |

x-trap-focus

40 | 41 | 42 | 43 | 44 |

45 | nested 46 |

47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 |

x-a

61 | 62 | 63 | 64 | 65 |

66 | nested 67 |

68 | 69 | 70 | 71 | 72 | 73 | 74 |

75 | with x-trap-focus 76 |

77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 |

x-b

85 | 86 | 87 | 88 | 89 |

90 | nested 91 |

92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 |

100 | with x-trap-focus 101 |

102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 |

Lots of focusable elements

110 | 115 | 116 | 117 | 118 | -------------------------------------------------------------------------------- /demo/index.html: -------------------------------------------------------------------------------- 1 | 13 | 14 | 15 | 16 | 17 | 18 | blockingElements polyfill test page 19 | 20 | 21 | 22 | 23 | 34 | 35 | 36 | 37 | 38 |

blocking elements

39 | 40 |
41 | 44 |
45 | 46 |
47 | 50 |

51 | 52 | 53 |

54 | 55 |
56 | 59 |

60 | 61 | 62 |

63 | 64 |
65 | 68 |

69 | 70 | 71 |

72 |
73 |
74 |
75 | 76 |
77 |

78 | Some inputs 79 |

80 | 81 | 82 | 83 | 84 |
85 | 86 |

87 | Check these other demos: 88 |

92 |

93 | 94 | 108 | 109 | 110 | 111 | -------------------------------------------------------------------------------- /test/shadow.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @license 3 | * Copyright 2016 Google Inc. All rights reserved. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | (function() { 18 | var assert = chai.assert; 19 | var fixtureLoader = new Fixture(); 20 | /* eslint-disable require-jsdoc */ 21 | 22 | function emptyBlockingElements() { 23 | while (document.$blockingElements.pop()) { 24 | // keep popping! 25 | } 26 | } 27 | 28 | describe('ShadowDom v1', function() { 29 | if (!Element.prototype.attachShadow) { 30 | console.log('ShadowDOM v1 is not supported by the browser.'); 31 | return; 32 | } 33 | 34 | var container; 35 | 36 | beforeEach(function(done) { 37 | container = fixtureLoader.load(` 38 |
39 | 40 | 41 | 42 |
`); 43 | var template = document.createElement('template'); 44 | template.innerHTML = ``; 45 | container.attachShadow({ 46 | mode: 'open', 47 | }).appendChild(template.content); 48 | // Needed by ShadowDOM polyfill. 49 | setTimeout(function() { 50 | done(); 51 | }); 52 | }); 53 | 54 | afterEach(function() { 55 | emptyBlockingElements(); 56 | fixtureLoader.destroy(); 57 | }); 58 | 59 | it('update elements in shadow dom', function() { 60 | var shadowBtn = container.shadowRoot.querySelector('button'); 61 | 62 | // Distributed element as a blocking element. 63 | document.$blockingElements.push(container.children[0]); 64 | assert.equal(document.$blockingElements.top, container.children[0]); 65 | assert.isTrue(shadowBtn.inert, 'button in shadow dom inert'); 66 | assert.isNotOk(container.children[0].inert, '1st child active'); 67 | assert.isTrue(container.children[1].inert, '2nd child inert'); 68 | assert.isTrue(container.children[2].inert, '3rd child inert'); 69 | 70 | // Button in shadow dom as a blocking element, its siblings should be inert 71 | document.$blockingElements.push(shadowBtn); 72 | assert.isTrue(document.$blockingElements.has(container.children[0]), 73 | '1st child is a blocking element'); 74 | assert.equal(document.$blockingElements.top, shadowBtn); 75 | assert.isNotOk(shadowBtn.inert, 'button in shadow dom active'); 76 | assert.isTrue(shadowBtn.nextElementSibling.inert, 'button sibling (slot) inert'); 77 | assert.isNotOk(container.children[0].inert, '1st child inert restored'); 78 | assert.isNotOk(container.children[1].inert, '2nd child inert restored'); 79 | assert.isNotOk(container.children[2].inert, '3rd child inert restored'); 80 | }); 81 | 82 | it('push() adds only elements contained in document', function() { 83 | assert.equal(document.$blockingElements.top, null); 84 | // We remove the container, then we try to add one of its shadowRoot children. 85 | container.parentNode.removeChild(container); 86 | assert.throws(function() { 87 | document.$blockingElements.push(container.shadowRoot.firstElementChild); 88 | }, 'Non-connected element cannot be a blocking element'); 89 | assert.equal(document.$blockingElements.top, null, 'element is not a blocking element'); 90 | }); 91 | 92 | it('mutation to shadow root should inert siblings', function(done) { 93 | // Make the first shadow root child blocking. 94 | var shadowA = container.shadowRoot.querySelector('button'); 95 | document.$blockingElements.push(shadowA); 96 | // Add a new shadow child (a sibling of the first one). 97 | var shadowB = document.createElement('input'); 98 | container.shadowRoot.appendChild(shadowB); 99 | // Mutation observer should notice the new child and inert it. 100 | setTimeout(function() { 101 | assert.isTrue(shadowB.inert, 'new shadow child inert'); 102 | done(); 103 | }); 104 | }); 105 | }); 106 | })(); 107 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://travis-ci.org/PolymerLabs/blocking-elements.svg?branch=master)](https://travis-ci.org/PolymerLabs/blocking-elements) 2 | [![Published on npm](https://img.shields.io/npm/v/blocking-elements.svg)](https://www.npmjs.com/package/blocking-elements) 3 | 4 | # Blocking Elements stack API 5 | 6 | Implementation of proposal https://github.com/whatwg/html/issues/897 7 | 8 | > The polyfill chooses a non-colliding name (`document.$blockingElements` instead of `document.blockingElements`) as the proposal is still work in progress and hasn't yet reached consensus on the semantics and functionality (see [this discussion](https://github.com/PolymerLabs/blocking-elements/pull/1#issuecomment-235102344) for more details). 9 | 10 | `document.$blockingElements` manages a stack of elements that inert the interaction outside them. 11 | 12 | - the stack can be updated with the methods `push(elem), remove(elem), pop()` 13 | - the top element (`document.$blockingElements.top`) and its subtree is the interactive part of the document 14 | - `has(elem)` returns if the element is a blocking element 15 | 16 | This polyfill will: 17 | 18 | - search for the path of the element to block up to `document.body` 19 | - set `inert` to all the siblings of each parent, skipping the parents and the element's distributed content (if any) 20 | 21 | Use this polyfill together with the [wicg-inert](https://github.com/WICG/inert) polyfill to disable interactions on the rest of the document. See the [demo page](https://github.com/PolymerLabs/blocking-elements/blob/master/demo/index.html) as an example. 22 | 23 | ## Why not listening to events that trigger focus change? 24 | 25 | Another approach could be to listen for events that trigger focus change (e.g. `focus, blur, keydown`) and prevent those if focus moves out of the blocking element. 26 | 27 | Wrapping the focus requires to find all the focusable nodes within the top blocking element, eventually sort by tabindex, in order to find first and last focusable node. 28 | 29 | This approach doesn't allow the focus to move outside the window (e.g. to the browser's url bar, dev console if opened, etc.), and is less robust when used with assistive technology (e.g. android talkback allows to move focus with swipe on screen, Apple Voiceover allows to move focus with special keyboard combinations). 30 | 31 | ## Install & use 32 | 33 | Blocking Elements relies on the [`inert` attribute](https://github.com/WICG/inert) and uses [`Set` objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set), so make sure to include their polyfills as needed. 34 | 35 | ```bash 36 | npm install --save babel-polyfill 37 | npm install --save wicg-inert 38 | npm install --save blocking-elements 39 | ``` 40 | 41 | ```html 42 | 43 | 44 | 45 | 46 |
47 | 48 | 49 |
50 | 51 | 52 | 53 | 61 | ``` 62 | 63 | ## Files 64 | 65 | Two scripts are included: 66 | 67 | 1. `/dist/blocking-elements.min.js`: minified and transpiled to ES5. 68 | 69 | 2. `/dist/blocking-elements.js`: un-minified ES2017. 70 | 71 | If your toolchain supports Node-style module resolution (e.g. TypeScript's `--moduleResolution=node`), then the main `blocking-elements` bare module specifier resolves to this file. TypeScript declarations are also included for this module: 72 | 73 | ```ts 74 | import {DocumentWithBlockingElements} from 'blocking-elements'; 75 | 76 | const blockingElements = 77 | (document as DocumentWithBlockingElements).$blockingElements; 78 | 79 | blockingElements.push(...); 80 | blockingElements.remove(...); 81 | ``` 82 | 83 | 84 | ## Local development 85 | 86 | Install the dependencies with `npm install` and serve the resources. 87 | 88 | Run the tests locally by navigating to http://localhost:8080/test/ 89 | 90 | ## Performance 91 | 92 | Performance is dependent on the `inert` polyfill performance. Chrome recently landed [the `inert` attribute implementation](https://codereview.chromium.org/2088453002/) behind a flag. 93 | 94 | Let's compare the how long it takes to toggle the deepest `x-trap-focus` inside nested `x-b` of the demo page () 95 | 96 | ![results](https://cloud.githubusercontent.com/assets/6173664/17538133/914f365a-5e57-11e6-9b91-1c6b7eb22d57.png). 97 | 98 | `document.$blockingElements` with native inert is **~15x faster** than polyfilled inert 🎉 🎉 🎉 99 | 100 | | with polyfilled inert (M58) | with native inert (M60) | 101 | |----------|--------| 102 | | ![polyfill-inert-1.png](assets/polyfill-inert-1.png) | ![native-inert-1.png](assets/native-inert-1.png) | 103 | | ![polyfill-inert-2.png](assets/polyfill-inert-2.png) | ![native-inert-2.png](assets/native-inert-2.png) | 104 | | ![polyfill-inert-3.png](assets/polyfill-inert-3.png) | ![native-inert-3.png](assets/native-inert-3.png) | 105 | | ![polyfill-inert-4.png](assets/polyfill-inert-4.png) | ![native-inert-4.png](assets/native-inert-4.png) | 106 | -------------------------------------------------------------------------------- /test/basic.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @license 3 | * Copyright 2016 Google Inc. All rights reserved. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | (function() { 18 | var assert = chai.assert; 19 | var fixtureLoader = new Fixture(); 20 | /* eslint-disable require-jsdoc */ 21 | 22 | function emptyBlockingElements() { 23 | while (document.$blockingElements.pop()) { 24 | // keep popping! 25 | } 26 | } 27 | 28 | describe('basic', function() { 29 | var container; 30 | 31 | beforeEach(function() { 32 | assert.equal(document.$blockingElements.top, null); 33 | container = fixtureLoader.load(` 34 |
35 | 36 | 37 | 38 |
`); 39 | }); 40 | 41 | afterEach(function() { 42 | emptyBlockingElements(); 43 | fixtureLoader.destroy(); 44 | }); 45 | 46 | it('document.$blockingElements is defined', function() { 47 | assert.isOk(document.$blockingElements); 48 | }); 49 | 50 | it('push() adds an element to the stack, remove() removes it', function() { 51 | var child = container.children[0]; 52 | document.$blockingElements.push(child); 53 | assert.equal(document.$blockingElements.top, child); 54 | 55 | document.$blockingElements.remove(child); 56 | assert.equal(document.$blockingElements.top, null); 57 | }); 58 | 59 | it('push() can be used to make an already blocking element the top blocking element', 60 | function() { 61 | document.$blockingElements.push(container.children[0]); 62 | assert.equal(document.$blockingElements.top, container.children[0], 63 | 'child0 is top blocking element'); 64 | // Add another element. 65 | document.$blockingElements.push(container.children[1]); 66 | assert.equal(document.$blockingElements.top, container.children[1], 67 | 'child1 is top blocking element'); 68 | // Push again first element. 69 | document.$blockingElements.push(container.children[0]); 70 | assert.equal(document.$blockingElements.top, container.children[0], 71 | 'child0 brought to top'); 72 | }); 73 | 74 | it('push() adds only elements contained in document', function() { 75 | assert.throws(function() { 76 | document.$blockingElements.push(document.createElement('div')); 77 | }, 'Non-connected element cannot be a blocking element'); 78 | assert.equal(document.$blockingElements.top, null, 'element is not a blocking element'); 79 | }); 80 | 81 | it('pop() removes the top blocking element from stack and returns it', function() { 82 | document.$blockingElements.push(container.children[0]); 83 | document.$blockingElements.push(container.children[1]); 84 | assert.isTrue(document.$blockingElements.has(container.children[0]), 85 | '1st child is a blocking element'); 86 | assert.equal(document.$blockingElements.top, container.children[1], 87 | '2nd child is top blocking element'); 88 | assert.equal(document.$blockingElements.pop(), container.children[1], 89 | '2nd child removed'); 90 | assert.equal(document.$blockingElements.top, container.children[0], 91 | '1sd child is top blocking element'); 92 | }); 93 | 94 | it('preserve already inert elements', function() { 95 | var child = container.children[0]; 96 | // Make children[1] inert 97 | container.children[1].inert = true; 98 | // Push and remove children[0], see if inert is preserved. 99 | document.$blockingElements.push(child); 100 | assert.equal(document.$blockingElements.top, child); 101 | document.$blockingElements.remove(child); 102 | assert.equal(document.$blockingElements.top, null); 103 | assert.isTrue(container.children[1].inert, 'inert preserved'); 104 | }); 105 | 106 | it('multiple push() update elements inertness', function() { 107 | document.$blockingElements.push(container.children[0]); 108 | assert.equal(document.$blockingElements.top, container.children[0]); 109 | assert.isNotOk(container.children[0].inert, '1st child active'); 110 | assert.isTrue(container.children[1].inert, '2nd child inert'); 111 | assert.isTrue(container.children[2].inert, '3rd child inert'); 112 | 113 | document.$blockingElements.push(container.children[1]); 114 | assert.isTrue(document.$blockingElements.has(container.children[0]), 115 | '1st child is a blocking element'); 116 | assert.equal(document.$blockingElements.top, container.children[1], 117 | '2nd child is top blocking element'); 118 | assert.isTrue(container.children[0].inert, '1st child inert'); 119 | assert.isNotOk(container.children[1].inert, '2nd child active'); 120 | assert.isTrue(container.children[2].inert, '3rd child inert'); 121 | }); 122 | 123 | it('remove() handles elements not in the dom anymore', function() { 124 | var child = container.children[0]; 125 | document.$blockingElements.push(child); 126 | assert.equal(document.$blockingElements.top, child); 127 | container.removeChild(child); 128 | document.$blockingElements.remove(child); 129 | assert.equal(document.$blockingElements.top, null); 130 | assert.isNotOk(container.inert, 'container active'); 131 | // Remaining children should be active. 132 | for (var i = 0; i < container.children.length; i++) { 133 | assert.isNotOk(container.children[i].inert, 'sibling active'); 134 | } 135 | }); 136 | 137 | it('destructor resets the document inertness', function() { 138 | document.$blockingElements.push(container.children[0]); 139 | // Destroy and then construct again. 140 | document.$blockingElements.destructor(); 141 | document.$blockingElements = new document.$blockingElements.constructor(); 142 | assert.isNotOk(container.inert, 'container active'); 143 | // Remaining children should be active. 144 | for (var i = 0; i < container.children.length; i++) { 145 | assert.isNotOk(container.children[i].inert, 'sibling active'); 146 | } 147 | }); 148 | }); 149 | 150 | describe('nested', function() { 151 | var container; 152 | var inner; 153 | 154 | beforeEach(function() { 155 | assert.equal(document.$blockingElements.top, null); 156 | container = fixtureLoader.load(` 157 |
158 | 159 | 160 | 161 |
162 | 163 | 164 | 165 |
166 |
`); 167 | inner = container.querySelector('#inner'); 168 | }); 169 | 170 | afterEach(function() { 171 | emptyBlockingElements(); 172 | fixtureLoader.destroy(); 173 | }); 174 | 175 | it('push() keeps parent tree active', function() { 176 | document.$blockingElements.push(inner.children[0]); 177 | assert.equal(document.$blockingElements.top, inner.children[0]); 178 | 179 | // node and its parents should be active 180 | assert.isNotOk(inner.children[0].inert, 'inner child active'); 181 | assert.isNotOk(inner.inert, 'inner active'); 182 | 183 | // Its siblings and parent's siblings should be inert. 184 | for (var i = 1; i < inner.children.length; i++) { 185 | assert.isTrue(inner.children[i].inert, 'inner sibling inert'); 186 | } 187 | assert.isTrue(container.children[0].inert, '1st child inert'); 188 | assert.isTrue(container.children[1].inert, '2nd child inert'); 189 | assert.isTrue(container.children[2].inert, '3rd child inert'); 190 | }); 191 | }); 192 | 193 | describe('mutations', function() { 194 | var container; 195 | 196 | beforeEach(function() { 197 | assert.equal(document.$blockingElements.top, null); 198 | container = fixtureLoader.load(` 199 |
200 | 201 | 202 | 203 |
`); 204 | }); 205 | 206 | afterEach(function() { 207 | emptyBlockingElements(); 208 | fixtureLoader.destroy(); 209 | }); 210 | 211 | it('should inert new siblings', function(done) { 212 | document.$blockingElements.push(container); 213 | var input = document.createElement('input'); 214 | container.parentNode.appendChild(input); 215 | // Wait for mutation observer to see the change. 216 | setTimeout(function() { 217 | assert.isTrue(input.inert, 'inerted'); 218 | done(); 219 | }); 220 | }); 221 | 222 | it('should inert new parent siblings', function(done) { 223 | document.$blockingElements.push(container); 224 | var input = document.createElement('input'); 225 | document.body.appendChild(input); 226 | // Wait for mutation observer to see the change. 227 | setTimeout(function() { 228 | assert.isTrue(input.inert, 'inerted'); 229 | document.body.removeChild(input); 230 | done(); 231 | }); 232 | }); 233 | 234 | it('should restore inertness of removed siblings', function(done) { 235 | document.$blockingElements.push(container.children[0]); 236 | var child1 = container.children[1]; 237 | assert.isTrue(child1.inert, 'inerted'); 238 | container.removeChild(child1); 239 | // Wait for mutation observer to see the change. 240 | setTimeout(function() { 241 | assert.isFalse(child1.inert, 'inert restored'); 242 | done(); 243 | }); 244 | }); 245 | 246 | it('should remove top if it was removed', function(done) { 247 | document.$blockingElements.push(container); 248 | container.parentNode.removeChild(container); 249 | // Wait for mutation observer to see the change. 250 | setTimeout(function() { 251 | assert.equal(document.$blockingElements.top, null); 252 | done(); 253 | }); 254 | }); 255 | }); 256 | })(); 257 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /src/blocking-elements.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * @license 3 | * Copyright 2016 Google Inc. All rights reserved. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | /** 19 | * `BlockingElements` manages a stack of elements that inert the interaction 20 | * outside them. The top element is the interactive part of the document. 21 | * The stack can be updated with the methods `push, remove, pop`. 22 | */ 23 | export interface BlockingElements { 24 | /** 25 | * Call this whenever this object is about to become obsolete. This empties 26 | * the blocking elements 27 | */ 28 | destructor(): void; 29 | 30 | /** 31 | * The top blocking element. 32 | */ 33 | top: HTMLElement|null; 34 | 35 | /** 36 | * Adds the element to the blocking elements. 37 | */ 38 | push(element: HTMLElement): void; 39 | 40 | /** 41 | * Removes the element from the blocking elements. Returns true if the 42 | * element was removed. 43 | */ 44 | remove(element: HTMLElement): boolean; 45 | 46 | /** 47 | * Remove the top blocking element and returns it. 48 | */ 49 | pop(): HTMLElement|null; 50 | 51 | /** 52 | * Returns if the element is a blocking element. 53 | */ 54 | has(element: HTMLElement): boolean; 55 | } 56 | 57 | export interface DocumentWithBlockingElements extends Document { 58 | $blockingElements: BlockingElements; 59 | } 60 | 61 | (() => { 62 | /* Symbols for private properties */ 63 | const _blockingElements = Symbol(); 64 | const _alreadyInertElements = Symbol(); 65 | const _topElParents = Symbol(); 66 | const _siblingsToRestore = Symbol(); 67 | const _parentMO = Symbol(); 68 | 69 | /* Symbols for private static methods */ 70 | const _topChanged = Symbol(); 71 | const _swapInertedSibling = Symbol(); 72 | const _inertSiblings = Symbol(); 73 | const _restoreInertedSiblings = Symbol(); 74 | const _getParents = Symbol(); 75 | const _getDistributedChildren = Symbol(); 76 | const _isInertable = Symbol(); 77 | const _handleMutations = Symbol(); 78 | 79 | interface Inertable extends HTMLElement { 80 | inert?: boolean; 81 | } 82 | 83 | interface InternalState { 84 | [_siblingsToRestore]: Set; 85 | [_parentMO]: MutationObserver; 86 | } 87 | interface HasInternalState extends Inertable, InternalState {} 88 | interface MaybeHasInternalState extends Inertable, Partial {} 89 | 90 | /** 91 | * ShadyDOM shady roots look a lot like real ShadowRoots. The __shady property 92 | * gives them away, though. 93 | */ 94 | interface MaybeShadyRoot extends Element { 95 | __shady: unknown; 96 | host: Element; 97 | } 98 | 99 | class BlockingElementsImpl implements BlockingElements { 100 | /** 101 | * The blocking elements. 102 | */ 103 | private[_blockingElements]: MaybeHasInternalState[] = []; 104 | 105 | /** 106 | * Used to keep track of the parents of the top element, from the element 107 | * itself up to body. When top changes, the old top might have been removed 108 | * from the document, so we need to memoize the inerted parents' siblings 109 | * in order to restore their inerteness when top changes. 110 | */ 111 | private[_topElParents]: HasInternalState[] = []; 112 | 113 | /** 114 | * Elements that are already inert before the first blocking element is 115 | * pushed. 116 | */ 117 | private[_alreadyInertElements] = new Set(); 118 | 119 | destructor(): void { 120 | // Restore original inertness. 121 | this[_restoreInertedSiblings](this[_topElParents]); 122 | // Note we don't want to make these properties nullable on the class, 123 | // since then we'd need non-null casts in many places. Calling a method on 124 | // a BlockingElements instance after calling destructor will result in an 125 | // exception. 126 | const nullable = this as unknown as { 127 | [_blockingElements]: null; 128 | [_topElParents]: null; 129 | [_alreadyInertElements]: null; 130 | }; 131 | nullable[_blockingElements] = null; 132 | nullable[_topElParents] = null; 133 | nullable[_alreadyInertElements] = null; 134 | } 135 | 136 | get top(): HTMLElement|null { 137 | const elems = this[_blockingElements]; 138 | return elems[elems.length - 1] || null; 139 | } 140 | 141 | push(element: HTMLElement): void { 142 | if (!element || element === this.top) { 143 | return; 144 | } 145 | // Remove it from the stack, we'll bring it to the top. 146 | this.remove(element); 147 | this[_topChanged](element); 148 | this[_blockingElements].push(element); 149 | } 150 | 151 | remove(element: HTMLElement): boolean { 152 | const i = this[_blockingElements].indexOf(element); 153 | if (i === -1) { 154 | return false; 155 | } 156 | this[_blockingElements].splice(i, 1); 157 | // Top changed only if the removed element was the top element. 158 | if (i === this[_blockingElements].length) { 159 | this[_topChanged](this.top); 160 | } 161 | return true; 162 | } 163 | 164 | pop(): HTMLElement|null { 165 | const top = this.top; 166 | top && this.remove(top); 167 | return top; 168 | } 169 | 170 | has(element: HTMLElement): boolean { 171 | return this[_blockingElements].indexOf(element) !== -1; 172 | } 173 | 174 | /** 175 | * Sets `inert` to all document elements except the new top element, its 176 | * parents, and its distributed content. 177 | */ 178 | private[_topChanged](newTop: MaybeHasInternalState|null): void { 179 | const toKeepInert = this[_alreadyInertElements]; 180 | const oldParents = this[_topElParents]; 181 | // No new top, reset old top if any. 182 | if (!newTop) { 183 | this[_restoreInertedSiblings](oldParents); 184 | toKeepInert.clear(); 185 | this[_topElParents] = []; 186 | return; 187 | } 188 | 189 | const newParents = this[_getParents](newTop); 190 | // New top is not contained in the main document! 191 | if (newParents[newParents.length - 1].parentNode !== document.body) { 192 | throw Error('Non-connected element cannot be a blocking element'); 193 | } 194 | // Cast here because we know we'll call _inertSiblings on newParents 195 | // below. 196 | this[_topElParents] = newParents as Array; 197 | 198 | const toSkip = this[_getDistributedChildren](newTop); 199 | 200 | // No previous top element. 201 | if (!oldParents.length) { 202 | this[_inertSiblings](newParents, toSkip, toKeepInert); 203 | return; 204 | } 205 | 206 | let i = oldParents.length - 1; 207 | let j = newParents.length - 1; 208 | // Find common parent. Index 0 is the element itself (so stop before it). 209 | while (i > 0 && j > 0 && oldParents[i] === newParents[j]) { 210 | i--; 211 | j--; 212 | } 213 | // If up the parents tree there are 2 elements that are siblings, swap 214 | // the inerted sibling. 215 | if (oldParents[i] !== newParents[j]) { 216 | this[_swapInertedSibling](oldParents[i], newParents[j]); 217 | } 218 | // Restore old parents siblings inertness. 219 | i > 0 && this[_restoreInertedSiblings](oldParents.slice(0, i)); 220 | // Make new parents siblings inert. 221 | j > 0 && this[_inertSiblings](newParents.slice(0, j), toSkip, null); 222 | } 223 | 224 | /** 225 | * Swaps inertness between two sibling elements. 226 | * Sets the property `inert` over the attribute since the inert spec 227 | * doesn't specify if it should be reflected. 228 | * https://html.spec.whatwg.org/multipage/interaction.html#inert 229 | */ 230 | private[_swapInertedSibling]( 231 | oldInert: HasInternalState, newInert: MaybeHasInternalState): void { 232 | const siblingsToRestore = oldInert[_siblingsToRestore]; 233 | // oldInert is not contained in siblings to restore, so we have to check 234 | // if it's inertable and if already inert. 235 | if (this[_isInertable](oldInert) && !oldInert.inert) { 236 | oldInert.inert = true; 237 | siblingsToRestore.add(oldInert); 238 | } 239 | // If newInert was already between the siblings to restore, it means it is 240 | // inertable and must be restored. 241 | if (siblingsToRestore.has(newInert)) { 242 | newInert.inert = false; 243 | siblingsToRestore.delete(newInert); 244 | } 245 | newInert[_parentMO] = oldInert[_parentMO]; 246 | newInert[_siblingsToRestore] = siblingsToRestore; 247 | (oldInert as MaybeHasInternalState)[_parentMO] = undefined; 248 | (oldInert as MaybeHasInternalState)[_siblingsToRestore] = undefined; 249 | } 250 | 251 | /** 252 | * Restores original inertness to the siblings of the elements. 253 | * Sets the property `inert` over the attribute since the inert spec 254 | * doesn't specify if it should be reflected. 255 | * https://html.spec.whatwg.org/multipage/interaction.html#inert 256 | */ 257 | private[_restoreInertedSiblings](elements: HasInternalState[]) { 258 | for (const element of elements) { 259 | const mo = element[_parentMO]; 260 | mo.disconnect(); 261 | (element as MaybeHasInternalState)[_parentMO] = undefined; 262 | const siblings = element[_siblingsToRestore]; 263 | for (const sibling of siblings) { 264 | sibling.inert = false; 265 | } 266 | (element as MaybeHasInternalState)[_siblingsToRestore] = undefined; 267 | } 268 | } 269 | 270 | /** 271 | * Inerts the siblings of the elements except the elements to skip. Stores 272 | * the inerted siblings into the element's symbol `_siblingsToRestore`. 273 | * Pass `toKeepInert` to collect the already inert elements. 274 | * Sets the property `inert` over the attribute since the inert spec 275 | * doesn't specify if it should be reflected. 276 | * https://html.spec.whatwg.org/multipage/interaction.html#inert 277 | */ 278 | private[_inertSiblings]( 279 | elements: MaybeHasInternalState[], toSkip: Set|null, 280 | toKeepInert: Set|null) { 281 | for (const element of elements) { 282 | // Assume element is not a Document, so it must have a parentNode. 283 | const parent = element.parentNode!; 284 | const children = parent.children; 285 | const inertedSiblings = new Set(); 286 | for (let j = 0; j < children.length; j++) { 287 | const sibling = children[j] as MaybeHasInternalState; 288 | // Skip the input element, if not inertable or to be skipped. 289 | if (sibling === element || !this[_isInertable](sibling) || 290 | (toSkip && toSkip.has(sibling))) { 291 | continue; 292 | } 293 | // Should be collected since already inerted. 294 | if (toKeepInert && sibling.inert) { 295 | toKeepInert.add(sibling); 296 | } else { 297 | sibling.inert = true; 298 | inertedSiblings.add(sibling); 299 | } 300 | } 301 | // Store the siblings that were inerted. 302 | element[_siblingsToRestore] = inertedSiblings; 303 | // Observe only immediate children mutations on the parent. 304 | const mo = new MutationObserver(this[_handleMutations].bind(this)); 305 | element[_parentMO] = mo; 306 | let parentToObserve = parent; 307 | // If we're using the ShadyDOM polyfill, then our parent could be a 308 | // shady root, which is an object that acts like a ShadowRoot, but isn't 309 | // actually a node in the real DOM. Observe the real DOM parent instead. 310 | const maybeShadyRoot = parentToObserve as MaybeShadyRoot; 311 | if (maybeShadyRoot.__shady && maybeShadyRoot.host) { 312 | parentToObserve = maybeShadyRoot.host; 313 | } 314 | mo.observe(parentToObserve, { 315 | childList: true, 316 | }); 317 | } 318 | } 319 | 320 | /** 321 | * Handles newly added/removed nodes by toggling their inertness. 322 | * It also checks if the current top Blocking Element has been removed, 323 | * notifying and removing it. 324 | */ 325 | private[_handleMutations](mutations: MutationRecord[]): void { 326 | const parents = this[_topElParents]; 327 | const toKeepInert = this[_alreadyInertElements]; 328 | for (const mutation of mutations) { 329 | // If the target is a shadowRoot, get its host as we skip shadowRoots when 330 | // computing _topElParents. 331 | const target = (mutation.target as ShadowRoot).host || mutation.target; 332 | const idx = target === document.body ? 333 | parents.length : 334 | parents.indexOf(target as HasInternalState); 335 | const inertedChild = parents[idx - 1]; 336 | const inertedSiblings = inertedChild[_siblingsToRestore]; 337 | 338 | // To restore. 339 | for (let i = 0; i < mutation.removedNodes.length; i++) { 340 | const sibling = mutation.removedNodes[i] as MaybeHasInternalState; 341 | if (sibling === inertedChild) { 342 | console.info('Detected removal of the top Blocking Element.'); 343 | this.pop(); 344 | return; 345 | } 346 | if (inertedSiblings.has(sibling)) { 347 | sibling.inert = false; 348 | inertedSiblings.delete(sibling); 349 | } 350 | } 351 | 352 | // To inert. 353 | for (let i = 0; i < mutation.addedNodes.length; i++) { 354 | const sibling = mutation.addedNodes[i] as MaybeHasInternalState; 355 | if (!this[_isInertable](sibling)) { 356 | continue; 357 | } 358 | if (toKeepInert && sibling.inert) { 359 | toKeepInert.add(sibling); 360 | } else { 361 | sibling.inert = true; 362 | inertedSiblings.add(sibling); 363 | } 364 | } 365 | } 366 | } 367 | 368 | /** 369 | * Returns if the element is inertable. 370 | */ 371 | private[_isInertable](element: HTMLElement): boolean { 372 | return false === /^(style|template|script)$/.test(element.localName); 373 | } 374 | 375 | /** 376 | * Returns the list of newParents of an element, starting from element 377 | * (included) up to `document.body` (excluded). 378 | */ 379 | private[_getParents](element: HTMLElement): Array { 380 | const parents = []; 381 | let current: HTMLElement|null|undefined = element; 382 | // Stop to body. 383 | while (current && current !== document.body) { 384 | // Skip shadow roots. 385 | if (current.nodeType === Node.ELEMENT_NODE) { 386 | parents.push(current); 387 | } 388 | // ShadowDom v1 389 | if (current.assignedSlot) { 390 | // Collect slots from deepest slot to top. 391 | while (current = current.assignedSlot) { 392 | parents.push(current); 393 | } 394 | // Continue the search on the top slot. 395 | current = parents.pop(); 396 | continue; 397 | } 398 | current = current.parentNode as HTMLElement || 399 | (current as Node as ShadowRoot).host; 400 | } 401 | return parents; 402 | } 403 | 404 | /** 405 | * Returns the distributed children of the element's shadow root. 406 | * Returns null if the element doesn't have a shadow root. 407 | */ 408 | private[_getDistributedChildren](element: HTMLElement): 409 | Set|null { 410 | const shadowRoot = element.shadowRoot; 411 | if (!shadowRoot) { 412 | return null; 413 | } 414 | const result = new Set(); 415 | let i; 416 | let j; 417 | let nodes; 418 | const slots = shadowRoot.querySelectorAll('slot'); 419 | if (slots.length && slots[0].assignedNodes) { 420 | for (i = 0; i < slots.length; i++) { 421 | nodes = slots[i].assignedNodes({ 422 | flatten: true, 423 | }); 424 | for (j = 0; j < nodes.length; j++) { 425 | if (nodes[j].nodeType === Node.ELEMENT_NODE) { 426 | result.add(nodes[j] as HTMLElement); 427 | } 428 | } 429 | } 430 | // No need to search for . 431 | } 432 | return result; 433 | } 434 | } 435 | 436 | (document as DocumentWithBlockingElements).$blockingElements = 437 | new BlockingElementsImpl(); 438 | })(); 439 | --------------------------------------------------------------------------------