├── .gitattributes
├── .gitignore
├── .npmrc
├── .travis.yml
├── LICENSE
├── README.md
├── index.html
├── package.json
├── polyfill.js
├── spec.css
├── spec.emu
├── spec.js
├── spec.md
└── test
├── adapter.js
├── promise.js
├── promiseSpec.js
└── test.js
/.gitattributes:
--------------------------------------------------------------------------------
1 | index.html -diff merge=ours
2 | spec.js -diff merge=ours
3 | spec.css -diff merge=ours
4 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Logs
2 | logs
3 | *.log
4 | npm-debug.log*
5 |
6 | # Runtime data
7 | pids
8 | *.pid
9 | *.seed
10 |
11 | # Directory for instrumented libs generated by jscoverage/JSCover
12 | lib-cov
13 |
14 | # Coverage directory used by tools like istanbul
15 | coverage
16 |
17 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
18 | .grunt
19 |
20 | # node-waf configuration
21 | .lock-wscript
22 |
23 | # Compiled binary addons (http://nodejs.org/api/addons.html)
24 | build/Release
25 |
26 | # Dependency directory
27 | node_modules
28 |
29 | # Optional npm cache directory
30 | .npm
31 |
32 | # Optional REPL history
33 | .node_repl_history
34 |
35 | # Only apps should have lockfiles
36 | npm-shrinkwrap.json
37 | yarn.lock
38 | package-lock.json
39 |
--------------------------------------------------------------------------------
/.npmrc:
--------------------------------------------------------------------------------
1 | package-lock=false
2 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: node_js
2 | node_js:
3 | - "node"
4 | before_install:
5 | - 'nvm install-latest-npm'
6 | script:
7 | - 'if [ -n "${LINT-}" ]; then npm run lint ; fi'
8 | - 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi'
9 | - 'if [ -n "${COVERAGE-}" ]; then npm run coverage ; fi'
10 | - 'if [ -n "${TEST-}" ]; then npm run tests-only ; elif [ -n "${NATIVE-}" ]; then npm run test:finally:native; fi'
11 | sudo: false
12 | env:
13 | - TEST=true
14 | matrix:
15 | fast_finish: true
16 | include:
17 | - node_js: "lts/*"
18 | env: TEST=true
19 | - node_js: "9"
20 | env: NATIVE=true
21 | - node_js: "8"
22 | env: NATIVE=true
23 | - node_js: "8.5"
24 | env: NATIVE=true
25 | allow_failures:
26 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2016 Jordan Harband
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # [Promise.prototype.finally](https://www.npmjs.com/package/promise.prototype.finally)
2 | ECMAScript Proposal, specs, and reference implementation for `Promise.prototype.finally`
3 |
4 | Spec drafted by [@ljharb](https://github.com/ljharb), following the lead from the [cancelable promise proposal](https://github.com/tc39/proposal-cancelable-promises/blob/e31520fc9a53a8cbeff53b0df413d9e565b27d69/Third%20State.md#promiseprototypefinally-implementation).
5 |
6 | Get the polyfill/shim on [npm](https://www.npmjs.com/package/promise.prototype.finally).
7 |
8 | This proposal is currently [stage 4](https://github.com/tc39/proposals/blob/master/finished-proposals.md) of the [process](https://tc39.github.io/process-document/).
9 |
10 | ## Rationale
11 | Many promise libraries have a "finally" method, for registering a callback to be invoked when a promise is settled (either fulfilled, or rejected). The essential use case here is cleanup - I want to hide the "loading" spinner on my AJAX request, or I want to close any file handles I’ve opened, or I want to log that an operation has completed regardless of whether it succeeded or not.
12 |
13 | ### Why not `.then(f, f)`?
14 | `promise.finally(func)` is similar to `promise.then(func, func)`, but is different in a few critical ways:
15 | - When creating a function inline, you can pass it once, instead of being forced to either declare it twice, or create a variable for it
16 | - A `finally` callback will not receive any argument, since there's no reliable means of determining if the promise was fulfilled or rejected. This use case is for precisely when you *do not care* about the rejection reason, or the fulfillment value, and so there's no need to provide it.
17 | - Unlike `Promise.resolve(2).then(() => {}, () => {})` (which will be resolved with `undefined`), `Promise.resolve(2).finally(() => {})` will be resolved with `2`.
18 | - Similarly, unlike `Promise.reject(3).then(() => {}, () => {})` (which will be resolved with `undefined`), `Promise.reject(3).finally(() => {})` will be rejected with `3`.
19 |
20 | However, please note: a `throw` (or returning a rejected promise) in the `finally` callback will reject the new promise with that rejection reason.
21 |
22 | ## Naming
23 | The reasons to stick with `finally` are straightforward: just like `catch`, `finally` would be an analog to the similarly-named syntactic forms from `try`/`catch`/`finally` (`try`, of course, not really having an analog any closer than `Promise.resolve().then`). Syntactic finally can only modify the return value with an “abrupt completion”: either throwing an exception, or returning a value early. `Promise#finally` will not be able to modify the return value, except by creating an abrupt completion by throwing an exception (ie, rejecting the promise) - since there is no way to distinguish between a “normal completion” and an early `return undefined`, the parallel with syntactic finally must have a slight consistency gap.
24 |
25 | I’d briefly considered `always` as an alternative, since that wouldn’t imply ordering, but I think the parallels to the syntactic variation are compelling.
26 |
27 | ## Implementations
28 | - [Bluebird#finally](http://bluebirdjs.com/docs/api/finally.html)
29 | - [Q#finally](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback)
30 | - [when#finally](https://github.com/cujojs/when/blob/master/docs/api.md#promisefinally)
31 | - [jQuery jqXHR#always](http://api.jquery.com/jQuery.ajax/#jqXHR)
32 |
33 | ## Spec
34 | You can view the spec in [markdown format](spec.md) or rendered as [HTML](https://tc39.github.io/proposal-promise-finally/).
35 |
--------------------------------------------------------------------------------
/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 | Promise.prototype.finally
9 |
100 |
1037 |
2122 |
2123 |
2124 |
2125 |
2126 |
2127 |
2150 |
2151 |
Stage 4 Draft / January 24, 2018
2152 |
Promise.prototype.finally
2153 |
2154 |
2155 | 1 Promise.prototype.finally ( onFinally )
2156 | When the finally
method is called with argument onFinally , the following steps are taken:
2157 |
2158 |
2159 | Let promise be the
2160 | this value.
2161 | If
2162 | Type (promise ) is not Object, throw a
2163 | TypeError exception.
2164 | Let C be ?
2165 | SpeciesConstructor (promise ,
2166 | %Promise% ).
2167 | Assert:
2168 | IsConstructor (C ) is
2169 | true .
2170 | If
2171 | IsCallable (onFinally ) is
2172 | false ,
2173 |
2174 | Let thenFinally be onFinally .
2175 | Let catchFinally be onFinally .
2176 |
2177 |
2178 | Else,
2179 |
2180 | Let thenFinally be a new built-in function object as defined in
2181 | ThenFinally Function .
2182 | Let catchFinally be a new built-in function object as defined in
2183 | CatchFinally Function .
2184 | Set thenFinally and catchFinally 's [[Constructor]] internal slots to C .
2185 | Set thenFinally and catchFinally 's [[OnFinally]] internal slots to onFinally .
2186 |
2187 |
2188 | Return ?
2189 | Invoke (promise , "then"
, « thenFinally , catchFinally »).
2190 |
2191 |
2192 |
2193 |
2194 |
2195 | 1.1 ThenFinally Function
2196 | A ThenFinally function is an anonymous built-in function that has a [[Constructor]] and an [[OnFinally]] internal slot. The value of the [[Constructor]] internal slot is a Promise
-like constructor function object, and the value of the [[OnFinally]] internal slot is a function object.
2197 | When a ThenFinally function F is called with argument value , the following steps are taken:
2198 |
2199 |
2200 | Let onFinally be F .[[OnFinally]].
2201 | Assert:
2202 | IsCallable (onFinally ) is
2203 | true .
2204 | Let result be ?
2205 | Call (onFinally ,
2206 | undefined ).
2207 | Let C be F .[[Constructor]].
2208 | Assert:
2209 | IsConstructor (C ) is
2210 | true .
2211 | Let promise be ?
2212 | PromiseResolve (C , result ).
2213 | Let valueThunk be equivalent to a function that returns value .
2214 | Return ?
2215 | Invoke (promise , "then"
, « valueThunk »).
2216 |
2217 |
2218 |
2219 |
2220 |
2221 |
2222 | 1.2 CatchFinally Function
2223 | A CatchFinally function is an anonymous built-in function that has a [[Constructor]] and an [[OnFinally]] internal slot. The value of the [[Constructor]] internal slot is a Promise
-like constructor function object, and the value of the [[OnFinally]] internal slot is a function object.
2224 | When a CatchFinally function F is called with argument reason , the following steps are taken:
2225 |
2226 |
2227 | Let onFinally be F .[[OnFinally]].
2228 | Assert:
2229 | IsCallable (onFinally ) is
2230 | true .
2231 | Let result be ?
2232 | Call (onFinally ,
2233 | undefined ).
2234 | Let C be F .[[Constructor]].
2235 | Assert:
2236 | IsConstructor (C ) is
2237 | true .
2238 | Let promise be ?
2239 | PromiseResolve (C , result ).
2240 | Let thrower be equivalent to a function that throws reason .
2241 | Return ?
2242 | Invoke (promise , "then"
, « thrower »).
2243 |
2244 |
2245 |
2246 |
2247 |
2248 |
2249 |
2250 |
2251 | 2 Promise.resolve ( x )
2252 | The resolve
function returns either a new promise resolved with the passed argument, or the argument itself if the argument is a promise produced by this constructor.
2253 |
2254 |
2255 | Let C be the
2256 | this value.
2257 | If
2258 | Type (C ) is not Object, throw a
2259 | TypeError exception.
2260 | Return ?
2261 | PromiseResolve (C , x ).
2262 |
2263 |
2264 |
2265 | Note
2266 |
2267 |
The resolve
function expects its
2268 | this value to be a constructor function that supports the parameter conventions of the Promise
constructor.
2269 |
2270 |
2271 |
2272 |
2273 |
2274 | 3 PromiseResolve ( C , x )
2275 | The abstract operation PromiseResolve, given a constructor and a value, returns a new promise resolved with that value.
2276 |
2277 |
2278 | Assert:
2279 | Type (C ) is Object.
2280 | If
2281 | IsPromise (x ) is
2282 | true , then
2283 |
2284 | Let xConstructor be ?
2285 | Get (x , "constructor"
).
2286 | If
2287 | SameValue (xConstructor , C ) is
2288 | true , return x .
2289 |
2290 |
2291 | Let promiseCapability be ?
2292 | NewPromiseCapability (C ).
2293 | Perform ?
2294 | Call (promiseCapability .[[Resolve]],
2295 | undefined , « x »).
2296 | Return promiseCapability .[[Promise]].
2297 |
2298 |
2299 |
2300 |
2301 |
2302 | A Copyright & Software License
2303 |
2304 | Copyright Notice
2305 | © 2018 Jordan Harband
2306 |
2307 | Software License
2308 | All Software contained in this document ("Software") is protected by copyright and is being made available under the "BSD License", included below. This Software may be subject to third party rights (rights from parties other than Ecma International), including patent rights, and no licenses under such third party rights are granted under this license even if the third party concerned is a member of Ecma International. SEE THE ECMA CODE OF CONDUCT IN PATENT MATTERS AVAILABLE AT http://www.ecma-international.org/memento/codeofconduct.htm FOR INFORMATION REGARDING THE LICENSING OF PATENT CLAIMS THAT ARE REQUIRED TO IMPLEMENT ECMA INTERNATIONAL STANDARDS.
2309 |
2310 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
2311 |
2312 |
2313 | Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2314 | Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
2315 | Neither the name of the authors nor Ecma International may be used to endorse or promote products derived from this software without specific prior written permission.
2316 |
2317 |
2318 | THIS SOFTWARE IS PROVIDED BY THE ECMA INTERNATIONAL "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ECMA INTERNATIONAL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2319 |
2320 |
2321 |
2322 |
2323 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ecma-proposal-promise-finally",
3 | "version": "0.0.0",
4 | "description": "ECMAScript spec proposal for Promise#finally",
5 | "scripts": {
6 | "build": "ecmarkup spec.emu --js=spec.js --css=spec.css | js-beautify -f - --type=html -w 0 -n -t | sed -e 's/ / /g' -e 's/[[:space:]]*$//' > index.html",
7 | "prepublish": "in-install || (npm run build && not-in-publish || (echo >&2 'no publishing' && exit 255))",
8 | "test": "npm run tests-only",
9 | "tests-only": "npm run test:aplus && npm run test:finally",
10 | "test:aplus": "promises-aplus-tests test/adapter",
11 | "test:finally": "mocha test/test",
12 | "test:finally:native": "node --harmony-promise-finally $(which _mocha) test/test"
13 | },
14 | "repository": {
15 | "type": "git",
16 | "url": "git+https://github.com/tc39/proposal-promise-finally.git"
17 | },
18 | "keywords": [
19 | "promise",
20 | "finally",
21 | "then",
22 | "thenable",
23 | "promises",
24 | "async",
25 | "ECMAScript",
26 | "ESNext",
27 | "spec",
28 | "proposal"
29 | ],
30 | "author": "Jordan Harband ",
31 | "license": "MIT",
32 | "bugs": {
33 | "url": "https://github.com/tc39/proposal-promise-finally/issues"
34 | },
35 | "homepage": "https://github.com/tc39/proposal-promise-finally#readme",
36 | "dependencies": {
37 | "especially": "^2.0.1"
38 | },
39 | "devDependencies": {
40 | "ecmarkup": "^3.12.0",
41 | "in-publish": "^2.0.0",
42 | "js-beautify": "^1.7.5",
43 | "mocha": "^3.5.3",
44 | "promises-aplus-tests": "^2.1.2"
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/polyfill.js:
--------------------------------------------------------------------------------
1 | if (typeof Promise !== 'function') {
2 | throw new TypeError('A global Promise is required');
3 | }
4 |
5 | if (typeof Promise.prototype.finally !== 'function') {
6 | var speciesConstructor = function (O, defaultConstructor) {
7 | if (!O || (typeof O !== 'object' && typeof O !== 'function')) {
8 | throw new TypeError('Assertion failed: Type(O) is not Object');
9 | }
10 | var C = O.constructor;
11 | if (typeof C === 'undefined') {
12 | return defaultConstructor;
13 | }
14 | if (!C || (typeof C !== 'object' && typeof C !== 'function')) {
15 | throw new TypeError('O.constructor is not an Object');
16 | }
17 | var S = typeof Symbol === 'function' && typeof Symbol.species === 'symbol' ? C[Symbol.species] : undefined;
18 | if (S == null) {
19 | return defaultConstructor;
20 | }
21 | if (typeof S === 'function' && S.prototype) {
22 | return S;
23 | }
24 | throw new TypeError('no constructor found');
25 | };
26 |
27 | var shim = {
28 | finally(onFinally) {
29 | var promise = this;
30 | if (typeof promise !== 'object' || promise === null) {
31 | throw new TypeError('"this" value is not an Object');
32 | }
33 | var C = speciesConstructor(promise, Promise); // throws if SpeciesConstructor throws
34 | if (typeof onFinally !== 'function') {
35 | return Promise.prototype.then.call(promise, onFinally, onFinally);
36 | }
37 | return Promise.prototype.then.call(
38 | promise,
39 | x => new C(resolve => resolve(onFinally())).then(() => x),
40 | e => new C(resolve => resolve(onFinally())).then(() => { throw e; })
41 | );
42 | }
43 | };
44 | Object.defineProperty(Promise.prototype, 'finally', { configurable: true, writable: true, value: shim.finally });
45 | }
46 |
--------------------------------------------------------------------------------
/spec.css:
--------------------------------------------------------------------------------
1 | body {
2 | display: flex;
3 | font-size: 18px;
4 | line-height: 1.5;
5 | font-family: Cambria, Palatino Linotype, Palatino, Liberation Serif, serif;
6 | padding: 0;
7 | margin: 0;
8 | color: #111;
9 | }
10 |
11 | #spec-container {
12 | padding: 0 20px;
13 | flex-grow: 1;
14 | flex-basis: 66%;
15 | box-sizing: border-box;
16 | overflow: hidden;
17 | }
18 |
19 | body.oldtoc {
20 | margin: 0 auto;
21 | }
22 |
23 | a {
24 | text-decoration: none;
25 | color: #206ca7;
26 | }
27 |
28 | a:visited {
29 | color: #206ca7;
30 | }
31 |
32 | a:hover {
33 | text-decoration: underline;
34 | color: #239dee;
35 | }
36 |
37 |
38 | code {
39 | font-weight: bold;
40 | font-family: Consolas, Monaco, monospace;
41 | white-space: pre;
42 | }
43 |
44 | pre code {
45 | font-weight: inherit;
46 | }
47 |
48 | pre code.hljs {
49 | background-color: #fff;
50 | margin: 0;
51 | padding: 0;
52 | }
53 |
54 | ol.toc {
55 | list-style: none;
56 | padding-left: 0;
57 | }
58 |
59 | ol.toc ol.toc {
60 | padding-left: 2ex;
61 | list-style: none;
62 | }
63 |
64 | var {
65 | color: #2aa198;
66 | transition: background-color 0.25s ease;
67 | cursor: pointer;
68 | }
69 |
70 | var.referenced {
71 | background-color: #ffff33;
72 | }
73 |
74 | emu-const {
75 | font-family: sans-serif;
76 | }
77 |
78 | emu-val {
79 | font-weight: bold;
80 | }
81 | emu-alg ol, emu-alg ol ol ol ol {
82 | list-style-type: decimal;
83 | }
84 |
85 | emu-alg ol ol, emu-alg ol ol ol ol ol {
86 | list-style-type: lower-alpha;
87 | }
88 |
89 | emu-alg ol ol ol, ol ol ol ol ol ol {
90 | list-style-type: lower-roman;
91 | }
92 |
93 | emu-eqn {
94 | display: block;
95 | margin-left: 4em;
96 | }
97 |
98 | emu-eqn.inline {
99 | display: inline;
100 | margin: 0;
101 | }
102 |
103 | emu-eqn div:first-child {
104 | margin-left: -2em;
105 | }
106 |
107 | emu-note {
108 | margin: 1em 0;
109 | color: #666;
110 | border-left: 5px solid #ccc;
111 | display: flex;
112 | flex-direction: row;
113 | }
114 |
115 | emu-note > span.note {
116 | flex-basis: 100px;
117 | min-width: 100px;
118 | flex-grow: 0;
119 | flex-shrink: 1;
120 | text-transform: uppercase;
121 | padding-left: 5px;
122 | }
123 |
124 | emu-note[type=editor] {
125 | border-left-color: #faa;
126 | }
127 |
128 | emu-note > div.note-contents {
129 | flex-grow: 1;
130 | flex-shrink: 1;
131 | }
132 |
133 | emu-note > div.note-contents > p:first-of-type {
134 | margin-top: 0;
135 | }
136 |
137 | emu-note > div.note-contents > p:last-of-type {
138 | margin-bottom: 0;
139 | }
140 |
141 | emu-figure {
142 | display: block;
143 | }
144 |
145 | emu-example {
146 | display: block;
147 | margin: 1em 3em;
148 | }
149 |
150 | emu-example figure figcaption {
151 | margin-top: 0.5em;
152 | text-align: left;
153 | }
154 |
155 | emu-figure figure,
156 | emu-example figure,
157 | emu-table figure {
158 | display: flex;
159 | flex-direction: column;
160 | align-items: center;
161 | }
162 |
163 | emu-production {
164 | display: block;
165 | margin-top: 1em;
166 | margin-bottom: 1em;
167 | margin-left: 5ex;
168 | }
169 |
170 | emu-grammar.inline, emu-production.inline,
171 | emu-grammar.inline emu-production emu-rhs, emu-production.inline emu-rhs,
172 | emu-grammar[collapsed] emu-production emu-rhs, emu-production[collapsed] emu-rhs {
173 | display: inline;
174 | padding-left: 1ex;
175 | margin-left: 0;
176 | }
177 |
178 | emu-grammar[collapsed] emu-production, emu-production[collapsed] {
179 | margin: 0;
180 | }
181 |
182 | emu-constraints {
183 | font-size: .75em;
184 | margin-right: 1ex;
185 | }
186 |
187 | emu-gann {
188 | margin-right: 1ex;
189 | }
190 |
191 | emu-gann emu-t:last-child,
192 | emu-gann emu-nt:last-child {
193 | margin-right: 0;
194 | }
195 |
196 | emu-geq {
197 | margin-left: 1ex;
198 | font-weight: bold;
199 | }
200 |
201 | emu-oneof {
202 | font-weight: bold;
203 | margin-left: 1ex;
204 | }
205 |
206 | emu-nt {
207 | display: inline-block;
208 | font-style: italic;
209 | white-space: nowrap;
210 | text-indent: 0;
211 | }
212 |
213 | emu-nt a, emu-nt a:visited {
214 | color: #333;
215 | }
216 |
217 | emu-rhs emu-nt {
218 | margin-right: 1ex;
219 | }
220 |
221 | emu-t {
222 | display: inline-block;
223 | font-family: monospace;
224 | font-weight: bold;
225 | white-space: nowrap;
226 | text-indent: 0;
227 | }
228 |
229 | emu-production emu-t {
230 | margin-right: 1ex;
231 | }
232 |
233 | emu-rhs {
234 | display: block;
235 | padding-left: 75px;
236 | text-indent: -25px;
237 | }
238 |
239 | emu-mods {
240 | font-size: .85em;
241 | vertical-align: sub;
242 | font-style: normal;
243 | font-weight: normal;
244 | }
245 |
246 | emu-production[collapsed] emu-mods {
247 | display: none;
248 | }
249 |
250 | emu-params, emu-opt {
251 | margin-right: 1ex;
252 | font-family: monospace;
253 | }
254 |
255 | emu-params, emu-constraints {
256 | color: #2aa198;
257 | }
258 |
259 | emu-opt {
260 | color: #b58900;
261 | }
262 |
263 | emu-gprose {
264 | font-size: 0.9em;
265 | font-family: Helvetica, Arial, sans-serif;
266 | }
267 |
268 | h1.shortname {
269 | color: #f60;
270 | font-size: 1.5em;
271 | margin: 0;
272 | }
273 |
274 | h1.version {
275 | color: #f60;
276 | font-size: 1.5em;
277 | margin: 0;
278 | }
279 |
280 | h1.title {
281 | margin-top: 0;
282 | color: #f60;
283 | }
284 |
285 | h1.first {
286 | margin-top: 0;
287 | }
288 |
289 | h1, h2, h3, h4, h5, h6 {
290 | position: relative;
291 | }
292 |
293 | h1 .secnum {
294 | text-decoration: none;
295 | margin-right: 10px;
296 | }
297 |
298 | h1 span.title {
299 | order: 2;
300 | }
301 |
302 |
303 | h1 { font-size: 2.67em; margin-top: 2em; margin-bottom: 0; line-height: 1em;}
304 | h2 { font-size: 2em; }
305 | h3 { font-size: 1.56em; }
306 | h4 { font-size: 1.25em; }
307 | h5 { font-size: 1.11em; }
308 | h6 { font-size: 1em; }
309 |
310 | h1:hover span.utils {
311 | display: block;
312 | }
313 |
314 | span.utils {
315 | font-size: 18px;
316 | line-height: 18px;
317 | display: none;
318 | position: absolute;
319 | top: 100%;
320 | left: 0;
321 | right: 0;
322 | font-weight: normal;
323 | }
324 |
325 | span.utils:before {
326 | content: "⤷";
327 | display: inline-block;
328 | padding: 0 5px;
329 | }
330 |
331 | span.utils > * {
332 | display: inline-block;
333 | margin-right: 20px;
334 | }
335 |
336 | h1 span.utils span.anchor a,
337 | h2 span.utils span.anchor a,
338 | h3 span.utils span.anchor a,
339 | h4 span.utils span.anchor a,
340 | h5 span.utils span.anchor a,
341 | h6 span.utils span.anchor a {
342 | text-decoration: none;
343 | font-variant: small-caps;
344 | }
345 |
346 | h1 span.utils span.anchor a:hover,
347 | h2 span.utils span.anchor a:hover,
348 | h3 span.utils span.anchor a:hover,
349 | h4 span.utils span.anchor a:hover,
350 | h5 span.utils span.anchor a:hover,
351 | h6 span.utils span.anchor a:hover {
352 | color: #333;
353 | }
354 |
355 | emu-intro h1, emu-clause h1, emu-annex h1 { font-size: 2em; }
356 | emu-intro h2, emu-clause h2, emu-annex h2 { font-size: 1.56em; }
357 | emu-intro h3, emu-clause h3, emu-annex h3 { font-size: 1.25em; }
358 | emu-intro h4, emu-clause h4, emu-annex h4 { font-size: 1.11em; }
359 | emu-intro h5, emu-clause h5, emu-annex h5 { font-size: 1em; }
360 | emu-intro h6, emu-clause h6, emu-annex h6 { font-size: 0.9em; }
361 | emu-intro emu-intro h1, emu-clause emu-clause h1, emu-annex emu-annex h1 { font-size: 1.56em; }
362 | emu-intro emu-intro h2, emu-clause emu-clause h2, emu-annex emu-annex h2 { font-size: 1.25em; }
363 | emu-intro emu-intro h3, emu-clause emu-clause h3, emu-annex emu-annex h3 { font-size: 1.11em; }
364 | emu-intro emu-intro h4, emu-clause emu-clause h4, emu-annex emu-annex h4 { font-size: 1em; }
365 | emu-intro emu-intro h5, emu-clause emu-clause h5, emu-annex emu-annex h5 { font-size: 0.9em; }
366 | emu-intro emu-intro emu-intro h1, emu-clause emu-clause emu-clause h1, emu-annex emu-annex emu-annex h1 { font-size: 1.25em; }
367 | emu-intro emu-intro emu-intro h2, emu-clause emu-clause emu-clause h2, emu-annex emu-annex emu-annex h2 { font-size: 1.11em; }
368 | emu-intro emu-intro emu-intro h3, emu-clause emu-clause emu-clause h3, emu-annex emu-annex emu-annex h3 { font-size: 1em; }
369 | emu-intro emu-intro emu-intro h4, emu-clause emu-clause emu-clause h4, emu-annex emu-annex emu-annex h4 { font-size: 0.9em; }
370 | emu-intro emu-intro emu-intro emu-intro h1, emu-clause emu-clause emu-clause emu-clause h1, emu-annex emu-annex emu-annex emu-annex h1 { font-size: 1.11em; }
371 | emu-intro emu-intro emu-intro emu-intro h2, emu-clause emu-clause emu-clause emu-clause h2, emu-annex emu-annex emu-annex emu-annex h2 { font-size: 1em; }
372 | emu-intro emu-intro emu-intro emu-intro h3, emu-clause emu-clause emu-clause emu-clause h3, emu-annex emu-annex emu-annex emu-annex h3 { font-size: 0.9em; }
373 | emu-intro emu-intro emu-intro emu-intro emu-intro h1, emu-clause emu-clause emu-clause emu-clause emu-clause h1, emu-annex emu-annex emu-annex emu-annex emu-annex h1 { font-size: 1em; }
374 | emu-intro emu-intro emu-intro emu-intro emu-intro h2, emu-clause emu-clause emu-clause emu-clause emu-clause h2, emu-annex emu-annex emu-annex emu-annex emu-annex h2 { font-size: 0.9em; }
375 | emu-intro emu-intro emu-intro emu-intro emu-intro emu-intro h1, emu-clause emu-clause emu-clause emu-clause emu-clause emu-clause h1, emu-annex emu-annex emu-annex emu-annex emu-annex emu-annex h1 { font-size: 0.9em }
376 |
377 | emu-clause, emu-intro, emu-annex {
378 | display: block;
379 | }
380 |
381 | /* Figures and tables */
382 | figure { display: block; margin: 1em 0 3em 0; }
383 | figure object { display: block; margin: 0 auto; }
384 | figure table.real-table { margin: 0 auto; }
385 | figure figcaption {
386 | display: block;
387 | color: #555555;
388 | font-weight: bold;
389 | text-align: center;
390 | }
391 |
392 | emu-table table {
393 | margin: 0 auto;
394 | }
395 |
396 | emu-table table, table.real-table {
397 | border-collapse: collapse;
398 | }
399 |
400 | emu-table td, emu-table th, table.real-table td, table.real-table th {
401 | border: 1px solid black;
402 | padding: 0.4em;
403 | vertical-align: baseline;
404 | }
405 | emu-table th, emu-table thead td, table.real-table th {
406 | background-color: #eeeeee;
407 | }
408 |
409 | /* Note: the left content edges of table.lightweight-table >tbody >tr >td
410 | and div.display line up. */
411 | table.lightweight-table {
412 | border-collapse: collapse;
413 | margin: 0 0 0 1.5em;
414 | }
415 | table.lightweight-table td, table.lightweight-table th {
416 | border: none;
417 | padding: 0 0.5em;
418 | vertical-align: baseline;
419 | }
420 |
421 | /* diff styles */
422 | ins {
423 | background-color: #e0f8e0;
424 | text-decoration: none;
425 | border-bottom: 1px solid #396;
426 | }
427 |
428 | del {
429 | background-color: #fee;
430 | }
431 |
432 | ins.block, del.block,
433 | emu-production > ins, emu-production > del,
434 | emu-grammar > ins, emu-grammar > del {
435 | display: block;
436 | }
437 |
438 | tr.ins > td > ins {
439 | border-bottom: none;
440 | }
441 |
442 | tr.ins > td {
443 | background-color: #e0f8e0;
444 | }
445 |
446 | tr.del > td {
447 | background-color: #fee;
448 | }
449 |
450 | /* Menu Styles */
451 | #menu-toggle {
452 | font-size: 2em;
453 |
454 | position: fixed;
455 | top: 0;
456 | left: 0;
457 | width: 1.5em;
458 | height: 1.5em;
459 | z-index: 3;
460 | visibility: hidden;
461 | color: #1567a2;
462 | background-color: #fff;
463 |
464 | line-height: 1.5em;
465 | text-align: center;
466 | -webkit-touch-callout: none;
467 | -webkit-user-select: none;
468 | -khtml-user-select: none;
469 | -moz-user-select: none;
470 | -ms-user-select: none;
471 | user-select: none;;
472 |
473 | cursor: pointer;
474 | }
475 |
476 | #menu {
477 | display: flex;
478 | flex-direction: column;
479 | width: 33%; height: 100vh;
480 | max-width: 500px;
481 | box-sizing: border-box;
482 | background-color: #ddd;
483 | overflow: hidden;
484 | transition: opacity 0.1s linear;
485 | padding: 0 5px;
486 | position: fixed;
487 | left: 0; top: 0;
488 | border-right: 2px solid #bbb;
489 |
490 | z-index: 2;
491 | }
492 |
493 | #menu-spacer {
494 | flex-basis: 33%;
495 | max-width: 500px;
496 | flex-grow: 0;
497 | flex-shrink: 0;
498 | }
499 |
500 | #menu a {
501 | color: #1567a2;
502 | }
503 |
504 | #menu.active {
505 | display: flex;
506 | opacity: 1;
507 | z-index: 2;
508 | }
509 |
510 | #menu-pins {
511 | flex-grow: 1;
512 | display: none;
513 | }
514 |
515 | #menu-pins.active {
516 | display: block;
517 | }
518 |
519 | #menu-pins-list {
520 | margin: 0;
521 | padding: 0;
522 | counter-reset: pins-counter;
523 | }
524 |
525 | #menu-pins-list > li:before {
526 | content: counter(pins-counter);
527 | counter-increment: pins-counter;
528 | display: inline-block;
529 | width: 25px;
530 | text-align: center;
531 | border: 1px solid #bbb;
532 | padding: 2px;
533 | margin: 4px;
534 | box-sizing: border-box;
535 | line-height: 1em;
536 | background-color: #ccc;
537 | border-radius: 4px;
538 | }
539 | #menu-toc > ol {
540 | padding: 0;
541 | flex-grow: 1;
542 | }
543 |
544 | #menu-toc > ol li {
545 | padding: 0;
546 | }
547 |
548 | #menu-toc > ol , #menu-toc > ol ol {
549 | list-style-type: none;
550 | margin: 0;
551 | padding: 0;
552 | }
553 |
554 | #menu-toc > ol ol {
555 | padding-left: 0.75em;
556 | }
557 |
558 | #menu-toc li {
559 | text-overflow: ellipsis;
560 | overflow: hidden;
561 | white-space: nowrap;
562 | }
563 |
564 | #menu-toc .item-toggle {
565 | display: inline-block;
566 | transform: rotate(-45deg) translate(-5px, -5px);
567 | transition: transform 0.1s ease;
568 | text-align: center;
569 | width: 20px;
570 |
571 | color: #aab;
572 |
573 | -webkit-touch-callout: none;
574 | -webkit-user-select: none;
575 | -khtml-user-select: none;
576 | -moz-user-select: none;
577 | -ms-user-select: none;
578 | user-select: none;;
579 |
580 | cursor: pointer;
581 | }
582 |
583 | #menu-toc .item-toggle-none {
584 | display: inline-block;
585 | width: 20px;
586 | }
587 |
588 | #menu-toc li.active > .item-toggle {
589 | transform: rotate(45deg) translate(-5px, -5px);
590 | }
591 |
592 | #menu-toc li > ol {
593 | display: none;
594 | }
595 |
596 | #menu-toc li.active > ol {
597 | display: block;
598 | }
599 |
600 | #menu-toc li.revealed > a {
601 | background-color: #bbb;
602 | font-weight: bold;
603 | /*
604 | background-color: #222;
605 | color: #c6d8e4;
606 | */
607 | }
608 |
609 | #menu-toc li.revealed-leaf> a {
610 | color: #206ca7;
611 | /*
612 | background-color: #222;
613 | color: #c6d8e4;
614 | */
615 | }
616 |
617 | #menu-toc li.revealed > .item-toggle {
618 | transform: rotate(45deg) translate(-5px, -5px);
619 | }
620 |
621 | #menu-toc li.revealed > ol {
622 | display: block;
623 | }
624 |
625 | #menu-toc li > a {
626 | padding: 2px 5px;
627 | }
628 |
629 | #menu > * {
630 | margin-bottom: 5px;
631 | }
632 |
633 | .menu-pane-header {
634 | padding: 0 5px;
635 | text-transform: uppercase;
636 | background-color: #aaa;
637 | color: #335;
638 | font-weight: bold;
639 | letter-spacing: 2px;
640 | flex-grow: 0;
641 | flex-shrink: 0;
642 | font-size: 0.8em;
643 | }
644 |
645 | #menu-toc {
646 | display: flex;
647 | flex-direction: column;
648 | width: 100%;
649 | overflow: hidden;
650 | flex-grow: 1;
651 | }
652 |
653 | #menu-toc ol.toc {
654 | overflow-x: hidden;
655 | overflow-y: auto;
656 | }
657 |
658 | #menu-search {
659 | position: relative;
660 | flex-grow: 0;
661 | flex-shrink: 0;
662 | width: 100%;
663 |
664 | display: flex;
665 | flex-direction: column;
666 |
667 | max-height: 300px;
668 | }
669 |
670 | #menu-trace-list {
671 | display: none;
672 | }
673 |
674 | #menu-search-box {
675 | box-sizing: border-box;
676 | display: block;
677 | width: 100%;
678 | margin: 5px 0 0 0;
679 | font-size: 1em;
680 | padding: 2px;
681 | background-color: #bbb;
682 | border: 1px solid #999;
683 | }
684 |
685 | #menu-search-results {
686 | overflow-x: hidden;
687 | overflow-y: auto;
688 | }
689 |
690 | li.menu-search-result-clause:before {
691 | content: 'clause';
692 | width: 40px;
693 | display: inline-block;
694 | text-align: right;
695 | padding-right: 1ex;
696 | color: #666;
697 | font-size: 75%;
698 | }
699 | li.menu-search-result-op:before {
700 | content: 'op';
701 | width: 40px;
702 | display: inline-block;
703 | text-align: right;
704 | padding-right: 1ex;
705 | color: #666;
706 | font-size: 75%;
707 | }
708 |
709 | li.menu-search-result-prod:before {
710 | content: 'prod';
711 | width: 40px;
712 | display: inline-block;
713 | text-align: right;
714 | padding-right: 1ex;
715 | color: #666;
716 | font-size: 75%
717 | }
718 |
719 |
720 | li.menu-search-result-term:before {
721 | content: 'term';
722 | width: 40px;
723 | display: inline-block;
724 | text-align: right;
725 | padding-right: 1ex;
726 | color: #666;
727 | font-size: 75%
728 | }
729 |
730 | #menu-search-results ul {
731 | padding: 0 5px;
732 | margin: 0;
733 | }
734 |
735 | #menu-search-results li {
736 | white-space: nowrap;
737 | text-overflow: ellipsis;
738 | }
739 |
740 |
741 | #menu-trace-list {
742 | counter-reset: item;
743 | margin: 0 0 0 20px;
744 | padding: 0;
745 | }
746 | #menu-trace-list li {
747 | display: block;
748 | white-space: nowrap;
749 | }
750 |
751 | #menu-trace-list li .secnum:after {
752 | content: " ";
753 | }
754 | #menu-trace-list li:before {
755 | content: counter(item) " ";
756 | background-color: #222;
757 | counter-increment: item;
758 | color: #999;
759 | width: 20px;
760 | height: 20px;
761 | line-height: 20px;
762 | display: inline-block;
763 | text-align: center;
764 | margin: 2px 4px 2px 0;
765 | }
766 |
767 | @media (max-width: 1000px) {
768 | body {
769 | margin: 0;
770 | display: block;
771 | }
772 |
773 | #menu {
774 | display: none;
775 | padding-top: 3em;
776 | width: 450px;
777 | }
778 |
779 | #menu.active {
780 | position: fixed;
781 | height: 100%;
782 | left: 0;
783 | top: 0;
784 | right: 300px;
785 | }
786 |
787 | #menu-toggle {
788 | visibility: visible;
789 | }
790 |
791 | #spec-container {
792 | padding: 0 5px;
793 | }
794 |
795 | #references-pane-spacer {
796 | display: none;
797 | }
798 | }
799 |
800 | @media only screen and (max-width: 800px) {
801 | #menu {
802 | width: 100%;
803 | }
804 |
805 | h1 .secnum:empty {
806 | margin: 0; padding: 0;
807 | }
808 | }
809 |
810 |
811 | /* Toolbox */
812 | .toolbox {
813 | position: absolute;
814 | background: #ddd;
815 | border: 1px solid #aaa;
816 | display: none;
817 | color: #eee;
818 | padding: 5px;
819 | border-radius: 3px;
820 | }
821 |
822 | .toolbox.active {
823 | display: inline-block;
824 | }
825 |
826 | .toolbox a {
827 | text-decoration: none;
828 | padding: 0 5px;
829 | }
830 |
831 | .toolbox a:hover {
832 | text-decoration: underline;
833 | }
834 |
835 | .toolbox:after, .toolbox:before {
836 | top: 100%;
837 | left: 15px;
838 | border: solid transparent;
839 | content: " ";
840 | height: 0;
841 | width: 0;
842 | position: absolute;
843 | pointer-events: none;
844 | }
845 |
846 | .toolbox:after {
847 | border-color: rgba(0, 0, 0, 0);
848 | border-top-color: #ddd;
849 | border-width: 10px;
850 | margin-left: -10px;
851 | }
852 | .toolbox:before {
853 | border-color: rgba(204, 204, 204, 0);
854 | border-top-color: #aaa;
855 | border-width: 12px;
856 | margin-left: -12px;
857 | }
858 |
859 | #references-pane-container {
860 | position: fixed;
861 | bottom: 0;
862 | left: 0;
863 | right: 0;
864 | height: 250px;
865 | display: none;
866 | background-color: #ddd;
867 | z-index: 1;
868 | }
869 |
870 | #references-pane-table-container {
871 | overflow-x: hidden;
872 | overflow-y: auto;
873 | }
874 |
875 | #references-pane-spacer {
876 | flex-basis: 33%;
877 | max-width: 500px;
878 | }
879 |
880 | #references-pane {
881 | flex-grow: 1;
882 | overflow: hidden;
883 | display: flex;
884 | flex-direction: column;
885 | }
886 |
887 | #references-pane-container.active {
888 | display: flex;
889 | }
890 |
891 | #references-pane-close:after {
892 | content: '✖';
893 | float: right;
894 | cursor: pointer;
895 | }
896 |
897 | #references-pane table tr td:first-child {
898 | text-align: right;
899 | padding-right: 5px;
900 | }
901 |
--------------------------------------------------------------------------------
/spec.emu:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | title: Promise.prototype.finally
8 | stage: 4
9 | contributors: Jordan Harband
10 |
11 |
12 |
13 | Promise.prototype.finally ( _onFinally_ )
14 | When the `finally` method is called with argument _onFinally_, the following steps are taken:
15 |
16 | 1. Let _promise_ be the *this* value.
17 | 1. If Type(_promise_) is not Object, throw a *TypeError* exception.
18 | 1. Let _C_ be ? SpeciesConstructor(_promise_, %Promise%).
19 | 1. Assert: IsConstructor(_C_) is *true*.
20 | 1. If IsCallable(_onFinally_) is *false*,
21 | 1. Let _thenFinally_ be _onFinally_.
22 | 1. Let _catchFinally_ be _onFinally_.
23 | 1. Else,
24 | 1. Let _thenFinally_ be a new built-in function object as defined in ThenFinally Function .
25 | 1. Let _catchFinally_ be a new built-in function object as defined in CatchFinally Function .
26 | 1. Set _thenFinally_ and _catchFinally_'s [[Constructor]] internal slots to _C_.
27 | 1. Set _thenFinally_ and _catchFinally_'s [[OnFinally]] internal slots to _onFinally_.
28 | 1. Return ? Invoke(_promise_, `"then"`, « _thenFinally_, _catchFinally_ »).
29 |
30 |
31 |
32 | ThenFinally Function
33 | A ThenFinally function is an anonymous built-in function that has a [[Constructor]] and an [[OnFinally]] internal slot. The value of the [[Constructor]] internal slot is a `Promise`-like constructor function object, and the value of the [[OnFinally]] internal slot is a function object.
34 | When a ThenFinally function _F_ is called with argument _value_, the following steps are taken:
35 |
36 | 1. Let _onFinally_ be _F_.[[OnFinally]].
37 | 1. Assert: IsCallable(_onFinally_) is *true*.
38 | 1. Let _result_ be ? Call(_onFinally_, *undefined*).
39 | 1. Let _C_ be _F_.[[Constructor]].
40 | 1. Assert: IsConstructor(_C_) is *true*.
41 | 1. Let _promise_ be ? PromiseResolve(_C_, _result_).
42 | 1. Let _valueThunk_ be equivalent to a function that returns _value_.
43 | 1. Return ? Invoke(_promise_, `"then"`, « _valueThunk_ »).
44 |
45 |
46 |
47 |
48 | CatchFinally Function
49 | A CatchFinally function is an anonymous built-in function that has a [[Constructor]] and an [[OnFinally]] internal slot. The value of the [[Constructor]] internal slot is a `Promise`-like constructor function object, and the value of the [[OnFinally]] internal slot is a function object.
50 | When a CatchFinally function _F_ is called with argument _reason_, the following steps are taken:
51 |
52 | 1. Let _onFinally_ be _F_.[[OnFinally]].
53 | 1. Assert: IsCallable(_onFinally_) is *true*.
54 | 1. Let _result_ be ? Call(_onFinally_, *undefined*).
55 | 1. Let _C_ be _F_.[[Constructor]].
56 | 1. Assert: IsConstructor(_C_) is *true*.
57 | 1. Let _promise_ be ? PromiseResolve(_C_, _result_).
58 | 1. Let _thrower_ be equivalent to a function that throws _reason_.
59 | 1. Return ? Invoke(_promise_, `"then"`, « _thrower_ »).
60 |
61 |
62 |
63 |
64 |
65 |
66 | Promise.resolve ( _x_ )
67 | The `resolve` function returns either a new promise resolved with the passed argument, or the argument itself if the argument is a promise produced by this constructor.
68 |
69 | 1. Let _C_ be the *this* value.
70 | 1. If Type(_C_) is not Object, throw a *TypeError* exception.
71 | 1. Return ? PromiseResolve(_C_, _x_).
72 |
73 |
74 | The `resolve` function expects its *this* value to be a constructor function that supports the parameter conventions of the `Promise` constructor.
75 |
76 |
77 |
78 |
79 | PromiseResolve ( _C_, _x_ )
80 | The abstract operation PromiseResolve, given a constructor and a value, returns a new promise resolved with that value.
81 |
82 | 1. Assert: Type(_C_) is Object.
83 | 1. If IsPromise(_x_) is *true*, then
84 | 1. Let _xConstructor_ be ? Get(_x_, `"constructor"`).
85 | 1. If SameValue(_xConstructor_, _C_) is *true*, return _x_.
86 | 1. Let _promiseCapability_ be ? NewPromiseCapability(_C_).
87 | 1. Perform ? Call(_promiseCapability_.[[Resolve]], *undefined*, « _x_ »).
88 | 1. Return _promiseCapability_.[[Promise]].
89 |
90 |
91 |
--------------------------------------------------------------------------------
/spec.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | function Search(menu) {
4 | this.menu = menu;
5 | this.$search = document.getElementById('menu-search');
6 | this.$searchBox = document.getElementById('menu-search-box');
7 | this.$searchResults = document.getElementById('menu-search-results');
8 |
9 | this.loadBiblio();
10 |
11 | document.addEventListener('keydown', this.documentKeydown.bind(this));
12 |
13 | this.$searchBox.addEventListener('keydown', debounce(this.searchBoxKeydown.bind(this), { stopPropagation: true }));
14 | this.$searchBox.addEventListener('keyup', debounce(this.searchBoxKeyup.bind(this), { stopPropagation: true }));
15 | }
16 |
17 | Search.prototype.loadBiblio = function () {
18 | var $biblio = document.getElementById('menu-search-biblio');
19 | if (!$biblio) {
20 | this.biblio = [];
21 | } else {
22 | this.biblio = JSON.parse($biblio.textContent);
23 | this.biblio.clauses = this.biblio.filter(function (e) { return e.type === 'clause' });
24 | this.biblio.byId = this.biblio.reduce(function (map, entry) {
25 | map[entry.id] = entry;
26 | return map;
27 | }, {});
28 | }
29 | }
30 |
31 | Search.prototype.documentKeydown = function (e) {
32 | if (e.keyCode === 191) {
33 | e.preventDefault();
34 | e.stopPropagation();
35 | this.triggerSearch();
36 | }
37 | }
38 |
39 | Search.prototype.searchBoxKeydown = function (e) {
40 | e.stopPropagation();
41 | e.preventDefault();
42 | if (e.keyCode === 191 && e.target.value.length === 0) {
43 | e.preventDefault();
44 | } else if (e.keyCode === 13) {
45 | e.preventDefault();
46 | this.selectResult();
47 | }
48 | }
49 |
50 | Search.prototype.searchBoxKeyup = function (e) {
51 | if (e.keyCode === 13 || e.keyCode === 9) {
52 | return;
53 | }
54 |
55 | this.search(e.target.value);
56 | }
57 |
58 |
59 | Search.prototype.triggerSearch = function (e) {
60 | if (this.menu.isVisible()) {
61 | this._closeAfterSearch = false;
62 | } else {
63 | this._closeAfterSearch = true;
64 | this.menu.show();
65 | }
66 |
67 | this.$searchBox.focus();
68 | this.$searchBox.select();
69 | }
70 | // bit 12 - Set if the result starts with searchString
71 | // bits 8-11: 8 - number of chunks multiplied by 2 if cases match, otherwise 1.
72 | // bits 1-7: 127 - length of the entry
73 | // General scheme: prefer case sensitive matches with fewer chunks, and otherwise
74 | // prefer shorter matches.
75 | function relevance(result, searchString) {
76 | var relevance = 0;
77 |
78 | relevance = Math.max(0, 8 - result.match.chunks) << 7;
79 |
80 | if (result.match.caseMatch) {
81 | relevance *= 2;
82 | }
83 |
84 | if (result.match.prefix) {
85 | relevance += 2048
86 | }
87 |
88 | relevance += Math.max(0, 255 - result.entry.key.length);
89 |
90 | return relevance;
91 | }
92 |
93 | Search.prototype.search = function (searchString) {
94 | var s = Date.now();
95 |
96 | if (searchString === '') {
97 | this.displayResults([]);
98 | this.hideSearch();
99 | return;
100 | } else {
101 | this.showSearch();
102 | }
103 |
104 | if (searchString.length === 1) {
105 | this.displayResults([]);
106 | return;
107 | }
108 |
109 | var results;
110 |
111 | if (/^[\d\.]*$/.test(searchString)) {
112 | results = this.biblio.clauses.filter(function (clause) {
113 | return clause.number.substring(0, searchString.length) === searchString;
114 | }).map(function (clause) {
115 | return { entry: clause };
116 | });
117 | } else {
118 | results = [];
119 |
120 | for (var i = 0; i < this.biblio.length; i++) {
121 | var entry = this.biblio[i];
122 |
123 | var match = fuzzysearch(searchString, entry.key);
124 | if (match) {
125 | results.push({ entry: entry, match: match });
126 | }
127 | }
128 |
129 | results.forEach(function (result) {
130 | result.relevance = relevance(result, searchString);
131 | });
132 |
133 | results = results.sort(function (a, b) { return b.relevance - a.relevance });
134 |
135 | }
136 |
137 | if (results.length > 50) {
138 | results = results.slice(0, 50);
139 | }
140 |
141 | this.displayResults(results);
142 | }
143 | Search.prototype.hideSearch = function () {
144 | this.$search.classList.remove('active');
145 | }
146 |
147 | Search.prototype.showSearch = function () {
148 | this.$search.classList.add('active');
149 | }
150 |
151 | Search.prototype.selectResult = function () {
152 | var $first = this.$searchResults.querySelector('li:first-child a');
153 |
154 | if ($first) {
155 | document.location = $first.getAttribute('href');
156 | }
157 |
158 | this.$searchBox.value = '';
159 | this.$searchBox.blur();
160 | this.displayResults([]);
161 | this.hideSearch();
162 |
163 | if (this._closeAfterSearch) {
164 | this.menu.hide();
165 | }
166 | }
167 |
168 | Search.prototype.displayResults = function (results) {
169 | if (results.length > 0) {
170 | this.$searchResults.classList.remove('no-results');
171 |
172 | var html = '';
173 |
174 | results.forEach(function (result) {
175 | var entry = result.entry;
176 | var id = entry.id;
177 | var cssClass = '';
178 | var text = '';
179 |
180 | if (entry.type === 'clause') {
181 | var number = entry.number ? entry.number + ' ' : '';
182 | text = number + entry.key;
183 | cssClass = 'clause';
184 | id = entry.id;
185 | } else if (entry.type === 'production') {
186 | text = entry.key;
187 | cssClass = 'prod';
188 | id = entry.id;
189 | } else if (entry.type === 'op') {
190 | text = entry.key;
191 | cssClass = 'op';
192 | id = entry.id || entry.refId;
193 | } else if (entry.type === 'term') {
194 | text = entry.key;
195 | cssClass = 'term';
196 | id = entry.id || entry.refId;
197 | }
198 |
199 | if (text) {
200 | html += ''
201 | }
202 | });
203 |
204 | html += ' '
205 |
206 | this.$searchResults.innerHTML = html;
207 | } else {
208 | this.$searchResults.innerHTML = '';
209 | this.$searchResults.classList.add('no-results');
210 | }
211 | }
212 |
213 |
214 | function Menu() {
215 | this.$toggle = document.getElementById('menu-toggle');
216 | this.$menu = document.getElementById('menu');
217 | this.$toc = document.querySelector('menu-toc > ol');
218 | this.$pins = document.querySelector('#menu-pins');
219 | this.$pinList = document.getElementById('menu-pins-list');
220 | this.$toc = document.querySelector('#menu-toc > ol');
221 | this.$specContainer = document.getElementById('spec-container');
222 | this.search = new Search(this);
223 |
224 | this._pinnedIds = {};
225 | this.loadPinEntries();
226 |
227 | // toggle menu
228 | this.$toggle.addEventListener('click', this.toggle.bind(this));
229 |
230 | // keydown events for pinned clauses
231 | document.addEventListener('keydown', this.documentKeydown.bind(this));
232 |
233 | // toc expansion
234 | var tocItems = this.$menu.querySelectorAll('#menu-toc li');
235 | for (var i = 0; i < tocItems.length; i++) {
236 | var $item = tocItems[i];
237 | $item.addEventListener('click', function($item, event) {
238 | $item.classList.toggle('active');
239 | event.stopPropagation();
240 | }.bind(null, $item));
241 | }
242 |
243 | // close toc on toc item selection
244 | var tocLinks = this.$menu.querySelectorAll('#menu-toc li > a');
245 | for (var i = 0; i < tocLinks.length; i++) {
246 | var $link = tocLinks[i];
247 | $link.addEventListener('click', function(event) {
248 | this.toggle();
249 | event.stopPropagation();
250 | }.bind(this));
251 | }
252 |
253 | // update active clause on scroll
254 | window.addEventListener('scroll', debounce(this.updateActiveClause.bind(this)));
255 | this.updateActiveClause();
256 |
257 | // prevent menu scrolling from scrolling the body
258 | this.$toc.addEventListener('wheel', function (e) {
259 | var target = e.currentTarget;
260 | var offTop = e.deltaY < 0 && target.scrollTop === 0;
261 | if (offTop) {
262 | e.preventDefault();
263 | }
264 | var offBottom = e.deltaY > 0
265 | && target.offsetHeight + target.scrollTop >= target.scrollHeight;
266 |
267 | if (offBottom) {
268 | e.preventDefault();
269 | }
270 | })
271 | }
272 |
273 | Menu.prototype.documentKeydown = function (e) {
274 | e.stopPropagation();
275 | if (e.keyCode === 80) {
276 | this.togglePinEntry();
277 | } else if (e.keyCode > 48 && e.keyCode < 58) {
278 | this.selectPin(e.keyCode - 49);
279 | }
280 | }
281 |
282 | Menu.prototype.updateActiveClause = function () {
283 | this.setActiveClause(findActiveClause(this.$specContainer))
284 | }
285 |
286 | Menu.prototype.setActiveClause = function (clause) {
287 | this.$activeClause = clause;
288 | this.revealInToc(this.$activeClause);
289 | }
290 |
291 | Menu.prototype.revealInToc = function (path) {
292 | var current = this.$toc.querySelectorAll('li.revealed');
293 | for (var i = 0; i < current.length; i++) {
294 | current[i].classList.remove('revealed');
295 | current[i].classList.remove('revealed-leaf');
296 | }
297 |
298 | var current = this.$toc;
299 | var index = 0;
300 | while (index < path.length) {
301 | var children = current.children;
302 | for (var i = 0; i < children.length; i++) {
303 | if ('#' + path[index].id === children[i].children[1].getAttribute('href') ) {
304 | children[i].classList.add('revealed');
305 | if (index === path.length - 1) {
306 | children[i].classList.add('revealed-leaf');
307 | var rect = children[i].getBoundingClientRect();
308 | this.$toc.getBoundingClientRect().top
309 | var tocRect = this.$toc.getBoundingClientRect();
310 | if (rect.top + 10 > tocRect.bottom) {
311 | this.$toc.scrollTop = this.$toc.scrollTop + (rect.top - tocRect.bottom) + (rect.bottom - rect.top);
312 | } else if (rect.top < tocRect.top) {
313 | this.$toc.scrollTop = this.$toc.scrollTop - (tocRect.top - rect.top);
314 | }
315 | }
316 | current = children[i].querySelector('ol');
317 | index++;
318 | break;
319 | }
320 | }
321 |
322 | }
323 | }
324 |
325 | function findActiveClause(root, path) {
326 | var clauses = new ClauseWalker(root);
327 | var $clause;
328 | var found = false;
329 | var path = path || [];
330 |
331 | while ($clause = clauses.nextNode()) {
332 | var rect = $clause.getBoundingClientRect();
333 | var $header = $clause.children[0];
334 | var marginTop = parseInt(getComputedStyle($header)["margin-top"]);
335 |
336 | if ((rect.top - marginTop) <= 0 && rect.bottom > 0) {
337 | found = true;
338 | return findActiveClause($clause, path.concat($clause)) || path;
339 | }
340 | }
341 |
342 | return path;
343 | }
344 |
345 | function ClauseWalker(root) {
346 | var previous;
347 | var treeWalker = document.createTreeWalker(
348 | root,
349 | NodeFilter.SHOW_ELEMENT,
350 | {
351 | acceptNode: function (node) {
352 | if (previous === node.parentNode) {
353 | return NodeFilter.FILTER_REJECT;
354 | } else {
355 | previous = node;
356 | }
357 | if (node.nodeName === 'EMU-CLAUSE' || node.nodeName === 'EMU-INTRO' || node.nodeName === 'EMU-ANNEX') {
358 | return NodeFilter.FILTER_ACCEPT;
359 | } else {
360 | return NodeFilter.FILTER_SKIP;
361 | }
362 | }
363 | },
364 | false
365 | );
366 |
367 | return treeWalker;
368 | }
369 |
370 | Menu.prototype.toggle = function () {
371 | this.$menu.classList.toggle('active');
372 | }
373 |
374 | Menu.prototype.show = function () {
375 | this.$menu.classList.add('active');
376 | }
377 |
378 | Menu.prototype.hide = function () {
379 | this.$menu.classList.remove('active');
380 | }
381 |
382 | Menu.prototype.isVisible = function() {
383 | return this.$menu.classList.contains('active');
384 | }
385 |
386 | Menu.prototype.showPins = function () {
387 | this.$pins.classList.add('active');
388 | }
389 |
390 | Menu.prototype.hidePins = function () {
391 | this.$pins.classList.remove('active');
392 | }
393 |
394 | Menu.prototype.addPinEntry = function (id) {
395 | var entry = this.search.biblio.byId[id];
396 | if (!entry) {
397 | // id was deleted after pin (or something) so remove it
398 | delete this._pinnedIds[id];
399 | this.persistPinEntries();
400 | return;
401 | }
402 |
403 | if (entry.type === 'clause') {
404 | var prefix;
405 | if (entry.number) {
406 | prefix = entry.number + ' ';
407 | } else {
408 | prefix = '';
409 | }
410 | this.$pinList.innerHTML += '' + prefix + entry.titleHTML + ' ';
411 | } else {
412 | this.$pinList.innerHTML += '' + entry.key + ' ';
413 | }
414 |
415 | if (Object.keys(this._pinnedIds).length === 0) {
416 | this.showPins();
417 | }
418 | this._pinnedIds[id] = true;
419 | this.persistPinEntries();
420 | }
421 |
422 | Menu.prototype.removePinEntry = function (id) {
423 | var item = this.$pinList.querySelector('a[href="#' + id + '"]').parentNode;
424 | this.$pinList.removeChild(item);
425 | delete this._pinnedIds[id];
426 | if (Object.keys(this._pinnedIds).length === 0) {
427 | this.hidePins();
428 | }
429 |
430 | this.persistPinEntries();
431 | }
432 |
433 | Menu.prototype.persistPinEntries = function () {
434 | try {
435 | if (!window.localStorage) return;
436 | } catch (e) {
437 | return;
438 | }
439 |
440 | localStorage.pinEntries = JSON.stringify(Object.keys(this._pinnedIds));
441 | }
442 |
443 | Menu.prototype.loadPinEntries = function () {
444 | try {
445 | if (!window.localStorage) return;
446 | } catch (e) {
447 | return;
448 | }
449 |
450 | var pinsString = window.localStorage.pinEntries;
451 | if (!pinsString) return;
452 | var pins = JSON.parse(pinsString);
453 | for(var i = 0; i < pins.length; i++) {
454 | this.addPinEntry(pins[i]);
455 | }
456 | }
457 |
458 | Menu.prototype.togglePinEntry = function (id) {
459 | if (!id) {
460 | id = this.$activeClause[this.$activeClause.length - 1].id;
461 | }
462 |
463 | if (this._pinnedIds[id]) {
464 | this.removePinEntry(id);
465 | } else {
466 | this.addPinEntry(id);
467 | }
468 | }
469 |
470 | Menu.prototype.selectPin = function (num) {
471 | document.location = this.$pinList.children[num].children[0].href;
472 | }
473 |
474 | var menu;
475 | function init() {
476 | menu = new Menu();
477 | var $container = document.getElementById('spec-container');
478 | $container.addEventListener('mouseover', debounce(function (e) {
479 | Toolbox.activateIfMouseOver(e);
480 | }));
481 | }
482 |
483 | document.addEventListener('DOMContentLoaded', init);
484 |
485 | function debounce(fn, opts) {
486 | opts = opts || {};
487 | var timeout;
488 | return function(e) {
489 | if (opts.stopPropagation) {
490 | e.stopPropagation();
491 | }
492 | var args = arguments;
493 | if (timeout) {
494 | clearTimeout(timeout);
495 | }
496 | timeout = setTimeout(function() {
497 | timeout = null;
498 | fn.apply(this, args);
499 | }.bind(this), 150);
500 | }
501 | }
502 |
503 | var CLAUSE_NODES = ['EMU-CLAUSE', 'EMU-INTRO', 'EMU-ANNEX'];
504 | function findLocalReferences ($elem) {
505 | var name = $elem.innerHTML;
506 | var references = [];
507 |
508 | var parentClause = $elem.parentNode;
509 | while (parentClause && CLAUSE_NODES.indexOf(parentClause.nodeName) === -1) {
510 | parentClause = parentClause.parentNode;
511 | }
512 |
513 | if(!parentClause) return;
514 |
515 | var vars = parentClause.querySelectorAll('var');
516 |
517 | for (var i = 0; i < vars.length; i++) {
518 | var $var = vars[i];
519 |
520 | if ($var.innerHTML === name) {
521 | references.push($var);
522 | }
523 | }
524 |
525 | return references;
526 | }
527 |
528 | function toggleFindLocalReferences($elem) {
529 | var references = findLocalReferences($elem);
530 | if ($elem.classList.contains('referenced')) {
531 | references.forEach(function ($reference) {
532 | $reference.classList.remove('referenced');
533 | });
534 | } else {
535 | references.forEach(function ($reference) {
536 | $reference.classList.add('referenced');
537 | });
538 | }
539 | }
540 |
541 | function installFindLocalReferences () {
542 | document.addEventListener('click', function (e) {
543 | if (e.target.nodeName === 'VAR') {
544 | toggleFindLocalReferences(e.target);
545 | }
546 | });
547 | }
548 |
549 | document.addEventListener('DOMContentLoaded', installFindLocalReferences);
550 |
551 |
552 |
553 |
554 | // The following license applies to the fuzzysearch function
555 | // The MIT License (MIT)
556 | // Copyright © 2015 Nicolas Bevacqua
557 | // Copyright © 2016 Brian Terlson
558 | // Permission is hereby granted, free of charge, to any person obtaining a copy of
559 | // this software and associated documentation files (the "Software"), to deal in
560 | // the Software without restriction, including without limitation the rights to
561 | // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
562 | // the Software, and to permit persons to whom the Software is furnished to do so,
563 | // subject to the following conditions:
564 |
565 | // The above copyright notice and this permission notice shall be included in all
566 | // copies or substantial portions of the Software.
567 |
568 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
569 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
570 | // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
571 | // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
572 | // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
573 | // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
574 | function fuzzysearch (searchString, haystack, caseInsensitive) {
575 | var tlen = haystack.length;
576 | var qlen = searchString.length;
577 | var chunks = 1;
578 | var finding = false;
579 | var prefix = true;
580 |
581 | if (qlen > tlen) {
582 | return false;
583 | }
584 |
585 | if (qlen === tlen) {
586 | if (searchString === haystack) {
587 | return { caseMatch: true, chunks: 1, prefix: true };
588 | } else if (searchString.toLowerCase() === haystack.toLowerCase()) {
589 | return { caseMatch: false, chunks: 1, prefix: true };
590 | } else {
591 | return false;
592 | }
593 | }
594 |
595 | outer: for (var i = 0, j = 0; i < qlen; i++) {
596 | var nch = searchString[i];
597 | while (j < tlen) {
598 | var targetChar = haystack[j++];
599 | if (targetChar === nch) {
600 | finding = true;
601 | continue outer;
602 | }
603 | if (finding) {
604 | chunks++;
605 | finding = false;
606 | }
607 | }
608 |
609 | if (caseInsensitive) { return false }
610 |
611 | return fuzzysearch(searchString.toLowerCase(), haystack.toLowerCase(), true);
612 | }
613 |
614 | return { caseMatch: !caseInsensitive, chunks: chunks, prefix: j <= qlen };
615 | }
616 |
617 | var Toolbox = {
618 | init: function () {
619 | this.$container = document.createElement('div');
620 | this.$container.classList.add('toolbox');
621 | this.$permalink = document.createElement('a');
622 | this.$permalink.textContent = 'Permalink';
623 | this.$pinLink = document.createElement('a');
624 | this.$pinLink.textContent = 'Pin';
625 | this.$pinLink.setAttribute('href', '#');
626 | this.$pinLink.addEventListener('click', function (e) {
627 | e.preventDefault();
628 | e.stopPropagation();
629 | menu.togglePinEntry(this.entry.id);
630 | }.bind(this));
631 |
632 | this.$refsLink = document.createElement('a');
633 | this.$refsLink.setAttribute('href', '#');
634 | this.$refsLink.addEventListener('click', function (e) {
635 | e.preventDefault();
636 | e.stopPropagation();
637 | referencePane.showReferencesFor(this.entry);
638 | }.bind(this));
639 | this.$container.appendChild(this.$permalink);
640 | this.$container.appendChild(this.$pinLink);
641 | this.$container.appendChild(this.$refsLink);
642 | document.body.appendChild(this.$container);
643 | },
644 |
645 | activate: function (el, entry, target) {
646 | if (el === this._activeEl) return;
647 | this.active = true;
648 | this.entry = entry;
649 | this.$container.classList.add('active');
650 | this.top = el.offsetTop - this.$container.offsetHeight - 10;
651 | this.left = el.offsetLeft;
652 | this.$container.setAttribute('style', 'left: ' + this.left + 'px; top: ' + this.top + 'px');
653 | this.updatePermalink();
654 | this.updateReferences();
655 | this._activeEl = el;
656 | if (this.top < document.body.scrollTop && el === target) {
657 | // don't scroll unless it's a small thing (< 200px)
658 | this.$container.scrollIntoView();
659 | }
660 | },
661 |
662 | updatePermalink: function () {
663 | this.$permalink.setAttribute('href', '#' + this.entry.id);
664 | },
665 |
666 | updateReferences: function () {
667 | this.$refsLink.textContent = 'References (' + this.entry.referencingIds.length + ')';
668 | },
669 |
670 | activateIfMouseOver: function (e) {
671 | var ref = this.findReferenceUnder(e.target);
672 | if (ref && (!this.active || e.pageY > this._activeEl.offsetTop)) {
673 | var entry = menu.search.biblio.byId[ref.id];
674 | this.activate(ref.element, entry, e.target);
675 | } else if (this.active && ((e.pageY < this.top) || e.pageY > (this._activeEl.offsetTop + this._activeEl.offsetHeight))) {
676 | this.deactivate();
677 | }
678 | },
679 |
680 | findReferenceUnder: function (el) {
681 | while (el) {
682 | var parent = el.parentNode;
683 | if (el.nodeName === 'H1' && parent.nodeName.match(/EMU-CLAUSE|EMU-ANNEX|EMU-INTRO/) && parent.id) {
684 | return { element: el, id: parent.id };
685 | } else if (el.nodeName.match(/EMU-(?!CLAUSE|XREF|ANNEX|INTRO)|DFN/) &&
686 | el.id && el.id[0] !== '_') {
687 | if (el.nodeName === 'EMU-FIGURE' || el.nodeName === 'EMU-TABLE' || el.nodeName === 'EMU-EXAMPLE') {
688 | // return the figcaption element
689 | return { element: el.children[0].children[0], id: el.id };
690 | } else if (el.nodeName === 'EMU-PRODUCTION') {
691 | // return the LHS non-terminal element
692 | return { element: el.children[0], id: el.id };
693 | } else {
694 | return { element: el, id: el.id };
695 | }
696 | }
697 | el = parent;
698 | }
699 | },
700 |
701 | deactivate: function () {
702 | this.$container.classList.remove('active');
703 | this._activeEl = null;
704 | this.activeElBounds = null;
705 | this.active = false;
706 | }
707 | }
708 |
709 | var referencePane = {
710 | init: function() {
711 | this.$container = document.createElement('div');
712 | this.$container.setAttribute('id', 'references-pane-container');
713 |
714 | var $spacer = document.createElement('div');
715 | $spacer.setAttribute('id', 'references-pane-spacer');
716 |
717 | this.$pane = document.createElement('div');
718 | this.$pane.setAttribute('id', 'references-pane');
719 |
720 | this.$container.appendChild($spacer);
721 | this.$container.appendChild(this.$pane);
722 |
723 | this.$header = document.createElement('div');
724 | this.$header.classList.add('menu-pane-header');
725 | this.$header.textContent = 'References to ';
726 | this.$headerRefId = document.createElement('a');
727 | this.$header.appendChild(this.$headerRefId);
728 | this.$closeButton = document.createElement('span');
729 | this.$closeButton.setAttribute('id', 'references-pane-close');
730 | this.$closeButton.addEventListener('click', function (e) {
731 | this.deactivate();
732 | }.bind(this));
733 | this.$header.appendChild(this.$closeButton);
734 |
735 | this.$pane.appendChild(this.$header);
736 | var tableContainer = document.createElement('div');
737 | tableContainer.setAttribute('id', 'references-pane-table-container');
738 |
739 | this.$table = document.createElement('table');
740 | this.$table.setAttribute('id', 'references-pane-table');
741 |
742 | this.$tableBody = this.$table.createTBody();
743 |
744 | tableContainer.appendChild(this.$table);
745 | this.$pane.appendChild(tableContainer);
746 |
747 | menu.$specContainer.appendChild(this.$container);
748 | },
749 |
750 | activate: function () {
751 | this.$container.classList.add('active');
752 | },
753 |
754 | deactivate: function () {
755 | this.$container.classList.remove('active');
756 | },
757 |
758 | showReferencesFor(entry) {
759 | this.activate();
760 | var newBody = document.createElement('tbody');
761 | var previousId;
762 | var previousCell;
763 | var dupCount = 0;
764 | this.$headerRefId.textContent = '#' + entry.id;
765 | this.$headerRefId.setAttribute('href', '#' + entry.id);
766 | entry.referencingIds.map(function (id) {
767 | var target = document.getElementById(id);
768 | var cid = findParentClauseId(target);
769 | var clause = menu.search.biblio.byId[cid];
770 | var dupCount = 0;
771 | return { id: id, clause: clause }
772 | }).sort(function (a, b) {
773 | return sortByClauseNumber(a.clause, b.clause);
774 | }).forEach(function (record, i) {
775 | if (previousId === record.clause.id) {
776 | previousCell.innerHTML += ' (' + (dupCount + 2) + ' )';
777 | dupCount++;
778 | } else {
779 | var row = newBody.insertRow();
780 | var cell = row.insertCell();
781 | cell.innerHTML = record.clause.number;
782 | cell = row.insertCell();
783 | cell.innerHTML = '' + record.clause.titleHTML + ' ';
784 | previousCell = cell;
785 | previousId = record.clause.id;
786 | dupCount = 0;
787 | }
788 | }, this);
789 | this.$table.removeChild(this.$tableBody);
790 | this.$tableBody = newBody;
791 | this.$table.appendChild(this.$tableBody);
792 | }
793 | }
794 | function findParentClauseId(node) {
795 | while (node && node.nodeName !== 'EMU-CLAUSE' && node.nodeName !== 'EMU-INTRO' && node.nodeName !== 'EMU-ANNEX') {
796 | node = node.parentNode;
797 | }
798 | if (!node) return null;
799 | return node.getAttribute('id');
800 | }
801 |
802 | function sortByClauseNumber(c1, c2) {
803 | var c1c = c1.number.split('.');
804 | var c2c = c2.number.split('.');
805 |
806 | for (var i = 0; i < c1c.length; i++) {
807 | if (i >= c2c.length) {
808 | return 1;
809 | }
810 |
811 | var c1 = c1c[i];
812 | var c2 = c2c[i];
813 | var c1cn = Number(c1);
814 | var c2cn = Number(c2);
815 |
816 | if (Number.isNaN(c1cn) && Number.isNaN(c2cn)) {
817 | if (c1 > c2) {
818 | return 1;
819 | } else if (c1 < c2) {
820 | return -1;
821 | }
822 | } else if (!Number.isNaN(c1cn) && Number.isNaN(c2cn)) {
823 | return -1;
824 | } else if (Number.isNaN(c1cn) && !Number.isNaN(c2cn)) {
825 | return 1;
826 | } else if(c1cn > c2cn) {
827 | return 1;
828 | } else if (c1cn < c2cn) {
829 | return -1;
830 | }
831 | }
832 |
833 | if (c1c.length === c2c.length) {
834 | return 0;
835 | }
836 | return -1;
837 | }
838 |
839 | document.addEventListener('DOMContentLoaded', function () {
840 | Toolbox.init();
841 | referencePane.init();
842 | })
843 | var CLAUSE_NODES = ['EMU-CLAUSE', 'EMU-INTRO', 'EMU-ANNEX'];
844 | function findLocalReferences ($elem) {
845 | var name = $elem.innerHTML;
846 | var references = [];
847 |
848 | var parentClause = $elem.parentNode;
849 | while (parentClause && CLAUSE_NODES.indexOf(parentClause.nodeName) === -1) {
850 | parentClause = parentClause.parentNode;
851 | }
852 |
853 | if(!parentClause) return;
854 |
855 | var vars = parentClause.querySelectorAll('var');
856 |
857 | for (var i = 0; i < vars.length; i++) {
858 | var $var = vars[i];
859 |
860 | if ($var.innerHTML === name) {
861 | references.push($var);
862 | }
863 | }
864 |
865 | return references;
866 | }
867 |
868 | function toggleFindLocalReferences($elem) {
869 | var references = findLocalReferences($elem);
870 | if ($elem.classList.contains('referenced')) {
871 | references.forEach(function ($reference) {
872 | $reference.classList.remove('referenced');
873 | });
874 | } else {
875 | references.forEach(function ($reference) {
876 | $reference.classList.add('referenced');
877 | });
878 | }
879 | }
880 |
881 | function installFindLocalReferences () {
882 | document.addEventListener('click', function (e) {
883 | if (e.target.nodeName === 'VAR') {
884 | toggleFindLocalReferences(e.target);
885 | }
886 | });
887 | }
888 |
889 | document.addEventListener('DOMContentLoaded', installFindLocalReferences);
890 |
--------------------------------------------------------------------------------
/spec.md:
--------------------------------------------------------------------------------
1 | ## Promise.prototype.finally ( _onFinally_ )
2 |
3 | When the `finally` method is called with argument _onFinally_, the following steps are taken:
4 | 1. Let _promise_ be the **this** value.
5 | 1. If Type (_promise_) is not Object, throw a *TypeError* exception.
6 | 1. Assert: IsConstructor (_C_) is *true*.
7 | 1. If IsCallable (_onFinally_) is *false*,
8 | 1. Let _thenFinally_ be _onFinally_.
9 | 1. Let _catchFinally_ be _onFinally_.
10 | 1. Else,
11 | 1. Let _thenFinally_ be a new built-in function object as defined in ThenFinally Function .
12 | 1. Let _catchFinally_ be a new built-in function object as defined in CatchFinally Function .
13 | 1. Set _thenFinally_ and _catchFinally_'s [[Constructor]] internal slots to _C_.
14 | 1. Set _thenFinally_ and _catchFinally_'s [[OnFinally]] internal slots to _onFinally_.
15 | 1. Return ? Invoke (_promise_, *"then"*, « _thenFinally_, _catchFinally_ »).
16 |
17 | ### ThenFinally Function
18 |
19 | A ThenFinally function is an anonymous built-in function that has a [[Constructor]] and an [[OnFinally]] internal slot. The value of the [[Constructor]] internal slot is a `Promise`-like constructor function object, and the value of the [[OnFinally]] internal slot is a function object.
20 |
21 | When a ThenFinally function _F_ is called with argument _value_, the following steps are taken:
22 | 1. Let _onFinally_ be _F_.[[OnFinally]].
23 | 1. Assert: IsCallable (_onFinally_) is *true*.
24 | 1. Let _result_ be ? Call(_onFinally_, *undefined*).
25 | 1. Let _C_ be _F_.[[Constructor]].
26 | 1. Assert: IsConstructor(_C_) is *true*.
27 | 1. Let _promise_ be ? PromiseResolve(_C_, _result_).
28 | 1. Let _valueThunk_ be equivalent to a function that returns _value_.
29 | 1. Return ? Invoke(_promise_, `"then"`, « _valueThunk_ »).
30 |
31 | ### CatchFinally Function
32 |
33 | A CatchFinally function is an anonymous built-in function that has a [[Constructor]] and an [[OnFinally]] internal slot. The value of the [[Constructor]] internal slot is a `Promise`-like constructor function object, and the value of the [[OnFinally]] internal slot is a function object.
34 |
35 | When a CatchFinally function _F_ is called with argument _reason_, the following steps are taken:
36 | 1. Let _onFinally_ be _F_.[[OnFinally]].
37 | 1. Assert: IsCallable (_onFinally_) is *true*.
38 | 1. Let _result_ be ? Call(_onFinally_, *undefined*).
39 | 1. Let _C_ be _F_.[[Constructor]].
40 | 1. Assert: IsConstructor(_C_) is *true*.
41 | 1. Let _promise_ be ? PromiseResolve(_C_, _result_).
42 | 1. Let _thrower_ be equivalent to a function that throws _reason_.
43 | 1. Return ? Invoke(_promise_, `"then"`, « _thrower_ »).
44 |
45 | ## Promise.resolve ( _x_ )
46 |
47 | The `resolve` function returns either a new promise resolved with the passed argument, or the argument itself if the argument is a promise produced by this constructor.
48 | 1. Let _C_ be the *this* value.
49 | 1. If Type (_C_) is not Object, throw a *TypeError* exception.
50 | 1. Return ? PromiseResolve(_C_, _x_).
51 |
52 | Note: the `resolve` function expects its *this* value to be a constructor function that supports the parameter conventions of the `Promise` constructor.
53 |
54 | ## PromiseResolve ( _C_, _x_ )
55 | The abstract operation PromiseResolve, given a constructor and a value, returns a new promise resolved with that value.
56 | 1. Assert: Type (_C_) is Object.
57 | 1. If IsPromise (_x_) is *true*, then
58 | 1. Let _xConstructor_ be ? Get (_x_, `"constructor"`).
59 | 1. If SameValue(_xConstructor_, _C_) is *true*, return _x_.
60 | 1. Let _promiseCapability_ be ? NewPromiseCapability (_C_).
61 | 1. Perform ? Call (_promiseCapability_.[[Resolve]], *undefined*, « _x_ »).
62 | 1. Return _promiseCapability_.[[Promise]].
63 |
--------------------------------------------------------------------------------
/test/adapter.js:
--------------------------------------------------------------------------------
1 | var P = require('./promise');
2 |
3 | module.exports = {
4 | resolved(x) { return P.resolve(x); },
5 | rejected(e) { return P.reject(e); },
6 | deferred() {
7 | var deferred = {};
8 | deferred.promise = new P((resolve, reject) => {
9 | deferred.resolve = resolve;
10 | deferred.reject = reject;
11 | });
12 | return deferred;
13 | }
14 | };
15 |
--------------------------------------------------------------------------------
/test/promise.js:
--------------------------------------------------------------------------------
1 | global.foo = 0;
2 | global.id = 1;
3 | const {
4 | Call,
5 | Get,
6 | Invoke,
7 | IsCallable,
8 | IsConstructor,
9 | SameValue,
10 | SpeciesConstructor,
11 | Type,
12 | } = require('especially/abstract-operations');
13 | const {
14 | assert,
15 | get_slot,
16 | has_slot,
17 | make_slots,
18 | set_slot,
19 | } = require('especially/meta');
20 | const { '@@species': atAtSpecies } = require('especially/well-known-symbols');
21 |
22 | const {
23 | PromiseIntrinsic,
24 | NewPromiseCapability,
25 | IsPromise,
26 | } = require('./promiseSpec');
27 |
28 | Object.assign(PromiseIntrinsic.prototype, {
29 | finally(onFinally) {
30 | const promise = this;
31 | if (IsPromise(this) === false) {
32 | throw new TypeError('Promise.prototype.finally only works on real promises');
33 | }
34 |
35 | const C = SpeciesConstructor(promise, PromiseIntrinsic);
36 | assert(IsConstructor(C));
37 |
38 | let thenFinally, catchFinally;
39 | if (IsCallable(onFinally) !== true) {
40 | thenFinally = onFinally;
41 | catchFinally = onFinally;
42 | } else {
43 | thenFinally = new ThenFinallyFunction();
44 | catchFinally = new CatchFinallyFunction();
45 |
46 | set_slot(thenFinally, 'Constructor', C);
47 | set_slot(catchFinally, 'Constructor', C);
48 |
49 | set_slot(thenFinally, 'OnFinally', onFinally);
50 | set_slot(catchFinally, 'OnFinally', onFinally);
51 | }
52 |
53 | return Invoke(promise, 'then', [thenFinally, catchFinally]);
54 | }
55 | });
56 | Object.defineProperty(PromiseIntrinsic.prototype, 'finally', {
57 | enumerable: false,
58 | });
59 | Object.assign(PromiseIntrinsic, {
60 | resolve(x) {
61 | let C = this;
62 |
63 | if (Type(C) !== 'Object') {
64 | throw new TypeError('Promise.all must be called on an object');
65 | }
66 |
67 | return PromiseResolve(C, x);
68 | }
69 | });
70 |
71 | function PromiseResolve(C, x) {
72 | assert(Type(C) === 'Object');
73 |
74 | if (IsPromise(x) === true) {
75 | const xConstructor = Get(x, 'constructor');
76 | if (SameValue(xConstructor, C) === true) {
77 | return x;
78 | }
79 | }
80 |
81 | const promiseCapability = NewPromiseCapability(C);
82 | Call(get_slot(promiseCapability, '[[Resolve]]'), undefined, [x]);
83 | return get_slot(promiseCapability, '[[Promise]]');
84 | }
85 |
86 | function ThenFinallyFunction() {
87 | const ThenFinally = (value) => {
88 | const onFinally = get_slot(ThenFinally, 'OnFinally');
89 | assert(IsCallable(onFinally));
90 |
91 | const result = onFinally();
92 |
93 | const C = get_slot(ThenFinally, 'Constructor');
94 | assert(IsConstructor(C));
95 |
96 | const promise = PromiseResolve(C, result);
97 | const valueThunk = () => value;
98 | return Invoke(promise, 'then', [valueThunk]);
99 | };
100 |
101 | make_slots(ThenFinally, [
102 | 'OnFinally',
103 | 'Constructor',
104 | ]);
105 |
106 | return ThenFinally;
107 | }
108 |
109 | function CatchFinallyFunction() {
110 | const CatchFinally = (reason) => {
111 | const onFinally = get_slot(CatchFinally, 'OnFinally');
112 | assert(IsCallable(onFinally));
113 |
114 | const result = onFinally();
115 |
116 | const C = get_slot(CatchFinally, 'Constructor');
117 | assert(IsConstructor(C));
118 |
119 | const promise = PromiseResolve(C, result);
120 | const thrower = () => { throw reason; };
121 | return Invoke(promise, 'then', [thrower]);
122 | };
123 |
124 | make_slots(CatchFinally, [
125 | 'OnFinally',
126 | 'Constructor',
127 | ]);
128 |
129 | return CatchFinally;
130 | }
131 |
132 | module.exports = PromiseIntrinsic;
133 |
--------------------------------------------------------------------------------
/test/promiseSpec.js:
--------------------------------------------------------------------------------
1 | global.foo = 0;
2 | global.id = 1;
3 | const {
4 | Call,
5 | EnqueueJob,
6 | Get,
7 | Invoke,
8 | IsCallable,
9 | IsConstructor,
10 | SameValue,
11 | SpeciesConstructor,
12 | Type,
13 | } = require('especially/abstract-operations');
14 | const {
15 | assert,
16 | get_slot,
17 | has_slot,
18 | make_slots,
19 | set_slot,
20 | } = require('especially/meta');
21 | const { '@@species': atAtSpecies } = require('especially/well-known-symbols');
22 |
23 | let PromiseIntrinsic;
24 |
25 | function IfAbruptRejectPromise(value, capability) {
26 | // Usage: pass it exceptions; it only handles that case.
27 | // Always use `return` before it, i.e. `try { ... } catch (e) { return IfAbruptRejectPromise(e, capability); }`.
28 | Call(get_slot(capability, '[[Reject]]'), value);
29 | return get_slot(capability, '[[Promise]]');
30 | }
31 |
32 | function CreateResolvingFunctions(promise) {
33 | const alreadyResolved = {};
34 | make_slots(alreadyResolved, [
35 | '[[Value]]',
36 | ]);
37 | set_slot(alreadyResolved, '[[Value]]', false);
38 |
39 | function resolve(resolution) {
40 | assert(has_slot(resolve, '[[Promise]]'));
41 | const promise = get_slot(resolve, '[[Promise]]');
42 | assert(Type(promise) === 'Object');
43 |
44 | const alreadyResolved = get_slot(resolve, '[[AlreadyResolved]]');
45 | if (get_slot(alreadyResolved, '[[Value]]') === true) {
46 | return;
47 | }
48 |
49 | set_slot(alreadyResolved, '[[Value]]', true);
50 |
51 | if (SameValue(resolution, promise) === true) {
52 | const selfResolutionError = new TypeError('self resolution');
53 | return RejectPromise(promise, selfResolutionError);
54 | }
55 |
56 | if (Type(resolution) !== 'Object') {
57 | return FulfillPromise(promise, resolution);
58 | }
59 |
60 | let thenAction;
61 | try {
62 | thenAction = Get(resolution, 'then');
63 | } catch (thenActionE) {
64 | return RejectPromise(promise, thenActionE);
65 | }
66 |
67 | if (IsCallable(thenAction) === false) {
68 | return FulfillPromise(promise, resolution);
69 | }
70 |
71 | EnqueueJob('PromiseJobs', PromiseResolveThenableJob, [promise, resolution, thenAction]);
72 | }
73 | make_slots(resolve, [
74 | '[[Promise]]',
75 | '[[AlreadyResolved]]',
76 | ]);
77 | set_slot(resolve, '[[Promise]]', promise);
78 | set_slot(resolve, '[[AlreadyResolved]]', alreadyResolved);
79 |
80 | function reject(reason) {
81 | assert(has_slot(reject, '[[Promise]]'));
82 | const promise = get_slot(reject, '[[Promise]]');
83 | assert(Type(promise) === 'Object');
84 |
85 | const alreadyResolved = get_slot(reject, '[[AlreadyResolved]]');
86 | if (get_slot(alreadyResolved, '[[Value]]') === true) {
87 | return undefined;
88 | }
89 |
90 | set_slot(alreadyResolved, '[[Value]]', true);
91 |
92 | return RejectPromise(promise, reason);
93 | }
94 | make_slots(reject, [
95 | '[[Promise]]',
96 | '[[AlreadyResolved]]',
97 | ]);
98 | set_slot(reject, '[[Promise]]', promise);
99 | set_slot(reject, '[[AlreadyResolved]]', alreadyResolved);
100 |
101 | const record = {};
102 | make_slots(record, [
103 | '[[Resolve]]',
104 | '[[Reject]]',
105 | ]);
106 | set_slot(record, '[[Resolve]]', resolve);
107 | set_slot(record, '[[Reject]]', reject);
108 | return record;
109 | }
110 |
111 | function FulfillPromise(promise, value) {
112 | assert(get_slot(promise, '[[PromiseState]]') === 'pending');
113 |
114 | const reactions = get_slot(promise, '[[PromiseFulfillReactions]]');
115 |
116 | set_slot(promise, '[[PromiseResult]]', value);
117 | set_slot(promise, '[[PromiseFulfillReactions]]', undefined);
118 | set_slot(promise, '[[PromiseRejectReactions]]', undefined);
119 | set_slot(promise, '[[PromiseState]]', 'fulfilled');
120 |
121 | return TriggerPromiseReactions(reactions, value);
122 | }
123 |
124 | function NewPromiseCapability(C) {
125 | if (IsConstructor(C) === false) {
126 | throw new TypeError('NewPromiseCapability only works on constructors');
127 | }
128 |
129 | const promiseCapability = {};
130 | make_slots(promiseCapability, [
131 | '[[Promise]]',
132 | '[[Resolve]]',
133 | '[[Reject]]',
134 | ]);
135 | set_slot(promiseCapability, '[[Promise]]', undefined);
136 | set_slot(promiseCapability, '[[Resolve]]', undefined);
137 | set_slot(promiseCapability, '[[Reject]]', undefined);
138 | function executor(resolve, reject) {
139 | const promiseCapability = get_slot(executor, '[[Capability]]');
140 |
141 | assert(IsPromiseCapabilityRecord(promiseCapability));
142 |
143 | if (get_slot(promiseCapability, '[[Resolve]]') !== undefined) {
144 | throw new TypeError('Promise capability must not have [[Resolve]] set when calling executor');
145 | }
146 | if (get_slot(promiseCapability, '[[Reject]]') !== undefined) {
147 | throw new TypeError('Promise capability must not have [[Reject]] set when calling executor');
148 | }
149 |
150 | set_slot(promiseCapability, '[[Resolve]]', resolve);
151 | set_slot(promiseCapability, '[[Reject]]', reject);
152 |
153 | return undefined;
154 | }
155 | make_slots(executor, ['[[Capability]]']);
156 | set_slot(executor, '[[Capability]]', promiseCapability);
157 |
158 | const promise = new C(executor);
159 | if (IsCallable(get_slot(promiseCapability, '[[Resolve]]')) === false) {
160 | throw new TypeError('The given constructor did not correctly set a [[Resolve]] function on the promise capability');
161 | }
162 | if (IsCallable(get_slot(promiseCapability, '[[Reject]]')) === false) {
163 | throw new TypeError('The given constructor did not correctly set a [[Reject]] function on the promise capability');
164 | }
165 |
166 | set_slot(promiseCapability, '[[Promise]]', promise);
167 | return promiseCapability;
168 | }
169 |
170 | function IsPromiseCapabilityRecord(x) {
171 | const promise = get_slot(x, '[[Promise]]');
172 | if (promise !== undefined && !IsPromise(promise)) {
173 | return false;
174 | }
175 |
176 | const resolve = get_slot(x, '[[Resolve]]');
177 | const reject = get_slot(x, '[[Reject]]');
178 | if (resolve !== undefined && !IsCallable(resolve)) {
179 | return false;
180 | }
181 | if (reject !== undefined && !IsCallable(reject)) {
182 | return false;
183 | }
184 |
185 | return true;
186 | }
187 |
188 | function IsPromiseReactionRecord(x) {
189 | if (Type(x) !== 'Object') {
190 | return false;
191 | }
192 |
193 | if (!has_slot(x, '[[Capability]]')) {
194 | return false;
195 | }
196 | if (!has_slot(x, '[[Type]]')) {
197 | return false;
198 | }
199 | const type = get_slot(x, '[[Type]]');
200 | if (type !== 'Fulfill' && type !== 'Reject') {
201 | return false;
202 | }
203 |
204 | if (!has_slot(x, '[[Handler]]')) {
205 | return false;
206 | }
207 | const handler = get_slot(x, '[[Handler]]');
208 | if (!IsCallable(handler) && handler !== undefined) {
209 | return false;
210 | }
211 |
212 | return true;
213 | }
214 |
215 | function IsPromise(x) {
216 | if (Type(x) !== 'Object') {
217 | return false;
218 | }
219 |
220 | if (!has_slot(x, '[[PromiseState]]')) {
221 | return false;
222 | }
223 |
224 | return true;
225 | }
226 |
227 | function RejectPromise(promise, reason) {
228 | assert(get_slot(promise, '[[PromiseState]]') === 'pending');
229 |
230 | const reactions = get_slot(promise, '[[PromiseRejectReactions]]');
231 |
232 | set_slot(promise, '[[PromiseResult]]', reason);
233 | set_slot(promise, '[[PromiseFulfillReactions]]', undefined);
234 | set_slot(promise, '[[PromiseRejectReactions]]', undefined);
235 | set_slot(promise, '[[PromiseState]]', 'rejected');
236 |
237 | if (get_slot(promise, '[[PromiseIsHandled]]') === false) {
238 | HostPromiseRejectionTracker(promise, 'reject');
239 | }
240 |
241 | return TriggerPromiseReactions(reactions, reason);
242 | }
243 |
244 | function TriggerPromiseReactions(reactions, argument) {
245 | for (const reaction of reactions) {
246 | EnqueueJob('PromiseJobs', PromiseReactionJob, [reaction, argument]);
247 | }
248 |
249 | return undefined;
250 | }
251 |
252 | function HostPromiseRejectionTracker(promise, operation) {
253 | assert(IsPromise(promise));
254 | assert(operation === 'reject' || operation === 'handle');
255 | }
256 |
257 | function NewCompletionRecord(type, value, target) {
258 | const completionRecord = {};
259 | make_slots(completionRecord, [
260 | '[[Type]]',
261 | '[[Value]]',
262 | '[[Target]]',
263 | ]);
264 | set_slot(completionRecord, '[[Type]]', type);
265 | set_slot(completionRecord, '[[Value]]', value);
266 | set_slot(completionRecord, '[[Target]]', target);
267 | return completionRecord;
268 | }
269 |
270 | function isCompletionRecord(completionRecord) {
271 | if (!has_slot(completionRecord, '[[Type]]') || !has_slot(completionRecord, '[[Value]]') || !has_slot(completionRecord, '[[Target]]')) {
272 | return false;
273 | }
274 | const type = get_slot(completionRecord, '[[Type]]');
275 | const possibleTypes = ['normal', 'break', 'continue', 'return', 'throw'];
276 | if (!possibleTypes.includes(type)) {
277 | return false;
278 | }
279 |
280 | const target = get_slot(completionRecord, '[[Target]]');
281 | if (typeof target !== 'undefined' && typeof target !== 'string') {
282 | return false;
283 | }
284 | return true;
285 | }
286 |
287 | function NormalCompletion(value) {
288 | return NewCompletionRecord('normal', value);
289 | }
290 |
291 | function AbruptCompletion(value) {
292 | return NewCompletionRecord('throw', value);
293 | }
294 |
295 | function isAbruptCompletion(completionRecord) {
296 | return isCompletionRecord(completionRecord) && get_slot(completionRecord, '[[Type]]') === 'throw';
297 | }
298 |
299 | function PromiseReactionJob(reaction, argument) {
300 | assert(IsPromiseReactionRecord(reaction) === true);
301 |
302 | const promiseCapability = get_slot(reaction, '[[Capability]]');
303 | const type = get_slot(reaction, '[[Type]]');
304 | const handler = get_slot(reaction, '[[Handler]]');
305 |
306 | let handlerResult;
307 | if (handler === undefined) {
308 | if (type === 'Fulfill') {
309 | handlerResult = NormalCompletion(argument);
310 | } else {
311 | assert(type === 'Reject');
312 | handlerResult = AbruptCompletion(argument);
313 | }
314 | } else {
315 | try {
316 | handlerResult = NormalCompletion(Call(handler, undefined, [argument]));
317 | } catch (callE) {
318 | handlerResult = AbruptCompletion(callE);
319 | }
320 | }
321 |
322 | let status;
323 | if (isAbruptCompletion(handlerResult)) {
324 | status = Call(get_slot(promiseCapability, '[[Reject]]'), undefined, [get_slot(handlerResult, '[[Value]]')]);
325 | } else {
326 | status = Call(get_slot(promiseCapability, '[[Resolve]]'), undefined, [get_slot(handlerResult, '[[Value]]')]);
327 | }
328 | return status;
329 | }
330 |
331 | function PromiseResolveThenableJob(promiseToResolve, thenable, then) {
332 | const resolvingFunctions = CreateResolvingFunctions(promiseToResolve);
333 |
334 | try {
335 | Call(then, thenable, [
336 | get_slot(resolvingFunctions, '[[Resolve]]'),
337 | get_slot(resolvingFunctions, '[[Reject]]'),
338 | ]);
339 | } catch (thenCallResultE) {
340 | Call(get_slot(resolvingFunctions, '[[Reject]]'), undefined, [thenCallResultE]);
341 | }
342 | }
343 |
344 | PromiseIntrinsic = class Promise {
345 | constructor(executor) {
346 | if (IsCallable(executor) === false) {
347 | throw new TypeError('executor must be callable');
348 | }
349 |
350 | // Cheating a bit on NewTarget stuff here.
351 |
352 | const promise = this;
353 | make_slots(promise, [
354 | '[[PromiseState]]',
355 | '[[PromiseConstructor]]',
356 | '[[PromiseResult]]',
357 | '[[PromiseFulfillReactions]]',
358 | '[[PromiseRejectReactions]]',
359 | '[[PromiseIsHandled]]',
360 | ]);
361 |
362 | set_slot(promise, '[[PromiseConstructor]]', this.constructor);
363 | set_slot(promise, '[[PromiseState]]', 'pending');
364 | set_slot(promise, '[[PromiseFulfillReactions]]', []);
365 | set_slot(promise, '[[PromiseRejectReactions]]', []);
366 | set_slot(promise, '[[PromiseIsHandled]]', false);
367 | promise.id = global.id++;
368 |
369 | const resolvingFunctions = CreateResolvingFunctions(promise);
370 |
371 | try {
372 | Call(executor, undefined, [
373 | get_slot(resolvingFunctions, '[[Resolve]]'),
374 | get_slot(resolvingFunctions, '[[Reject]]')
375 | ]);
376 | } catch (completionE) {
377 | Call(get_slot(resolvingFunctions, '[[Reject]]'), undefined, [completionE]);
378 | }
379 |
380 | return promise;
381 | }
382 |
383 | static all(iterable) {
384 | let C = this;
385 |
386 | if (Type(C) !== 'Object') {
387 | throw new TypeError('Promise.all must be called on an object');
388 | }
389 |
390 | const S = Get(C, atAtSpecies);
391 | if (S !== undefined && S !== null) {
392 | C = S;
393 | }
394 |
395 | // The algorithm and indirection here, with PerformPromiseAll, manual iteration, and the closure-juggling, is just
396 | // too convoluted compared to normal ES code, so let's skip it. The following should be equivalent; it maintains
397 | // some of the formal translation in places, but skips on some of the structure.
398 |
399 | return new C((resolve, reject) => {
400 | const values = [];
401 |
402 | let remainingElementsCount = 1;
403 | let index = 0;
404 |
405 | for (const nextValue of iterable) {
406 | values.push(undefined);
407 | const nextPromise = Invoke(C, 'resolve', [nextValue]);
408 |
409 | let alreadyCalled = false;
410 | const resolveElement = x => {
411 | if (alreadyCalled === true) {
412 | return undefined;
413 | }
414 | alreadyCalled = true;
415 | values[index] = x;
416 |
417 | remainingElementsCount = remainingElementsCount - 1;
418 | if (remainingElementsCount === 0) {
419 | resolve(values);
420 | }
421 | };
422 |
423 | remainingElementsCount = remainingElementsCount + 1;
424 |
425 | Invoke(nextPromise, 'then', [resolveElement, reject]);
426 |
427 | index += 1;
428 | }
429 | });
430 | }
431 |
432 | static race(iterable) {
433 | let C = this;
434 |
435 | if (Type(C) !== 'Object') {
436 | throw new TypeError('Promise.all must be called on an object');
437 | }
438 |
439 | const S = Get(C, atAtSpecies);
440 | if (S !== undefined && S !== null) {
441 | C = S;
442 | }
443 |
444 | // Similarly to for `Promise.all`, we avoid some of the indirection here.
445 |
446 | return new C((resolve, reject) => {
447 | for (const nextValue of iterable) {
448 | const nextPromise = Invoke(C, 'resolve', [nextValue]);
449 | Invoke(nextPromise, 'then', [resolve, reject]);
450 | }
451 | });
452 | }
453 |
454 | static reject(r) {
455 | let C = this;
456 |
457 | if (Type(C) !== 'Object') {
458 | throw new TypeError('Promise.all must be called on an object');
459 | }
460 |
461 | const S = Get(C, atAtSpecies);
462 | if (S !== undefined && S !== null) {
463 | C = S;
464 | }
465 |
466 | const promiseCapability = NewPromiseCapability(C);
467 | Call(get_slot(promiseCapability, '[[Reject]]'), undefined, [r]);
468 | return get_slot(promiseCapability, '[[Promise]]');
469 | }
470 |
471 | static resolve(x) {
472 | let C = this;
473 |
474 | if (Type(C) !== 'Object') {
475 | throw new TypeError('Promise.all must be called on an object');
476 | }
477 |
478 | if (IsPromise(x) === true) {
479 | const xConstructor = Get(x, 'constructor');
480 | if (SameValue(xConstructor, C) === true) {
481 | return x;
482 | }
483 | }
484 |
485 | const promiseCapability = NewPromiseCapability(C);
486 | Call(get_slot(promiseCapability, '[[Resolve]]'), undefined, [x]);
487 | return get_slot(promiseCapability, '[[Promise]]');
488 | }
489 |
490 | static get [atAtSpecies]() {
491 | return this;
492 | }
493 |
494 | catch(onRejected) {
495 | return Invoke(this, 'then', [undefined, onRejected]);
496 | }
497 |
498 | then(onFulfilled, onRejected) {
499 | const promise = this;
500 | if (IsPromise(this) === false) {
501 | throw new TypeError('Promise.prototype.then only works on real promises');
502 | }
503 |
504 | const C = SpeciesConstructor(promise, PromiseIntrinsic);
505 | const resultCapability = NewPromiseCapability(C);
506 | return PerformPromiseThen(promise, onFulfilled, onRejected, resultCapability);
507 | }
508 | }
509 |
510 | function createPromiseReactionRecord(capability, type, handler) {
511 | const record = {};
512 | make_slots(record, [
513 | '[[Capability]]',
514 | '[[Type]]',
515 | '[[Handler]]',
516 | ]);
517 | set_slot(record, '[[Capability]]', capability);
518 | set_slot(record, '[[Type]]', type);
519 | set_slot(record, '[[Handler]]', handler);
520 | return record;
521 | }
522 |
523 | function PerformPromiseThen(promise, onFulfilled, onRejected, resultCapability) {
524 | assert(IsPromise(promise) === true);
525 | assert(IsPromiseCapabilityRecord(resultCapability) === true);
526 |
527 | if (IsCallable(onFulfilled) === false) {
528 | onFulfilled = undefined;
529 | }
530 |
531 | if (IsCallable(onRejected) === false) {
532 | onRejected = undefined;
533 | }
534 |
535 | const fulfillReaction = createPromiseReactionRecord(resultCapability, 'Fulfill', onFulfilled);
536 | const rejectReaction = createPromiseReactionRecord(resultCapability, 'Reject', onRejected);
537 |
538 | const state = get_slot(promise, '[[PromiseState]]');
539 | if (state === 'pending') {
540 | get_slot(promise, '[[PromiseFulfillReactions]]').push(fulfillReaction);
541 | get_slot(promise, '[[PromiseRejectReactions]]').push(rejectReaction);
542 | } else if (state === 'fulfilled') {
543 | const value = get_slot(promise, '[[PromiseResult]]');
544 | EnqueueJob('PromiseJobs', PromiseReactionJob, [fulfillReaction, value]);
545 | } else {
546 | assert(state === 'rejected');
547 | const reason = get_slot(promise, '[[PromiseResult]]');
548 | if (get_slot(promise, '[[PromiseIsHandled]]') === false) {
549 | HostPromiseRejectionTracker(promise, 'handle');
550 | }
551 | EnqueueJob('PromiseJobs', PromiseReactionJob, [rejectReaction, reason]);
552 | }
553 |
554 | set_slot(promise, '[[PromiseIsHandled]]', true);
555 | return get_slot(resultCapability, '[[Promise]]');
556 | }
557 |
558 | module.exports = {
559 | PromiseIntrinsic,
560 | NewPromiseCapability,
561 | IsPromise,
562 | };
563 |
--------------------------------------------------------------------------------
/test/test.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | var assert = require('assert');
4 |
5 | var P = typeof Promise === 'function' && typeof Promise.prototype.finally === 'function' ? Promise : require('./promise');
6 | var adapter = require('./adapter');
7 |
8 | var someRejectionReason = { message: 'some rejection reason' };
9 | var anotherReason = { message: 'another rejection reason' };
10 |
11 | describe('mocha promise sanity check', () => {
12 | it('passes with a resolved promise', () => {
13 | return P.resolve(3);
14 | });
15 |
16 | it('passes with a rejected then resolved promise', () => {
17 | return P.reject(someRejectionReason).catch(x => 'this should be resolved');
18 | });
19 |
20 | var ifPromiseIt = P === Promise ? it : it.skip;
21 | ifPromiseIt('is the native Promise', () => {
22 | assert.equal(P, Promise);
23 | });
24 | });
25 |
26 | describe('onFinally', () => {
27 | describe('no callback', () => {
28 | specify('from resolved', (done) => {
29 | adapter.resolved(3)
30 | .then((x) => {
31 | assert.strictEqual(x, 3);
32 | return x;
33 | })
34 | .finally()
35 | .then(function onFulfilled(x) {
36 | assert.strictEqual(x, 3);
37 | done();
38 | }, function onRejected() {
39 | done(new Error('should not be called'));
40 | });
41 | });
42 |
43 | specify('from rejected', (done) => {
44 | adapter.rejected(someRejectionReason)
45 | .catch((e) => {
46 | assert.strictEqual(e, someRejectionReason);
47 | throw e;
48 | })
49 | .finally()
50 | .then(function onFulfilled() {
51 | done(new Error('should not be called'));
52 | }, function onRejected(reason) {
53 | assert.strictEqual(reason, someRejectionReason);
54 | done();
55 | });
56 | });
57 | });
58 |
59 | describe('throws an exception', () => {
60 | specify('from resolved', (done) => {
61 | adapter.resolved(3)
62 | .then((x) => {
63 | assert.strictEqual(x, 3);
64 | return x;
65 | })
66 | .finally(function onFinally() {
67 | assert(arguments.length === 0);
68 | throw someRejectionReason;
69 | }).then(function onFulfilled() {
70 | done(new Error('should not be called'));
71 | }, function onRejected(reason) {
72 | assert.strictEqual(reason, someRejectionReason);
73 | done();
74 | });
75 | });
76 |
77 | specify('from rejected', (done) => {
78 | adapter.rejected(anotherReason).finally(function onFinally() {
79 | assert(arguments.length === 0);
80 | throw someRejectionReason;
81 | }).then(function onFulfilled() {
82 | done(new Error('should not be called'));
83 | }, function onRejected(reason) {
84 | assert.strictEqual(reason, someRejectionReason);
85 | done();
86 | });
87 | });
88 | });
89 |
90 | describe('returns a non-promise', () => {
91 | specify('from resolved', (done) => {
92 | adapter.resolved(3)
93 | .then((x) => {
94 | assert.strictEqual(x, 3);
95 | return x;
96 | })
97 | .finally(function onFinally() {
98 | assert(arguments.length === 0);
99 | return 4;
100 | }).then(function onFulfilled(x) {
101 | assert.strictEqual(x, 3);
102 | done();
103 | }, function onRejected() {
104 | done(new Error('should not be called'));
105 | });
106 | });
107 |
108 | specify('from rejected', (done) => {
109 | adapter.rejected(anotherReason)
110 | .catch((e) => {
111 | assert.strictEqual(e, anotherReason);
112 | throw e;
113 | })
114 | .finally(function onFinally() {
115 | assert(arguments.length === 0);
116 | throw someRejectionReason;
117 | }).then(function onFulfilled() {
118 | done(new Error('should not be called'));
119 | }, function onRejected(e) {
120 | assert.strictEqual(e, someRejectionReason);
121 | done();
122 | });
123 | });
124 | });
125 |
126 | describe('returns a pending-forever promise', () => {
127 | specify('from resolved', (done) => {
128 | var timeout;
129 | adapter.resolved(3)
130 | .then((x) => {
131 | assert.strictEqual(x, 3);
132 | return x;
133 | })
134 | .finally(function onFinally() {
135 | assert(arguments.length === 0);
136 | timeout = setTimeout(done, 0.1e3);
137 | return new P(() => {}); // forever pending
138 | }).then(function onFulfilled(x) {
139 | clearTimeout(timeout);
140 | done(new Error('should not be called'));
141 | }, function onRejected() {
142 | clearTimeout(timeout);
143 | done(new Error('should not be called'));
144 | });
145 | });
146 |
147 | specify('from rejected', (done) => {
148 | var timeout;
149 | adapter.rejected(someRejectionReason)
150 | .catch((e) => {
151 | assert.strictEqual(e, someRejectionReason);
152 | throw e;
153 | })
154 | .finally(function onFinally() {
155 | assert(arguments.length === 0);
156 | timeout = setTimeout(done, 0.1e3);
157 | return new P(() => {}); // forever pending
158 | }).then(function onFulfilled(x) {
159 | clearTimeout(timeout);
160 | done(new Error('should not be called'));
161 | }, function onRejected() {
162 | clearTimeout(timeout);
163 | done(new Error('should not be called'));
164 | });
165 | });
166 | });
167 |
168 | describe('returns an immediately-fulfilled promise', () => {
169 | specify('from resolved', (done) => {
170 | adapter.resolved(3)
171 | .then((x) => {
172 | assert.strictEqual(x, 3);
173 | return x;
174 | })
175 | .finally(function onFinally() {
176 | assert(arguments.length === 0);
177 | return adapter.resolved(4);
178 | }).then(function onFulfilled(x) {
179 | assert.strictEqual(x, 3);
180 | done();
181 | }, function onRejected() {
182 | done(new Error('should not be called'));
183 | });
184 | });
185 |
186 | specify('from rejected', (done) => {
187 | adapter.rejected(someRejectionReason)
188 | .catch((e) => {
189 | assert.strictEqual(e, someRejectionReason);
190 | throw e;
191 | })
192 | .finally(function onFinally() {
193 | assert(arguments.length === 0);
194 | return adapter.resolved(4);
195 | }).then(function onFulfilled() {
196 | done(new Error('should not be called'));
197 | }, function onRejected(e) {
198 | assert.strictEqual(e, someRejectionReason);
199 | done();
200 | });
201 | });
202 | });
203 |
204 | describe('returns an immediately-rejected promise', () => {
205 | specify('from resolved ', (done) => {
206 | adapter.resolved(3)
207 | .then((x) => {
208 | assert.strictEqual(x, 3);
209 | return x;
210 | })
211 | .finally(function onFinally() {
212 | assert(arguments.length === 0);
213 | return adapter.rejected(4);
214 | }).then(function onFulfilled(x) {
215 | done(new Error('should not be called'));
216 | }, function onRejected(e) {
217 | assert.strictEqual(e, 4);
218 | done();
219 | });
220 | });
221 |
222 | specify('from rejected', (done) => {
223 | const newReason = {};
224 | adapter.rejected(someRejectionReason)
225 | .catch((e) => {
226 | assert.strictEqual(e, someRejectionReason);
227 | throw e;
228 | })
229 | .finally(function onFinally() {
230 | assert(arguments.length === 0);
231 | return adapter.rejected(newReason);
232 | }).then(function onFulfilled(x) {
233 | done(new Error('should not be called'));
234 | }, function onRejected(e) {
235 | assert.strictEqual(e, newReason);
236 | done();
237 | });
238 | });
239 | });
240 |
241 | describe('returns a fulfilled-after-a-second promise', () => {
242 | specify('from resolved', (done) => {
243 | var timeout;
244 | adapter.resolved(3)
245 | .then((x) => {
246 | assert.strictEqual(x, 3);
247 | return x;
248 | })
249 | .finally(function onFinally() {
250 | assert(arguments.length === 0);
251 | timeout = setTimeout(done, 1.5e3);
252 | return new P((resolve) => {
253 | setTimeout(() => resolve(4), 1e3);
254 | });
255 | }).then(function onFulfilled(x) {
256 | clearTimeout(timeout);
257 | assert.strictEqual(x, 3);
258 | done();
259 | }, function onRejected() {
260 | clearTimeout(timeout);
261 | done(new Error('should not be called'));
262 | });
263 | });
264 |
265 | specify('from rejected', (done) => {
266 | var timeout;
267 | adapter.rejected(3)
268 | .catch((e) => {
269 | assert.strictEqual(e, 3);
270 | throw e;
271 | })
272 | .finally(function onFinally() {
273 | assert(arguments.length === 0);
274 | timeout = setTimeout(done, 1.5e3);
275 | return new P((resolve) => {
276 | setTimeout(() => resolve(4), 1e3);
277 | });
278 | }).then(function onFulfilled() {
279 | clearTimeout(timeout);
280 | done(new Error('should not be called'));
281 | }, function onRejected(e) {
282 | clearTimeout(timeout);
283 | assert.strictEqual(e, 3);
284 | done();
285 | });
286 | });
287 | });
288 |
289 | describe('returns a rejected-after-a-second promise', () => {
290 | specify('from resolved', (done) => {
291 | var timeout;
292 | adapter.resolved(3)
293 | .then((x) => {
294 | assert.strictEqual(x, 3);
295 | return x;
296 | })
297 | .finally(function onFinally() {
298 | assert(arguments.length === 0);
299 | timeout = setTimeout(done, 1.5e3);
300 | return new P((resolve, reject) => {
301 | setTimeout(() => reject(4), 1e3);
302 | });
303 | }).then(function onFulfilled() {
304 | clearTimeout(timeout);
305 | done(new Error('should not be called'));
306 | }, function onRejected(e) {
307 | clearTimeout(timeout);
308 | assert.strictEqual(e, 4);
309 | done();
310 | });
311 | });
312 |
313 | specify('from rejected', (done) => {
314 | var timeout;
315 | adapter.rejected(someRejectionReason)
316 | .catch((e) => {
317 | assert.strictEqual(e, someRejectionReason);
318 | throw e;
319 | })
320 | .finally(function onFinally() {
321 | assert(arguments.length === 0);
322 | timeout = setTimeout(done, 1.5e3);
323 | return new P((resolve, reject) => {
324 | setTimeout(() => reject(anotherReason), 1e3);
325 | });
326 | }).then(function onFulfilled() {
327 | clearTimeout(timeout);
328 | done(new Error('should not be called'));
329 | }, function onRejected(e) {
330 | clearTimeout(timeout);
331 | assert.strictEqual(e, anotherReason);
332 | done();
333 | });
334 | });
335 | });
336 |
337 | specify('has the correct property descriptor', () => {
338 | var descriptor = Object.getOwnPropertyDescriptor(P.prototype, 'finally');
339 |
340 | assert.strictEqual(descriptor.writable, true);
341 | assert.strictEqual(descriptor.configurable, true);
342 | assert.strictEqual(descriptor.enumerable, false);
343 | });
344 | });
345 |
--------------------------------------------------------------------------------