HTML — Web application API

8.1. ~scripting

【 この節の和訳は、 `別~page@~WAPI#scripting$にて。 】

8.2. `WindowOrWorkerGlobalScope^I ~mixin

`WindowOrWorkerGlobalScope$I ~mixinは、 `Window$I, `WorkerGlobalScope$I 両~obj上に公開されることになる~APIの利用~用にある。 ◎ The WindowOrWorkerGlobalScope mixin is for use of APIs that are to be exposed on Window and WorkerGlobalScope objects.

注記: 他の標準は、 更に拡張するときは, partial interface mixin `WindowOrWorkerGlobalScope$I { … }; を適切な参照-とともに利用することが奨励される。 ◎ Other standards are encouraged to further extend it using partial interface mixin WindowOrWorkerGlobalScope { … }; along with an appropriate reference.

typedef (DOMString or `Function$I) `TimerHandler@I;

interface mixin `WindowOrWorkerGlobalScope@I {
  [Replaceable] readonly attribute USVString `origin$m;
  readonly attribute boolean `isSecureContext$m;
  readonly attribute boolean `crossOriginIsolated$m;

  undefined `reportError$m(any %e);

  // base64 utility methods
  DOMString `btoa$m(DOMString %data);
  ByteString `atob$m(DOMString %data);

  // timers
  long `setTimeout$m(
      `TimerHandler$I %handler,
      optional long %timeout = 0,
      any... %arguments
  );
  undefined `clearTimeout$m(optional long %id = 0);
  long `setInterval$m(
      `TimerHandler$I %handler,
      optional long %timeout = 0,
      any... %arguments
  );
  undefined `clearInterval$m(optional long %id = 0);

  // microtask queuing
  undefined `queueMicrotask$m(`VoidFunction$I %callback);

  // ImageBitmap
  `Promise$<`ImageBitmap$I> `createImageBitmap$m(
      `ImageBitmapSource$I %image,
      optional `ImageBitmapOptions$I %options = {}
  );
  `Promise$<`ImageBitmap$I> `createImageBitmap$m(
      `ImageBitmapSource$I %image,
      long %sx, long %sy, long %sw, long %sh,
      optional `ImageBitmapOptions$I %options = {}
  );
  // structured cloning
  any `structuredClone$m(any %value, optional `StructuredSerializeOptions$I %options = {});
};
`Window$I includes `WindowOrWorkerGlobalScope$I;
`WorkerGlobalScope$I includes `WindowOrWorkerGlobalScope$I;
self.`isSecureContext$m
この大域~objは`~secureな文脈$enVを表現するかどうかを返す。 `SECURE-CONTEXTS$r ◎ Returns whether or not this global object represents a secure context. [SECURE-CONTEXTS]
%origin = self.`origin$m
この大域~objの`生成元$を文字列に直列化した結果を返す。 ◎ Returns the global object's origin, serialized as string.
%origin = self.`crossOriginIsolated$m
この大域~obj内で走っている~scriptには、 非同一-生成元~隔離を要求する~APIを利用することは,許容されるかどうかを返す。 これは、[ `Cross-Origin-Opener-Policy$h, `Cross-Origin-Embedder-Policy$h ]~HTTP応答~header, および `cross-origin-isolated$l 特能に依存する。 ◎ Returns whether scripts running in this global are allowed to use APIs that require cross-origin isolation. This depends on the `Cross-Origin-Opener-Policy` and `Cross-Origin-Embedder-Policy` HTTP response headers and the "cross-origin-isolated" feature.

開発者には、 `location.origin@~WINDOW#dom-location-origin$c よりも `self.origin@#dom-origin$c を利用することが強く奨励される。 前者は環境の~URLの`生成元$urlを返す一方で、 後者は環境の`生成元$enVを返す。 `https://stargate.example/^c にある文書~内で実行している次の~scriptを~~考える: ◎ Developers are strongly encouraged to use self.origin over location.origin. The former returns the origin of the environment, the latter of the URL of the environment. Imagine the following script executing in a document on https://stargate.example/:

var %frame = document.createElement("iframe")
%frame.onload = function() {
  var %frameWin = %frame.contentWindow
  console.log(%frameWin.location.origin) // "null"
  console.log(%frameWin.origin) // "https://stargate.example"
}
document.body.appendChild(%frame)

`self.origin^c は、 `location.origin^c よりも依拠-可能な~security指示子である。 ◎ self.origin is a more reliable security indicator.

`isSecureContext@m 取得子~手続きは ⇒ ~RET ~IS[ コレに`関連な設定群~obj$は`~secureな文脈$enVである ] ◎ The isSecureContext getter steps are to return true if this's relevant settings object is a secure context, or false otherwise.
`origin@m 取得子~手続きは ⇒ ~RET `生成元を直列化する$( コレに`関連な設定群~obj$の`生成元$enV ) ◎ The origin getter steps are to return this's relevant settings object's origin, serialized.
`crossOriginIsolated@m 取得子~手続きは ⇒ ~RET コレに`関連な設定群~obj$の`非同一-生成元~能力は隔離されるか?$enV ◎ The crossOriginIsolated getter steps are to return this's relevant settings object's cross-origin isolated capability.

8.3. ~base64用の~~便利~method

[ `atob()$m / `btoa()$m ]~methodにより、 内容~dataと~base64符号化法との間で相互に変形できるようになる。 ◎ The atob() and btoa() methods allow developers to transform content to and from the base64 encoding.

注記: これらの~method名は、 語呂的には "b" は "binary", "a" は "ASCII" を表すと見なせるが、 主に歴史的な理由から,実施においては[ 入力, 出力† ]いずれも ~Unicode文字列である。 ◎ In these APIs, for mnemonic purposes, the "b" can be considered to stand for "binary", and the "a" for "ASCII". In practice, though, for primarily historical reasons, both the input and output of these functions are Unicode strings.

【† `atob()^m が返す値は `ByteString^I 型に改められたが (過去には `DOMString^I 型だった)、 いずれにせよ,~JS側においては文字列になる。 】

%result = self.`btoa(data)$m
~Unicode文字列の形をとる入力~data — 範囲 { `0000^U 〜 `00FF^U } 内の文字のみからなり,各~文字が[ 範囲 { 0x00 〜 0xFF } 内の同じ値をとる~binary~byte ]を表現する~data — を~base64表現へ変換した結果を返す。 ◎ Takes the input data, in the form of a Unicode string containing only characters in the range U+0000 to U+00FF, each representing a binary byte with values 0x00 to 0xFF respectively, and converts it to its base64 representation, which it returns.
入力~文字列~内に範囲~外の文字がある場合、 `InvalidCharacterError$E 例外が投出される。 ◎ Throws an "InvalidCharacterError" DOMException exception if the input string contains any out-of-range characters.
%result = self.`atob(data)$m
~Unicode文字列の形をとる[ ~base64に符号化された~binary~data ]を包含する入力を~Unicode文字列 — 範囲 { `0000^U 〜 `00FF^U } 内の文字のみからなり,各~文字が[ 範囲 { 0x00 〜 0xFF } 内の同じ値をとる~binary~byte ]を表現する文字列 — へ復号した結果を返す。 ◎ Takes the input data, in the form of a Unicode string containing base64-encoded binary data, decodes it, and returns a string consisting of characters in the range U+0000 to U+00FF, each representing a binary byte with values 0x00 to 0xFF respectively, corresponding to that binary data.
入力~文字列が妥当な~base64~dataでない場合、 `InvalidCharacterError$E 例外が投出される。 ◎ Throws an "InvalidCharacterError" DOMException if the input string is not valid base64 data.

`btoa(data)@m ~method~手続きは: ◎ The btoa(data) method must\

  1. ~IF[ %data 内に[ 符号位置 ~GT `00FF^U ]を満たす文字がある ] ⇒ ~THROW `InvalidCharacterError$E ◎ throw an "InvalidCharacterError" DOMException if data contains any character whose code point is greater than U+00FF.\
  2. ~RET `~forgiving-base64符号化する$( `同型に符号化する$( %data ) ) ◎ Otherwise, the user agent must convert data to a byte sequence whose nth byte is the eight-bit representation of the nth code point of data, and then must apply forgiving-base64 encode to that byte sequence and return the result.

`atob(data)@m ~method~手続きは: ◎ The atob(data) method steps are:

  1. %結果 ~LET `~forgiving-base64復号する$( %data ) ◎ Let decodedData be the result of running forgiving-base64 decode on data.
  2. ~IF[ %結果 ~EQ `失敗^i ] ⇒ ~THROW `InvalidCharacterError$E ◎ If decodedData is failure, then throw an "InvalidCharacterError" DOMException.
  3. ~RET %結果 ◎ Return decodedData.

8.4. 動的~markup挿入

【 この節の内容の和訳は、 `別~page@~HTMLdynamic#dynamic-markup-insertion$にて。 】

8.5. ~DOMの構文解析-法

【 この節の内容の和訳は、 `別~page@~HTMLdynamic#dom-parsing-and-serialization$にて。 】

8.6. ~timer

[ `setTimeout()$m / `setInterval()$m ]~methodにより、 作者は,~timerに基づく~callbackを~scheduleできるようになる。 ◎ The setTimeout() and setInterval() methods allow authors to schedule timer-based callbacks.

%id = self.`setTimeout(handler [, timeout [, ...arguments ] ])$m
%timeout ~milli秒~後に %handler を走らす~timeoutを~scheduleする。 %arguments は そのまま %handler に渡される。 ◎ Schedules a timeout to run handler after timeout milliseconds. Any arguments are passed straight through to the handler.
%id = self.`setTimeout(code [, timeout ])$m
%timeout ~milli秒~後に %code を~compileして走らす~timeoutを~scheduleする ◎ Schedules a timeout to compile and run code after timeout milliseconds.
self.`clearTimeout(id)$m
[ `setTimeout()$m / `setInterval()$m により設定された~timeout ]のうち, %id で識別されるものを取消す。 ◎ Cancels the timeout set with setTimeout() or setInterval() identified by id.
%id = self.`setInterval(handler [, timeout [, ...arguments ] ])$m
%timeout ~milli秒ごとに %handler を走らす~timeoutを~scheduleする。 %arguments は そのまま %handler に渡される。 ◎ Schedules a timeout to run handler every timeout milliseconds. Any arguments are passed straight through to the handler.
%id = self.`setInterval(code [, timeout ])$m
%timeout ~milli秒ごとに %code を~compileしてを走らす~timeoutを~scheduleする。 ◎ Schedules a timeout to compile and run code every timeout milliseconds.
self.`clearInterval(id)$m
[ `setTimeout()$m / `setInterval()$m により設定された~timeout ]のうち, %id で識別されるものを取消す。 ◎ Cancels the timeout set with setInterval() or setTimeout() identified by id.

注記: ~timerは、 入子にできる。 ただし,そのような入子な~timerが 5 個を超えて以降は、 ~intervalは 4 ~milli秒~以上に強制される。 ◎ Timers can be nested; after five such nested timers, however, the interval is forced to be at least four milliseconds.

注記: この~APIは、 ~timerを正確に~schedule通りに走らすことは保証しない。 ~CPU負荷, 他の~task, 等々に因る延期が予期される。 ◎ This API does not guarantee that timers will run exactly on schedule. Delays due to CPU load, other tasks, etc, are to be expected.

`WindowOrWorkerGlobalScope$I ~mixinを実装する~objは、 `作動中な~timer群が成す~map@ を持つ — それは`有順序~map$であり,初期~時は空とする。 この~mapを成す各~entryの: ◎ Objects that implement the WindowOrWorkerGlobalScope mixin have a map of active timers, which is a map, initially empty.\

注記: `作動中な~timer群が成す~map$を成す~entryのうち, その~keyが数値になるものは、 `~timer初期化~手続き$により — すなわち,[ `setTimeout()$m / `setInterval()$m ]により — ~~作成されたものに限られる。 他の仕様が`手続きを~timeout後に走らす$~algoを利用するときは、 当の識別子は,数値~以外の一意な値になる。 [ `clearTimeout()$m / `clearInterval()$m ]が影響するのは,数値を~keyとする~timer限られるが、 すべての~timerは, `遊休~刻限の算出@~WAPI#idle-deadline-computation$に寄与することに加え, 関連な大域~objが破壊されるとき~clearされる。 ◎ For entries put in the map of active timers by the timer initialization steps, i.e., by setTimeout() and setInterval(), the keys are numbers. For other specifications that use the run steps after a timeout algorithm, the identifier is a unique non-numeric value. Only the numeric-keyed timers are affected by clearTimeout() and clearInterval(), but all timers contribute to idle deadline computation, and are cleared when the relevant global is destroyed.


`setTimeout(handler, timeout, ...arguments)@m ~method~手続きは ⇒ ~RET `~timer初期化~手続き$( ↓ ) ⇒# コレ, %handler, %timeout, %arguments ◎ The setTimeout(handler, timeout, ...arguments) method steps are to return the result of running the timer initialization steps given this, handler, timeout, arguments, and false.
`setInterval(handler, timeout, ...arguments)@m ~method~手続きは ⇒ ~RET `~timer初期化~手続き$( ↓ ) ⇒# コレ, %handler, %timeout, %arguments, `繰返す^i ◎ The setInterval(handler, timeout, ...arguments) method steps are to return the result of running the timer initialization steps given this, handler, timeout, arguments, and true.

[ `clearTimeout(id)@m / `clearInterval(id)@m ]~method~手続きは、いずれも ⇒ コレの`作動中な~timer群が成す~map$[ %id ] ~SET ε ◎ The clearTimeout(id) and clearInterval(id) method steps are to remove this's map of active timers[id].

注記: 両~methodとも,同じ~mapに属する~entryを~clearするので、 どちらも[ `setTimeout()$m / `setInterval()$m ]で作成された~timerを~clearするのに利用できる。 ◎ Because clearTimeout() and clearInterval() clear entries from the same map, either method can be used to clear timers created by setTimeout() or setInterval().


`~timer初期化~手続き@ は、所与の ⇒# `WindowOrWorkerGlobalScope$I %大域~obj, 文字列または `Function$I %~handler, ~~整数 %~timeout, ~list %引数~群, %繰返すか ~IN { `繰返す^i, ε } (省略時は ε ), %前回の~ID(省略時は ε ) ◎終 に対し,次を走らす: ◎ The timer initialization steps, given a WindowOrWorkerGlobalScope global, a string or Function handler, a number timeout, a list arguments, a boolean repeat, and optionally (and only if repeat is true) a number previousId, are:

  1. %thisArg ~LET %大域~obj に応じて ⇒# `WorkerGlobalScope$I ~objであるならば %大域~obj / `Window$I ~objであるならば %大域~obj に対応する `WindowProxy$I ~obj ◎ Let thisArg be global if that is a WorkerGlobalScope object; otherwise let thisArg be the WindowProxy that corresponds to global.
  2. %~ID ~LET %前回の~ID ◎ If previousId was given, let id be previousId;\
  3. ~IF[ %~ID ~EQ ε ] ⇒ %~ID ~SET 次を満たす`実装定義$な整数 ⇒ [ 正である ]~AND[ %大域~obj の`作動中な~timer群が成す~map$[ %~ID ] ~EQ ε ] ◎ otherwise, let id be an implementation-defined integer that is greater than zero and does not already exist in global's map of active timers.
  4. %入子ng~level ~LET 0 ◎ ↓
  5. ~IF[ `~surrounding~agent$の`~event~loop$aGにて`現在~走っている~task$は, この~algoにより作成された`~task$である ] ⇒ %入子ng~level ~LET その~taskの`~timerの入子ng~level$ ◎ If the surrounding agent's event loop's currently running task is a task that was created by this algorithm, then let nesting level be the task's timer nesting level. Otherwise, let nesting level be zero.

    注記: ~taskの`~timerの入子ng~level$は、[ `setTimeout()$m に対する入子な~call, `setInterval()$m により作成される繰返な~timer ]のどちらにも利用される(この 2 つの組合nも含め)。 言い換えれば、 特定0の~methodではなく,この~algoの入子な呼出nを表現する。 ◎ The task's timer nesting level is used both for nested calls to setTimeout(), and for the repeating timers created by setInterval(). (Or, indeed, for any combination of the two.) In other words, it represents nested invocations of this algorithm, not of a particular method.

  6. ~IF[ %~timeout ~LT 0 ] ⇒ %~timeout ~SET 0 ◎ If timeout is less than 0, then set timeout to 0.
  7. ~IF[ %入子ng~level ~GT 5 ]~AND[ %~timeout ~LT 4 ] ⇒ %~timeout ~SET 4 ◎ If nesting level is greater than 5, and timeout is less than 4, then set timeout to 4.
  8. %~realm ~LET %大域~obj に`関連な~realm$ ◎ Let realm be global's relevant realm.
  9. %起動ng~script ~LET `作動中な~script$ ◎ Let initiating script be the active script.
  10. %~task ~LET 次の手続きを走らす`~task$: ◎ Let task be a task that runs the following substeps:

    1. ~IF[ %大域~obj の`作動中な~timer群が成す~map$[ %~ID ] ~EQ ε ] ⇒ ~RET ◎ If id does not exist in global's map of active timers, then abort these steps.
    2. `~timer~handler用に計時~報を記録する$( %~handler, %大域~obj に`関連な設定群~obj$, %繰返すか ) ◎ Record timing info for timer handler given handler, global's relevant settings object, and repeat.
    3. ~IF[ %~handler は `Function$I である ] ⇒ `~callback関数を呼出す$( %~handler, %引数~群, %thisArg ) ⇒ 例外が投出されたときは、~catchして ⇒# その`例外を報告する$ ◎ If handler is a Function, then invoke handler given arguments with the callback this value set to thisArg. If this throws an exception, catch it, and report the exception.
    4. ~ELSE: ◎ Otherwise:

      1. ~Assert: %~handler は文字列である ◎ Assert: handler is a string.
      2. `HostEnsureCanCompileStrings$jA( %~realm ) を遂行する ⇒ 例外が投出されたときは、~catchして ⇒# その`例外を報告する$; ~RET ◎ Perform HostEnsureCanCompileStrings(realm). If this throws an exception, catch it, report the exception, and abort these steps.
      3. %設定群~obj ~LET %大域~obj に`関連な設定群~obj$ ◎ Let settings object be global's relevant settings object.
      4. %~fetch~option群 ~LET `既定の古典~script~fetch~option群$ ◎ Let fetch options be the default classic script fetch options.
      5. %基底~URL ~LET %設定群~obj の`~API用~基底~URL$enV ◎ Let base URL be settings object's API base URL.
      6. ~IF[ %起動ng~script ~NEQ ~NULL ]: ◎ If initiating script is not null, then:

        1. %~fetch~option群 ~SET 新たな`~script~fetch~option群$ — その ⇒# `暗号用~nonce$sfO ~SET %起動ng~script の`~fetch~option群$sC の`暗号用~nonce$sfO, `完全性~metadata$sfO ~SET 空~文字列, `構文解析器~metadata$sfO ~SET `not-parser-inserted^l, `資格証~mode$sfO ~SET %起動ng~script の`~fetch~option群$sC の`資格証~mode$sfO, `~referrer施策$sfO ~SET %起動ng~script の`~fetch~option群$sC の`~referrer施策$sfO, `~fetch優先度$sfO ~SET `auto^l ◎ Let fetch options be a script fetch options whose cryptographic nonce is initiating script's fetch options's cryptographic nonce, integrity metadata is the empty string, parser metadata is "not-parser-inserted", credentials mode is initiating script's fetch options's credentials mode, referrer policy is initiating script's fetch options's referrer policy, and fetch priority is "auto".
        2. %基底~URL ~SET %起動ng~script の`基底~URL$sC ◎ Set base URL to initiating script's base URL.

        この手続きによる効果は、[ `setTimeout()$m / `setInterval()$m ]が文字列を~compileするときの挙動は, `eval()$c によるそれと等価になることを確保する。 すなわち、 `import()$c 介して~fetchする【される?】`~module~script$は, 両~文脈において同じに挙動することになる。 ◎ The effect of these steps ensures that the string compilation done by setTimeout() and setInterval() behaves equivalently to that done by eval(). That is, module script fetches via import() will behave the same in both contexts.

      7. %~script ~LET `古典~scriptを作成する$( ↓ ) ⇒# %~handler, %設定群~obj, %基底~URL, %~fetch~option群 ◎ Let script be the result of creating a classic script given handler, settings object, base URL, and fetch options.
      8. `古典~scriptを走らす$( %~script ) ◎ Run the classic script script.
    5. ~IF[ %大域~obj の`作動中な~timer群が成す~map$[ %~ID ] ~EQ ε ] ⇒ ~RET ◎ If id does not exist in global's map of active timers, then abort these steps.

      注記: %~ID ~entryは、 %~handler 内の作者~codeが[ `clearTimeout()$m / `clearInterval()$m ]を~callして除去されるかもしれない。 ◎ It might have been removed via the author code in handler calling clearTimeout() or clearInterval().

    6. ~IF[ %繰返すか ~EQ `繰返す^i ] ⇒ `~timer初期化~手続き$( ↓ ) ⇒# %大域~obj, %~handler, %~timeout, %引数~群, `繰返す^i, %~ID ◎ If repeat is true, then perform the timer initialization steps again, given global, handler, timeout, arguments, true, and id.
    7. ~ELSE ⇒ %大域~obj の`作動中な~timer群が成す~map$[ %~ID ] ~SET ε ◎ Otherwise, remove global's map of active timers[id].
  11. %入子ng~level ~INCBY 1 ◎ Increment nesting level by one.
  12. %~task の`~timerの入子ng~level@ ~SET %入子ng~level ◎ Set task's timer nesting level to nesting level.
  13. %完了~手続き ~LET 次を走らす~algo ⇒ `大域~taskを~queueする$( `~timer~task~source@ , %大域~obj, %~task ) ◎ Let completionStep be an algorithm step which queues a global task on the timer task source given global to run task.
  14. `手続きを~timeout後に走らす$( ↓ ) ⇒# %大域~obj, `setTimeout/setInterval^l, %~timeout, %完了~手続き, %~ID ◎ Run steps after a timeout given global, "setTimeout/setInterval", timeout, completionStep, and id.
  15. ~RET %~ID ◎ Return id.

注記: ~Web~IDLに定義されるとおり、 引数の変換は,`~timer初期化~手続き$が呼出される前に~Web~IDLにて定義される~algo内で起こる (例:最初の引数として渡された~objに対し `toString()^m ~methodを呼出すなど): ◎ Argument conversion as defined by Web IDL (for example, invoking toString() methods on objects passed as the first argument) happens in the algorithms defined in Web IDL, before this algorithm is invoked.

例えば、次のちっぽけな~codeによる結果の %log は `ONE TWO ^l になる: ◎ So for example, the following rather silly code will result in the log containing "ONE TWO ":

var %log = '';
function logger(%s) { %log += %s + ' '; }

setTimeout({ toString: function () {
  setTimeout("logger('ONE')", 100);
  return "logger('TWO')";
} }, 100);

数~milli秒かかる~taskを間断なく遅延なしに走らせつつ, ~browserにも~UIに応じる余裕を与える (および,~browserが~CPU~~時間を得るために~scriptを強制終了するのを避ける) ためには、 単純に作業を遂行する前に次回の~timerを~queueする: ◎ To run tasks of several milliseconds back to back without any delay, while still yielding back to the browser to avoid starving the user interface (and to avoid the browser killing the script for hogging the CPU), simply queue the next timer before performing work:

function doExpensiveWork() {
  var %done = false;
  // ...
  /* 
この部分は、
%done を ~T に設定するまでに数~milli秒かかる
◎
this part of the function takes up to five milliseconds set done to true if we're done
 */
  // ...

  return %done;
}

function rescheduleWork() {
  var %id = setTimeout(rescheduleWork, 0); /*
      
次回の反復を予め~scheduleしておく
◎
preschedule next iteration
 */
  if (doExpensiveWork())
    clearTimeout(%id); /*
      
用済みになったら~timeoutを~clearする
◎
clear the timeout if we don't need it
 */
}

function scheduleWork() {
  setTimeout(rescheduleWork, 0);
}

scheduleWork(); /*
  
たくさんの作業を行う~taskを~queueする
◎
queues a task to do lots of work
 */

`手続きを~timeout後に走らす@ ときは、所与の ⇒# `WindowOrWorkerGlobalScope$I %大域~obj, 文字列 %順序付け識別子, 数値 %~milli秒数, 手続き %完了~手続き, 値 %~timer~key (省略時は ε ) ◎終 に対し: ◎ To run steps after a timeout, given a WindowOrWorkerGlobalScope global, a string orderingIdentifier, a number milliseconds, a set of steps completionSteps, and an optional value timerKey:

  1. ~Assert: [ %~timer~key ~NEQ ε ]ならば、 この~algoの~call元は`~timer初期化~手続き$である (他の仕様は、 %~timer~key として ε 以外を渡してはナラナイ)。 ◎ Assert: if timerKey is given, then the caller of this algorithm is the timer initialization steps. (Other specifications must not pass timerKey.)
  2. ~IF[ %~timer~key ~EQ ε ] ⇒ %~timer~key ~SET 新たな数値~以外の一意な値 ◎ If timerKey is not given, then set it to a new unique non-numeric value.
  3. %開始-時刻 ~LET `現在の高分解能~時刻$( %大域~obj ) ◎ Let startTime be the current high resolution time given global.
  4. %大域~obj の`作動中な~timer群が成す~map$[ %~timer~key ] ~SET ( %開始-時刻 ~PLUS %~milli秒数 ) ◎ Set global's map of active timers[timerKey] to startTime plus milliseconds.
  5. この段は`並列的$に走らす: ◎ Run the following steps in parallel:

    1. %大域~obj に応じて:

      • `Window$I ~objである場合 ⇒ %大域~obj に`結付けられた文書$が`全部的に作動中$になるまで 更に %~milli秒数 ~milli秒~待機する (連続的でなくともよい 【?】 )。
      • `WorkerGlobalScope$I ~objである場合 ⇒ ~workerを休止せずに %~milli秒数 ~milli秒~待機する (連続的でなくともよい)。
      ◎ If global is a Window object, wait until global's associated Document has been fully active for a further milliseconds milliseconds (not necessarily consecutively). ◎ Otherwise, global is a WorkerGlobalScope object; wait until milliseconds milliseconds have passed with the worker not suspended (not necessarily consecutively).
    2. [ この~algoのこの呼出n %A より先に呼出された,この~algoの他の呼出n %B ]のうち, ~AND↓ を満たすものがあれば、 それらが完了するまで待機する:

      • 完了していない
      • %B における %大域~obj ~EQ %A における %大域~obj
      • %B における %順序付け識別子 ~EQ %A における %順序付け識別子
      • %B における %~milli秒数 ~LTE %A における %~milli秒数 †

      【† 例えば ( %A, %B ) における %~milli秒数 が ( 1, 2 ) の場合、 %B が %A より 100 ~milli秒~早く呼出されていても, %A から先に実行される余地があることになる。 】

      ◎ Wait until any invocations of this algorithm that had the same global and orderingIdentifier, that started before this one, and whose milliseconds is less than or equal to this one's, have completed.
    3. 任意選択で ⇒ `実装定義$な長さの時間だけ待機する ◎ Optionally, wait a further implementation-defined length of time.

      注記: この段には、[ 機器の電力消費を最適化する必要に応じて,~timeoutを~~延長する ]ことを~UAに許容することが意図される。 例えば,~timerの粒度を抑えるような節電~modeを備える処理器も中にはある — そのような~platformでは、 ~UAは,より正確aな非~節電~modeを利用することを要求する代わりに, この~scheduleに収まるよう~timerを遅くできる。 ◎ This is intended to allow user agents to pad timeouts as needed to optimize the power usage of the device. For example, some processors have a low-power mode where the granularity of timers is reduced; on such platforms, user agents can slow timers down to fit this schedule instead of requiring the processor to use the more accurate mode with its associated higher power usage.

    4. %完了~手続き を遂行する ◎ Perform completionSteps.
    5. ~IF[ %~timer~key は数値でない ] ⇒ %大域~obj の`作動中な~timer群が成す~map$[ %~timer~key ] ~SET ε ◎ If timerKey is a non-numeric value, remove global's map of active timers[timerKey].

`手続きを~timeout後に走らす$は、 他の仕様が `setTimeout()$m と類似な方式で[ 開発者が給した~codeを開発者が給した~timeout後に実行したい ]と求めるとき利用するために意味される (しかしながら、 それには `setTimeout()$m の[ 入子にする/【 %~timeout を】切り上げる ]挙動はないことに注意)。 そのような仕様は、 %順序付け識別子 を選ぶことで, 自身の仕様の~timeoutたちの順序付けを[ 他の仕様の~timeoutとの順序付けを拘束しない ]よう確保できる。 ◎ Run steps after a timeout is meant to be used by other specifications that want to execute developer-supplied code after a developer-supplied timeout, in a similar manner to setTimeout(). (Note, however, it does not have the nesting and clamping behavior of setTimeout().) Such specifications can choose an orderingIdentifier to ensure ordering within their specification's timeouts, while not constraining ordering with respect to other specification's timeouts.

8.7. 小taskの~queue法

%self.`queueMicrotask(callback)$m
所与の %callback を走らす`小taskを~queueする$。 ◎ Queues a microtask to run the given callback.

`queueMicrotask(callback)@m ~method~手続きは ⇒ `小taskを~queueする$( 次の手続き )

手続きは ⇒ `~callback関数を呼出す$( %callback, « » ) ⇒ %callback から例外が投出されたときは ⇒ その`例外を報告する$
◎ The queueMicrotask(callback) method must queue a microtask to invoke callback, and if callback throws an exception, report the exception.

`queueMicrotask()$m ~methodは、 作者の~callbackを`小task~queue$上に~scheduleすることを許容する。 これは、当の~callbackの~codeを — 例えば `setTimeout(f, 0)$m を利用したときのように、 `~event~loop$に制御を戻すことなく — `~JS実行~文脈~stack$が次回に空になったとき,走らすことを許容する — それが起こるのは、 現在~実行-中な同期的な~JSすべてが完了まで走ったときである。 ◎ The queueMicrotask() method allows authors to schedule a callback on the microtask queue. This allows their code to run once the JavaScript execution context stack is next empty, which happens once all currently executing synchronous JavaScript has run to completion. This doesn't yield control back to the event loop, as would be the case when using, for example, setTimeout(f, 0).

作者は、[ いくつもの小taskを~scheduleするのは、 いくつもの同期的~codeを走らすのと同じ悪影響を処理能に及ぼす ]ことを,自覚すること。 どちらも,~browserが描画などの自前の作業を行うのを~~妨げる。 多くの事例では、[ `requestAnimationFrame()$m / `requestIdleCallback()$m ]を選ぶ方が良い。 特に,次回の描画~周回より前に~codeを走らすのが目標なら、 `requestAnimationFrame()$m がその目的を果たす。 ◎ Authors ought to be aware that scheduling a lot of microtasks has the same performance downsides as running a lot of synchronous code. Both will prevent the browser from doing its own work, such as rendering. In many cases, requestAnimationFrame() or requestIdleCallback() is a better choice. In particular, if the goal is to run code before the next rendering cycle, that is the purpose of requestAnimationFrame().

`queueMicrotask()$m は、 次の例から見てとれるように,同期的な~codeを配列し直す仕組みと捉えるのが最も良い — 実質的に、~queueした~codeを[ 現在~実行-中な同期的な~JSが完了まで走った直後 ]に配置するような。 ◎ As can be seen from the following examples, the best way of thinking about queueMicrotask() is as a mechanism for rearranging synchronous code, effectively placing the queued code immediately after the currently executing synchronous JavaScript has run to completion.

`queueMicrotask()$m を利用する最も共通的な理由として、[ 情報が同期的に可用になる事例でも,過度な遅延が導入される ]ことはないよう,順序を一貫させることが挙げられる。 ◎ The most common reason for using queueMicrotask() is to create consistent ordering, even in the cases where information is available synchronously, without introducing undue delay.

例えば、 ある~custom要素を考える — それは、 `load^et ~eventを発火することに加え,以前に読込んだ~dataも内部~cacheに保守する。 素朴に実装するなら、 次の様になろう: ◎ For example, consider a custom element firing a load event, that also maintains an internal cache of previously-loaded data. A naïve implementation might look like:

MyElement.prototype.loadData = function (%url) {
  if (this._cache[%url]) {
    this._setData(this._cache[%url]);
    this.dispatchEvent(new Event("load"));
  } else {
    fetch(%url).then(%res => %res.arrayBuffer()).then(%data => {
      this._cache[%url] = %data;
      this._setData(%data);
      this.dispatchEvent(new Event("load"));
    });
  }
};

しかしながら,この実装には、 利用者にとって挙動が一貫しなくなり得る問題がある。 例えば、次のような~codeでは: ◎ This naïve implementation is problematic, however, in that it causes its users to experience inconsistent behavior. For example, code such as

%element.addEventListener("load", () => console.log("loaded"));
console.log("1");
%element.loadData();
console.log("2");

`1^l, `2^l, `loaded^l の順に~logすることもあれば (~dataを~fetchする必要がある場合)、 `1^l, `loaded^l, `2^l の順に~logすることもある (~dataは すでに~cacheされている場合)。 同様に、[ `loadData()^c を~callした直後の時点で,要素に~dataが設定されるかどうか ]も一貫しなくなる。 ◎ will sometimes log "1, 2, loaded" (if the data needs to be fetched), and sometimes log "1, loaded, 2" (if the data is already cached). Similarly, after the call to loadData(), it will be inconsistent whether or not the data is set on the element.

`queueMicrotask()$m を利用すれば、 順序は一貫するようになる: ◎ To get a consistent ordering, queueMicrotask() can be used:

MyElement.prototype.loadData = function (%url) {
  if (this._cache[%url]) {
    queueMicrotask(() => {
      this._setData(this._cache[%url]);
      this.dispatchEvent(new Event("load"));
    });
  } else {
    fetch(%url).then(%res => %res.arrayBuffer()).then(%data => {
      this._cache[%url] = %data;
      this._setData(%data);
      this.dispatchEvent(new Event("load"));
    });
  }
};

これは、本質的に,~queueされた~codeを[ `~JS実行~文脈~stack$が空になった後に走らす ]よう配列し直して、 要素~状態の順序付けや更新が一貫することを確保する。 ◎ By essentially rearranging the queued code to be after the JavaScript execution context stack empties, this ensures a consistent ordering and update of the element's state.

`queueMicrotask()$m には、 別の興味を引く利用もある — それは、協調していない複数の~call元からの作業を “~batch” できるようにする。 例えば、[ なるべく早く~dataを送信したいが、 容易に避けれるなら,複数の~network要請は為さない ]ことが求まれる,ある~library関数を考える。 これらを兼ね備えるには、 次の様な仕方がある: ◎ Another interesting use of queueMicrotask() is to allow uncoordinated "batching" of work by multiple callers. For example, consider a library function that wants to send data somewhere as soon as possible, but doesn't want to make multiple network requests if doing so is easily avoidable. One way to balance this would be like so:

const %queuedToSend = [];

function sendData(%data) {
  %queuedToSend.push(%data);

  if (%queuedToSend.length === 1) {
    queueMicrotask(() => {
      const %stringToSend = JSON.stringify(%queuedToSend);
      %queuedToSend.length = 0;

      fetch("/endpoint", %stringToSend);
    });
  }
}

このように~~構成しておけば、 `sendData()^c を現在~実行-中な同期的な~JSの中で~~後続して何回か~callしても, 1 回の `fetch()$m ~callにまとめるよう~batchされる — ~fetchに先んじるような介在する~event~loop~taskを経ずに (代わりに `setTimeout()$m を利用した類似な~codeでは、 そのような~taskが起こることになる)。 ◎ With this architecture, multiple subsequent calls to sendData() within the currently executing synchronous JavaScript will be batched together into one fetch() call, but with no intervening event loop tasks preempting the fetch (as would have happened with similar code that instead used setTimeout()).

8.8. 利用者~向けの~prompt

8.8.1. 単純な~dialog

%window.`alert(message)$m
所与の~messageを伴う~modal~alertを表示して、 利用者がそれを退けるまで待機する。 ◎ Displays a modal alert with the given message, and waits for the user to dismiss it.
%result = %window.`confirm(message)$m
所与の~messageを伴う[ OK / Cancel ]~modal~promptを表示して、 利用者がそれを退けるまで待機する。 利用者が[ OK を~clickしたなら ~T / Cancel を~clickしたなら ~F ]を返す。 ◎ Displays a modal OK/Cancel prompt with the given message, waits for the user to dismiss it, and returns true if the user clicks OK and false if the user clicks Cancel.
%result = %window.`prompt(message [, default])$m
~text~control, および所与の~messageを伴う~modal~promptを表示して、 利用者がそれを退けるまで待機する。 利用者が[ ~promptを取消したなら ~NULL / ~ELSE_ 利用者が手入力した値 ]を返す。 %default 引数が在る場合、 その値が既定の~~入力として利用される。 ◎ Displays a modal text control prompt with the given message, waits for the user to dismiss it, and returns the value that the user entered. If the user cancels the prompt, then returns null instead. If the second argument is present, then the given value is used as a default.

注記: これらの~methodが呼出された場合、 `~media~data$を読込んでいる`~media要素$などの[ `~task$/`小task$ ]に依存する~logicは停滞する。 ◎ Logic that depends on tasks or microtasks, such as media elements loading their media data, are stalled when these methods are invoked.

`~alert0()@m / `alert(message)@m ~method~手続きは: ◎ The alert() and alert(message) method steps are:

  1. ~IF[ コレは`単純~dialogを示せない$ ] ⇒ ~RET ◎ If we cannot show simple dialogs for this, then return.
  2. %message ~LET [ この~methodは引数を伴わずに呼出されたならば空~文字列 / ~ELSE_ ~methodの最初の引数 ] ◎ If the method was invoked with no arguments, then let message be the empty string; otherwise, let message be the method's first argument.
  3. %message ~SET `文字列を任意選択で切落す$( `改行文字を正規化する$( %message ) ) ◎ Set message to the result of normalizing newlines given message. ◎ Set message to the result of optionally truncating message.
  4. `000A^U LF を改行として扱う下で,利用者に %message を示す ◎ Show message to the user, treating U+000A LF as a line break.
  5. `~WebDriver-BiDi利用者~promptが開かれた$( コレ, `alert^l, %message ) ◎ Invoke WebDriver BiDi user prompt opened with this, "alert", and message.
  6. 任意選択で ⇒ 利用者が~messageを認知するまで`静止する$ ◎ Optionally, pause while waiting for the user to acknowledge the message.
  7. `~WebDriver-BiDi利用者~promptが閉じられた$( コレ, ~T ) ◎ Invoke WebDriver BiDi user prompt closed with this and true.

注記: 歴史的な理由から、 この~methodは, 2 個の多重定義を利用して定義されており,~optional引数は利用していない。 これによる実用的な影響iは、 `alert(undefined)^c は `alert("undefined")^c として扱われる一方で, `alert()^c は `alert("")^c として扱われることである。 ◎ This method is defined using two overloads, instead of using an optional argument, for historical reasons. The practical impact of this is that alert(undefined) is treated as alert("undefined"), but alert() is treated as alert("").

`confirm(message)@m ~method~手続きは: ◎ The confirm(message) method steps are:

  1. ~IF[ コレは`単純~dialogを示せない$ ] ⇒ ~RET ~F ◎ If we cannot show simple dialogs for this, then return false.
  2. %message ~SET `文字列を任意選択で切落す$( `改行文字を正規化する$( %message ) ) ◎ Set message to the result of normalizing newlines given message. ◎ Set message to the result of optionally truncating message.
  3. `000A^U LF を改行として扱う下で,利用者に %message を示して、 利用者に肯定か否定か訊ねる ◎ Show message to the user, treating U+000A LF as a line break, and ask the user to respond with a positive or negative response.
  4. `~WebDriver-BiDi利用者~promptが開かれた$( コレ, `confirm^l, %message ) ◎ Invoke WebDriver BiDi user prompt opened with this, "confirm", and message.
  5. 利用者が応答するまで`静止する$ ◎ Pause until the user responds either positively or negatively.
  6. %結果 ~LET 利用者の応答に応じて ⇒ 肯定ならば ~T / 否定ならば ~F ◎ ↓
  7. `~WebDriver-BiDi利用者~promptが閉じられた$( コレ, %結果 ) ◎ Invoke WebDriver BiDi user prompt closed with this, and true if the user responded positively or false otherwise.
  8. ~RET %結果 ◎ If the user responded positively, return true; otherwise, the user responded negatively: return false.

`prompt(message, default)@m ~method~手続きは: ◎ The prompt(message, default) method steps are:

  1. ~IF[ コレは`単純~dialogを示せない$ ] ⇒ ~RET ~NULL ◎ If we cannot show simple dialogs for this, then return null.
  2. %message ~SET `文字列を任意選択で切落す$( `改行文字を正規化する$( %message ) ) ◎ Set message to the result of normalizing newlines given message. ◎ Set message to the result of optionally truncating message.
  3. %default ~SET `文字列を任意選択で切落す$( %default ) ◎ Set default to the result of optionally truncating default.
  4. `000A^U LF を改行として扱う下で,利用者に %message を示して、 既定の応答を %default 値にする下で,利用者に 文字列~値で応答するか中止するか訊ねる ◎ Show message to the user, treating U+000A LF as a line break, and ask the user to either respond with a string value or abort. The response must be defaulted to the value given by default.
  5. `~WebDriver-BiDi利用者~promptが開かれた$( コレ, `prompt^l, %message, %default ) ◎ Invoke WebDriver BiDi user prompt opened with this, "prompt", message, and default.
  6. 利用者が応答するまで`静止する$ ◎ Pause while waiting for the user's response.
  7. %結果 ~SET [ 利用者が中止したならば ~NULL / ~ELSE_ 利用者が応答した文字列 ] ◎ Let result be null if the user aborts, or otherwise the string that the user responded with.
  8. %応答したか ~LET ~IS[ %結果 ~NEQ ~NULL ] ◎ ↓
  9. `~WebDriver-BiDi利用者~promptが閉じられた$( コレ, %応答したか, %結果 ) ◎ Invoke WebDriver BiDi user prompt closed with this, false if result is null or true otherwise, and result.
  10. ~RET %結果 ◎ Return result.

`文字列を任意選択で切落す@ ときは、所与の ( 文字列 %s ) に対し,[ %s そのままか,または %s から導出されるより短い何らかの文字列 ]を返す。 ~UAは、 %s から省かれた部位を表示するための~UIを供するべきでない — そうすると “~securityに関する重要事項です。次を~clickして全部的な詳細を読んで下さい。” のような類の~dialogを容易に作成できてしまい,濫用され易くなるので。 ◎ To optionally truncate a simple dialog string s, return either s itself or some string derived from s that is shorter. User agents should not provide UI for displaying the elided portion of s, as this makes it too easy for abusers to create dialogs of the form "Important security alert! Click 'Show More' for full details!".

注記: 例えば~UAは、 ~messageの最初の 100 文字だけ表示したり, 文字列を "…" で中略するよう求めるかもしれない。 この種の改変は、 不自然に巨大な, もっともらしい~system~dialogに濫用される~~可能性を制限するのに有用になり得る。 ◎ For example, a user agent might want to only display the first 100 characters of a message. Or, a user agent might replace the middle of the string with "…". These types of modifications can be useful in limiting the abuse potential of unnaturally large, trustworthy-looking system dialogs.

所与の`~window$ %~window は、 次の~algoが ~T を返すとき, `単純~dialogを示せない@ とされる: ◎ We cannot show simple dialogs for a Window window when the following algorithm returns true:

  1. ~IF[ `~sandbox化( ~modal )~flag$ ~IN [ %~window に`結付けられた文書$にて`作動中な~sandbox法~flag集合$ ]] ⇒ ~RET ~T ◎ If the active sandboxing flag set of window's associated Document has the sandboxed modals flag set, then return true.
  2. ~IF[ ( %~window に`関連な設定群~obj$の`生成元$enV, %~window に`関連な設定群~obj$の`~top-level生成元$enV ) は`同じ生成元~domain$でない ] ⇒ ~RET ~T ◎ If window's relevant settings object's origin and window's relevant settings object's top-level origin are not same origin-domain, then return true.
  3. 任意選択で ⇒ ~IF[ %~window に`関連な~agent$の`~event~loop$aGの`終了n入子ng~level$ ~NEQ 0 ] ⇒ ~RET ~T ◎ If window's relevant agent's event loop's termination nesting level is nonzero, then optionally return true.
  4. 任意選択で ⇒ ~RET ~T

    (例えば,~UAは、 利用者に,以降の~modal~dialogをすべて無視する選択肢を与えることもできる — 利用者がその選択肢を選んだ場合、 この手続きを呼出した~methodは,それ以降 呼出される度に,この段で中止されることになる。)

    ◎ Optionally, return true. (For example, the user agent might give the user the option to ignore all modal dialogs, and would thus abort at this step whenever the method was invoked.)
  5. ~RET ~F ◎ Return false.

8.8.2. 印刷-法

%window.`print()$m
利用者に~pageを印刷する旨を~promptする。 ◎ Prompts the user to print the page.

`print()@m ~method~手続きは: ◎ The print() method steps are:

  1. %文書 ~LET コレに`結付けられた文書$ ◎ Let document be this's associated Document.
  2. ~IF[ %文書 は`全部的に作動中$でない ] ⇒ ~RET ◎ If document is not fully active, then return.
  3. ~IF[ %文書 の`~unload~counter$ ~GT 0 ] ⇒ ~RET ◎ If document's unload counter is greater than 0, then return.
  4. ~IF[ %文書 は`~load後~task用に準備済み$である ] ⇒ %文書 の`印刷-時の手続き$docを走らす ◎ If document is ready for post-load tasks, then run the printing steps for document.
  5. ~ELSE ⇒ %文書 の `読込んだとき印刷するか@doc ~SET ~T 【この~flagは、初期~時には暗黙的に ~F をとる】 ◎ Otherwise, set document's print when loaded flag.

~UAは、 利用者から文書 %文書 の`物理形を得する$ (例:印刷, あるいは ~PDF などの物理形の表現も含む) 機会を依頼されたときも、 `印刷-時の手続き$docを走らすべきである。 ◎ User agents should also run the printing steps whenever the user asks for the opportunity to obtain a physical form (e.g. printed copy), or the representation of a physical form (e.g. PDF copy), of a document.

所与の %文書 の `印刷-時の手続き@doc は: ◎ The printing steps for a Document document are:

  1. 任意選択で、 次のいずれかまたは両方を行う: ◎ The user agent may display a message to the user or return (or both).

    • 利用者に~messageを表示する
    • ~RET

    一例として,~kiosk~browserは、 `print()$m ~methodに対する呼出n すべてを黙って無視することもできる。 ◎ For instance, a kiosk browser could silently ignore any invocations of the print() method.

    一例として,~mobile機器~上の~browserは、 近くに印刷機がないことを検出したなら, “~PDFに保存” の選択肢を提供するに先立って その旨を伝える~messageを表示することもできる。 ◎ For instance, a browser on a mobile device could detect that there are no printers in the vicinity and display a message saying so before continuing to offer a "save to PDF" option.

  2. ~IF[ `~sandbox化( ~modal )~flag$ ~IN %文書 にて`作動中な~sandbox法~flag集合$ ] ⇒ ~RET ◎ If the active sandboxing flag set of document has the sandboxed modals flag set, then return.

    注記: 印刷-用~dialogが %文書 の~sandboxで阻止された場合、 `beforeprint$et / `afterprint$et ~eventは発火されない。 ◎ If the printing dialog is blocked by a Document's sandbox, then neither the beforeprint nor afterprint events will be fired.

  3. %文書~群 ~LET %文書, および[ %文書 内の各 `子~navigable$【にて`作動中な文書$nav】 ]からなる集合 【順序は定義されていない。】 ◎ ↓
  4. %文書~群 を成す ~EACH( %D ) に対し ⇒ `~eventを発火する$( %D に`関連な大域~obj$, `beforeprint$et ) ◎ The user agent must fire an event named beforeprint at the relevant global object of document, as well as any child navigable in it.

    ここで先祖に向けて発火しないことは、 ~~正しいとは思えない — 何らかの~taskを~queueする必要がある見込みが高い。 `課題 #5096@~HTMLissue/5096$ を見よ。 ◎ Firing in children only doesn't seem right here, and some tasks likely need to be queued. See issue #5096.

    `beforeprint$et ~eventは、 印刷される複製に注釈を加えるときに利用できる — 一例として,印刷した時刻を追加するなど。 ◎ The beforeprint event can be used to annotate the printed copy, for instance adding the time at which the document was printed.

  5. ~UAは、 利用者に %文書 の`物理形を得する$(または その表現を得る)機会を提供するべきである — そうする場合 ⇒ 利用者が受容するか辞退するまで待機してもヨイ — そうする場合 ⇒ 待機-中は`静止する$モノトスル。 ◎ The user agent should offer the user the opportunity to obtain a physical form (or the representation of a physical form) of document. The user agent may wait for the user to either accept or decline before returning; if so, the user agent must pause while the method is waiting.\

    待機するかどうかにかかわらず、 当の物理形には,この~algoのこの時点における %文書 の状態を利用するモノトスル。 ◎ Even if the user agent doesn't wait at this point, the user agent must use the state of the relevant documents as they are at this point in the algorithm if and when it eventually creates the alternate form.

  6. %文書~群 を成す ~EACH( %D ) に対し ⇒ `~eventを発火する$( %D に`関連な大域~obj$, `afterprint$et ) ◎ The user agent must fire an event named afterprint at the relevant global object of document, as well as any child navigables in it.

    ここで先祖に向けて発火しないことは、 ~~正しいとは思えない — 何らかの~taskを~queueする必要がある見込みが高い。 `課題 #5096@~HTMLissue/5096$ を見よ。 ◎ Firing in children only doesn't seem right here, and some tasks likely need to be queued. See issue #5096.

    `afterprint$et ~eventは、 `beforeprint$et ~event時に追加された注釈を復帰するため, あるいは印刷-後の~UIを示すためにも利用できる。 後者の一例としては、 利用者に 何段階かにわたる手続きを踏んでもらう~pageがあるとき、 ~scriptは,印刷-後に 自動的に次の段階へ進めることもできる。 ◎ The afterprint event can be used to revert annotations added in the earlier event, as well as showing post-printing UI. For instance, if a page is walking the user through the steps of applying for a home loan, the script could automatically advance to the next step after having printed a form or other.

8.9. ~systemの状態と能力

【 この節の内容の和訳は、 `別~page@~HTMLnavigator$にて。 】

8.10. 画像

[Exposed=(Window,Worker), `Serializable$, `Transferable$]
interface `ImageBitmap@I {
  readonly attribute unsigned long `width$m;
  readonly attribute unsigned long `height$m;
  undefined `close$m();
};

typedef (`CanvasImageSource$I or
         `Blob$I or
         `ImageData$I) `ImageBitmapSource@I;

enum `ImageOrientation@I { `from-image$l, `flipY$l };
enum `PremultiplyAlpha@I { `none$l, `premultiply$l, `default$l };
enum `ColorSpaceConversion@I { `~none0$l, `~default0$l };
enum `ResizeQuality@I { `pixelated$l, `low$l, `medium$l, `high$l };

dictionary `ImageBitmapOptions@I {
  `ImageOrientation$I `imageOrientation$m = `from-image$l;
  `PremultiplyAlpha$I `premultiplyAlpha$m = `default$l;
  `ColorSpaceConversion$I `colorSpaceConversion$m = `~default0$l;
  [EnforceRange] unsigned long `resizeWidth$m;
  [EnforceRange] unsigned long `resizeHeight$m;
  `ResizeQuality$I `resizeQuality$m = `low$l;
};

`ImageBitmap$I ~objは、 過度な待時間なく~canvasに塗れるような,~bitmap画像を表現する。 ◎ An ImageBitmap object represents a bitmap image that can be painted to a canvas without undue latency.

注記: 何を以って過度な待時間とするかの正確な判定は実装者に委ねられるが、 一般に,~bitmapの利用-時に ~network I/O, や~local~disk I/O を要するならば, 待時間はおそらく過度になる。 一方で,他を阻むのは GPU や~system RAM からの読取nに限られるならば、 待時間はおそらく受容-可能になる。 ◎ The exact judgement of what is undue latency of this is left up to the implementer, but in general if making use of the bitmap requires network I/O, or even local disk I/O, then the latency is probably undue; whereas if it only requires a blocking read from a GPU or system RAM, the latency is probably acceptable.

%promise = self.`createImageBitmap$m(%image [, %options ])
%promise = self.`createImageBitmap$m(%image, %sx, %sy, %sw, %sh [, %options ])
所与の %image から新たな `ImageBitmap$I が作成された時点で解決される,~promiseを返す — %image は次のいずれかをとり得る ⇒ `img$e 要素 / `~SVG-image$ 要素 / `video$e 要素 / `canvas$e 要素 / `Blob$I ~obj / `ImageData$I ~obj / 別の `ImageBitmap$I ~obj ◎ Takes image, which can be an img element, an SVG image element, a video element, a canvas element, a Blob object, an ImageData object, or another ImageBitmap object, and returns a promise that is resolved when a new ImageBitmap is created.
`ImageBitmap$I ~objを構築できなかった場合 — 例えば、供された %image ~dataが実際には画像でなかったなど — ~promiseは却下される。 ◎ If no ImageBitmap object can be constructed, for example because the provided image data is not actually an image, then the promise is rejected instead.
%sx, %sy, %sw, %sh 引数が供された場合、 ~source画像は,それらが成す矩形に切抜かれる — 元の画像に無い画素は、 `透明な黒$に置換される。【!* clip?】 これらの座標は、 ~source画像の~pixel座標~空間であり,`~CSS~pixel$数`ではない^em。 ◎ If sx, sy, sw, and sh arguments are provided, the source image is cropped to the given pixels, with any pixels missing in the original replaced by transparent black. These coordinates are in the source image's pixel coordinate space, not in CSS pixels.
%options が供された場合、 `ImageBitmap$I ~objの~bitmap~dataは, %options に則って改変される。 例えば[ %options の `premultiplyAlpha$m ~option ~EQ `premultiply$l ]ならば、 `~bitmap~data$ の各~色~channelは その`~alpha~channelにより乗算済み$にされる。 ◎ If options is provided, the ImageBitmap object's bitmap data is modified according to options. For example, if the premultiplyAlpha option is set to "premultiply", the bitmap data's color channels are premultiplied by its alpha channel.

~source画像の状態が妥当でない場合、 ~promiseは `InvalidStateError$E で却下される — 例えば:

  • 成功裡に読込まれなかった `img$e 要素
  • `ImageBitmap$I ~objであって[ `Detached$sl 内部~slot値 ~EQ ~T ]なるもの
  • `ImageData$I ~objであって[ `data$m 属性~値の `ViewedArrayBuffer^sl 内部~slotは detached 【 `IsDetachedBuffer$jA( 内部~slotの値 ) ~EQ ~T 】 ]なるもの
  • `Blob$I であって その~dataを~bitmap画像に解釈できないもの
◎ Rejects the promise with an "InvalidStateError" DOMException if the source image is not in a valid state (e.g., an img element that hasn't loaded successfully, an ImageBitmap object whose [[Detached]] internal slot value is true, an ImageData object whose data attribute value's [[ViewedArrayBuffer]] internal slot is detached, or a Blob whose data cannot be interpreted as a bitmap image).
~scriptから~source画像の画像~dataへの~accessは許容されない場合、 ~promiseは `SecurityError$E 例外で却下される (例: `~CORS非同一-生成元$の `video$e / 別の`生成元$からの~worker内の~scriptにより描かれている `canvas$e )。 ◎ Rejects the promise with a "SecurityError" DOMException if the script is not allowed to access the image data of the source image (e.g. a video that is CORS-cross-origin, or a canvas being drawn on by a script in a worker from another origin).
%imageBitmap.`close$m()
%imageBitmap の下層の`~bitmap~data$を解放する。 ◎ Releases imageBitmap's underlying bitmap data.
%imageBitmap.`width$m
画像の`生来な横幅$を`~CSS~pixel$数で返す。 ◎ Returns the natural width of the image, in CSS pixels.
%imageBitmap.`height$m
画像の`生来な縦幅$を`~CSS~pixel$数で返す。 ◎ Returns the natural height of the image, in CSS pixels.

各 `ImageBitmap$I %O は: ◎ ↓

各 `ImageBitmap$I は、 `直列化-可能$/`転送-可能$である: ◎ ImageBitmap objects are serializable objects and transferable objects.


[ `createImageBitmap(image, options)@m / `createImageBitmap(image, sx, sy, sw, sh, options)^m ]~method~手続きは: ◎ The createImageBitmap(image, options) and createImageBitmap(image sx, sy, sw, sh, options) methods, when invoked, must run these steps:

  1. %xywh ~LET ~IS[ %sx, %sy, %sw, %sh 引数は指定されている ] ◎ ↓
  2. ~IF[ %xywh ~EQ ~T ] ⇒ ~IF[ %sw ~EQ 0 ]~OR[ %sh ~EQ 0 ] ⇒# ~RET `却下される~promise$( `RangeError$E 例外 ) ◎ If either sw or sh is given and is 0, then return a promise rejected with a RangeError.
  3. `~resize横幅@V ~LET %options[ "`resizeWidth@m" ] ◎ ↓
  4. `~resize縦幅@V ~LET %options[ "`resizeHeight@m" ] ◎ ↓
  5. ~IF[ `~resize横幅$V ~EQ 0 ]~OR[ `~resize横幅$V ~EQ 0 ] ⇒# `却下される~promise$( `InvalidStateError$E 例外 ) ◎ If either options's resizeWidth or options's resizeHeight is present and is 0, then return a promise rejected with an "InvalidStateError" DOMException.
  6. %image `引数は利用-可能か検査する@~HEcanvas#check-the-usability-of-the-image-argument$ ⇒ ~IF[ 例外が投出された/結果は `不良^i ] ⇒# `却下される~promise$( `InvalidStateError$E 例外 ) ◎ Check the usability of the image argument. If this throws an exception or returns bad, then return a promise rejected with an "InvalidStateError" DOMException.
  7. %promise ~LET `新たな~promise$ ◎ Let p be a new promise.
  8. 以下を遂行する:

    【 この訳では,原文の~algoを再構成している — その重複している~logicを この段の中に集約して, 重複していない部分を 下の “`~bitmap~dataを取得する$” に抜き出すことにより。 】

    1. %~bitmapを得る手続き ~LET 次を走らす手続き:

      1. ( %~bitmap~data, %生成元cleanか ) ~LET `~bitmap~dataを取得する$( %image )
      2. ~IF[ %~bitmap~data ~EQ ε ] ⇒ ~RET ε
      3. %O ~LET 新たな `ImageBitmap$I ~obj
      4. %O の`~bitmap~data$ ~SET `~source矩形に切抜いて整形する$( %~bitmap~data )
      5. %O の~bitmapの`生成元cleanか$ ~SET %生成元cleanか
      6. ~RET %O
    2. ~IF[ %image は `Blob$I ~objである ]:

      1. この段は、 `並列的$に走らす:

        1. %~bitmap ~LET %~bitmapを得る手続き()
        2. ~IF[ %~bitmap ~NEQ ε ] ⇒ `~promiseを解決する$( %promise, %~bitmap )
        3. ~ELSE ⇒ `~promiseを却下する$( %promise, `InvalidStateError$E 例外 )
    3. ~ELSE:

      1. %~bitmap ~LET %~bitmapを得る手続き()
      2. ~IF[ %~bitmap ~EQ ε ] ⇒ ~RET `却下される~promise$( `InvalidStateError$E 例外 )
      3. 次を`並列的$に走らす ⇒ `~promiseを解決する$( %promise, %~bitmap )
    4. ~RET %promise
    ◎ ↓

上の手続きにて `~bitmap~dataを取得する@ 下位-手続きは、 所与の ( %image ) に対し, %image に応じて次を走らす: ◎ Let imageBitmap be a new ImageBitmap object. ◎ Switch on image:

`img$e
`~SVG-image$
  1. %寸法 ~LET %image の~media~dataの`生来な寸法$ ◎ ↓
  2. ~IF[ %寸法 ~EQ ε (例:内容~sizeが指定されていない~vector~graphic) ]:

    1. ~IF[ `~resize横幅$V ~EQ ε ]~OR[ `~resize縦幅$V ~EQ ε ] ⇒ ~RET ( ε, ε )
    2. ~UAは、 %image を~size ( `~resize横幅$V, `~resize縦幅$V ) の~bitmapに描画するべきである 【 “べき” とは?】
    ◎ If image's media data has no natural dimensions (e.g., it's a vector graphic with no specified content size) and either options's resizeWidth or options's resizeHeight is not present, then a promise rejected with an "InvalidStateError" DOMException. ◎ If image's media data has no natural dimensions (e.g., it's a vector graphics with no specified content size), it should be rendered to a bitmap of the size specified by the resizeWidth and the resizeHeight options.
  3. %~bitmap~data ~LET %image の~media~dataを`代表する~bitmap~data$の複製 ◎ Set imageBitmap's bitmap data to a copy of image's media data, cropped to the source rectangle with formatting. If this is an animated image, imageBitmap's bitmap data must only be taken from the default image of the animation (the one that the format defines is to be used when animation is not supported or is disabled), or, if there is no such image, the first frame of the animation.
  4. %生成元cleanか ~LET ~IS[ ~NOT %image `引数は生成元cleanでない$ ] ◎ If image is not origin-clean, then set the origin-clean flag of imageBitmap's bitmap to false.
  5. ~RET ( %~bitmap~data, %生成元cleanか ) ◎ Run this step in parallel: • Resolve p with imageBitmap.
`video$e
  1. ~IF[ %image の `networkState$m 属性~値 ~EQ `NETWORK_EMPTY$m ] ⇒ ~RET ( ε, ε ): ◎ If image's networkState attribute is NETWORK_EMPTY, then return a promise rejected with an "InvalidStateError" DOMException.
  2. %~bitmap~data ~LET `現在の再生位置$にある~frameの複製 — その~sizeは `~media資源$の ( `生来な横幅$video, `生来な縦幅$video ) とする (すなわち,縦横比による補正は適用-済み) ◎ Set imageBitmap's bitmap data to a copy of the frame at the current playback position, at the media resource's natural width and natural height (i.e., after any aspect-ratio correction has been applied), cropped to the source rectangle with formatting.
  3. %生成元cleanか ~LET ~IS[ ~NOT %image `引数は生成元cleanでない$ ] ◎ If image is not origin-clean, then set the origin-clean flag of imageBitmap's bitmap to false.
  4. ~RET ( %~bitmap~data, %生成元cleanか ) ◎ Run this step in parallel: • Resolve p with imageBitmap.
`canvas$e
  1. ~RET ( %image の`~bitmap~data$の複製, %image の~bitmapの`生成元cleanか$ ) ◎ Set imageBitmap's bitmap data to a copy of image's bitmap data, cropped to the source rectangle with formatting. ◎ Set the origin-clean flag of the imageBitmap's bitmap to the same value as the origin-clean flag of image's bitmap. ◎ Run this step in parallel: • Resolve p with imageBitmap.
`Blob$I ~obj
  1. %画像~data ~LET %image から~dataを読取る 【`読取n演算@~FILEAPI#readOperation$により?】 ⇒ `読取る間に~errorが生じた@~FILEAPI#file-error-read$ときは ⇒ ~RET ( ε, ε ) ◎ Run these step in parallel: ◎ Let imageData be the result of reading image's data. If an error occurs during reading of the object, then reject p with an "InvalidStateError" DOMException and abort these steps.
  2. %画像~data の公式的な型 ~LET [ %image の `type$m 属性で与えられる~MIME型 ]を与える下で,`画像を特定的に~sniffするための規則$を適用して、 %画像~data の~file形式を決定した結果 ◎ Apply the image sniffing rules to determine the file format of imageData, with MIME type of image (as given by image's type attribute) giving the official type.
  3. ~IF[ ~OR↓ ]…

    • %画像~data の公式的な型は~supportされる画像~file形式でない (例:画像でない)
    • %画像~data は破損している
    • %画像~data から寸法を得せない (例: 生来な~sizeを伴わない~vector~graphic)

    …ならば ⇒ ~RET ( ε, ε )

    ◎ If imageData is not in a supported image file format (e.g., it's not an image at all), or if imageData is corrupted in some fatal way such that the image dimensions cannot be obtained (e.g., a vector graphic with no natural size), then reject p with an "InvalidStateError" DOMException and abort these steps.
  4. %~bitmap~data ~LET %画像~data を`代表する~bitmap~data$ ◎ Set imageBitmap's bitmap data to imageData, cropped to the source rectangle with formatting. If this is an animated image, imageBitmap's bitmap data must only be taken from the default image of the animation (the one that the format defines is to be used when animation is not supported or is disabled), or, if there is no such image, the first frame of the animation.
  5. ~RET ( %~bitmap~data, ~T ) ◎ Resolve p with imageBitmap.
`ImageData$I
  1. ~IF[ `IsDetachedBuffer$jA( %image の `data$m 属性~値の `ViewedArrayBuffer^sl 内部~slot値 ) ~EQ ~T ] ⇒ ~RET ( ε, ε ) ◎ Let buffer be image's data attribute value's [[ViewedArrayBuffer]] internal slot. ◎ If IsDetachedBuffer(buffer) is true, then return a promise rejected with an "InvalidStateError" DOMException.
  2. ~RET ( %image が与える画像~data, ~T ) ◎ Set imageBitmap's bitmap data to image's image data, cropped to the source rectangle with formatting. ◎ Run this step in parallel: • Resolve p with imageBitmap.
`ImageBitmap$I
  1. ~RET ( %image の`~bitmap~data$の複製, %image の~bitmapの`生成元cleanか$ ) ◎ Set imageBitmap's bitmap data to a copy of image's bitmap data, cropped to the source rectangle with formatting. ◎ Set the origin-clean flag of imageBitmap's bitmap to the same value as the origin-clean flag of image's bitmap. ◎ Run this step in parallel: • Resolve p with imageBitmap.
`VideoFrame$I
  1. ~RET ( %image の可視な画素~dataの複製, ~T ) ◎ Set imageBitmap's bitmap data to a copy of image's visible pixel data, cropped to the source rectangle with formatting. ◎ Run this step in parallel: • Resolve p with imageBitmap.

◎ ↑↑Return p.

所与の %画像~data を `代表する~bitmap~data@ は、次の結果を返す:

  1. ~IF[ %画像~data は~animated画像でない ] ⇒ ~RET %画像~data
  2. ~RET [ %画像~data の形式にて[ ~animationが ~supportされないか不能化されている ]ときに利用するものと定義されている既定の画像 ]が[ あれば それ / なければ~animationの最初の~frame ]
◎ ↑

上の手続きにて `~source矩形に切抜いて整形する@ 下位-手続きは、 所与の ( `~bitmap~data$ %入力 ) に対し,次を走らす: ◎ When the steps above require that the user agent crop bitmap data to the source rectangle with formatting, the user agent must run the following steps: • Let input be the bitmap data being transformed.

  1. %~source矩形 ~LET ( 左端, 上端, 右端, 下端 ) が次で与えられる矩形:

    %xywh ~EQ ~T の場合
    • 左端: min( %sx, %sx + %sw )
    • 上端: min( %sy, %sy + %sh )
    • 右端: max( %sx, %sx + %sw )
    • 下端: max( %sy, %sy + %sh )
    他の場合
    ( 0, 0, %入力 の横幅, %入力 の縦幅 )
    ◎ If sx, sy, sw and sh are specified, let sourceRectangle be a rectangle whose corners are the four points (sx, sy), (sx+sw, sy),(sx+sw, sy+sh), (sx,sy+sh). Otherwise let sourceRectangle be a rectangle whose corners are the four points (0,0), (width of input, 0), (width of input, height of input), (0, height of input). ◎ If either sw or sh are negative, then the top-left corner of this rectangle will be to the left or above the (sx, sy) point.
  2. ( %横幅, %縦幅 ) ~LET %~source矩形 の ( 横幅, 縦幅 )
  3. ( %出力~横幅, %出力~縦幅 ) ~LET (`~resize横幅$V, `~resize縦幅$V ) に応じて,次の表tで与えられる値を整数に切り上げた結果:

    `~resize横幅$V `~resize縦幅$V %出力~横幅 %出力~縦幅
    非ε 非ε `~resize横幅$V `~resize縦幅$V
    非ε ε `~resize横幅$V %縦幅 × `~resize横幅$V ÷ %横幅
    ε 非ε %横幅 × `~resize縦幅$V ÷ %縦幅 `~resize縦幅$V
    ε ε %横幅 %縦幅
    ◎ Let outputWidth be determined as follows: • If the resizeWidth member of options is specified •• the value of the resizeWidth member of options • If the resizeWidth member of options is not specified, but the resizeHeight member is specified •• the width of sourceRectangle, times the value of the resizeHeight member of options, divided by the height of sourceRectangle, rounded up to the nearest integer • If neither resizeWidth nor resizeHeight are specified •• the width of sourceRectangle Let outputHeight be determined as follows: • If the resizeHeight member of options is specified •• the value of the resizeHeight member of options • If the resizeHeight member of options is not specified, but the resizeWidth member is specified •• the height of sourceRectangle, times the value of the resizeWidth member of options, divided by the width of sourceRectangle, rounded up to the nearest integer • If neither resizeWidth nor resizeHeight are specified •• the height of sourceRectangle
  4. %平面 ~LET ( x 軸は右向き, y 軸は下向き ) にされた, 広さ無限な, `透明な黒$の平面 ◎ ↓
  5. %入力 を,次に従うように %平面 に~~合成する:

    • %入力 の左上隅は、 %平面 の原点に位置させる。
    • %入力 画像~data内の各~画素は、 %平面 において 1 × 1 の正方形を占めるとする。
    ◎ Place input on an infinite transparent black grid plane, positioned so that its top left corner is at the origin of the plane, with the x-coordinate increasing to the right, and the y-coordinate increasing down, and with each pixel in the input image data occupying a cell on the plane's grid.
  6. %出力 ~LET [ %平面 上の %~source矩形 が占める矩形~内の画像 ]を~size ( %出力~横幅, %出力~縦幅 ) に拡縮した結果 ⇒ これに利用する拡縮ng~algoは、 `resizeQuality$m ~optionの値を目安にするべきである ◎ Let output be the rectangle on the plane denoted by sourceRectangle. ◎ Scale output to the size specified by outputWidth and outputHeight. The user agent should use the value of the resizeQuality option to guide the choice of scaling algorithm.
  7. %options[ "`imageOrientation@m" ] に応じて:

    `flipY@l
    %出力 を縦向きに裏返す — ~sourceの画像~方位~metadata( `EXIF$r ~metadataなど)があっても無視rする ◎ If the value of the imageOrientation member of options is "flipY", output must be flipped vertically, disregarding any image orientation metadata of the source (such as EXIF metadata), if any. [EXIF]
    `from-image@l
    何もしない ◎ If the value is "from-image", no extra step is needed.

    注記: 列挙~値には `none^l も利用されていたが、 `from-image$l に改称された。 将来には、 `none^l を追加し直すことになる — 異なる意味を伴わせて。 ◎ There used to be a "none" enum value. It was renamed to "from-image". In the future, "none" will be added back with a different meaning.

  8. ~IF[ %image は `img$e 要素または `Blob$I ~objである ] ⇒ %options[ "`colorSpaceConversion@m" ] に応じて: ◎ If image is an img element or a Blob object, let val be the value of the colorSpaceConversion member of options, and then run these substeps:

    `~default0@l
    色~空間の変換の挙動は,実装に特有である — 実装は、 画像を~canvasに描く際に利用する既定の色~空間に則って選ぶべきである。 ◎ If val is "default", the color space conversion behavior is implementation-specific, and should be chosen according to the default color space that the implementation uses for drawing images onto the canvas.
    `~none0@l
    %出力 は、 色~空間の変換を遂行することなく復号するモノトスル。 すなわち,画像を復号する~algoは、[ ~source~data内に埋込まれている色~profile~metadata, 表示~機器の色~profile ]どちらも無視するモノトスル。 ◎ If val is "none", output must be decoded without performing any color space conversions. This means that the image decoding algorithm must ignore color profile metadata embedded in the source data as well as the display device color profile.
  9. %options[ "`premultiplyAlpha@m" ] に応じて: ◎ Let val be the value of premultiplyAlpha member of options, and then run these substeps:

    `default@l
    %出力 を~alphaにより乗算済みにするかどうかは、 実装に特有である — 実装は、[ 画像を~canvasに描くために最適と判断されるもの ]に則って選ぶべきである。 ◎ If val is "default", the alpha premultiplication behavior is implementation-specific, and should be chosen according to implementation deems optimal for drawing images onto the canvas.
    `premultiply@l
    ~IF[ %出力 は~alphaにより乗算済みでない ] ⇒ %出力 のすべての 色~成分を`~alphaで乗算する$ ◎ If val is "premultiply", the output that is not premultiplied by alpha must have its color components multiplied by alpha and that is premultiplied by alpha must be left untouched.
    `none@l
    ~IF[ %出力 は~alphaにより乗算済みである ] ⇒ %出力 のすべての色~成分を`~alphaで除算する$ ◎ If val is "none", the output that is not premultiplied by alpha must be left untouched and that is premultiplied by alpha must have its color components divided by alpha.
  10. ~RET %出力 ◎ Return output.

`close()@m ~method~手続きは: ◎ The close() method steps are:

  1. コレの `Detached$sl 内部~slot値 ~SET ~T ◎ Set this's [[Detached]] internal slot value to true.
  2. コレの`~bitmap~data$ ~SET ε ◎ Unset this's bitmap data.

`width@m 取得子~手続きは: ◎ The width getter steps are:

  1. ~IF[ コレの `Detached$sl 内部~slotの値 ~EQ ~T ] ⇒ ~RET 0 ◎ If this's [[Detached]] internal slot's value is true, then return 0.
  2. ~RET `~CSS~pixel$数による,コレの横幅 ◎ Return this's width, in CSS pixels.

`height@m 取得子~手続きは: ◎ The height getter steps are:

  1. ~IF[ コレの `Detached$sl 内部~slotの値 ~EQ ~T ] ⇒ ~RET 0 ◎ If this's [[Detached]] internal slot's value is true, then return 0.
  2. ~RET `~CSS~pixel$数による,コレの縦幅 ◎ Return this's height, in CSS pixels.

`resizeQuality@m ~memberは、 `ResizeQuality$I 列挙~値をとり,[ 画像の拡縮-時に利用する補間~品質の選好 ]を表出するために利用される — とり得る値の意味は: ◎ The ResizeQuality enumeration is used to express a preference for the interpolation quality to use when scaling images.

`pixelated@l
画像の外観をできるだけ保つような選好を指示する。 双線形~補間など、 色を “滑らかに” 拡縮する~algoは,受容-可能である。 ◎ The "pixelated" value indicates a preference to scale the image that maximizes the appearance. Scaling algorithms that "smooth" colors are acceptable, such as bilinear interpolation.
`low@l
低~品質な画像~補間の選好を指示する。 計算量は `high$l より少なく済み得る。 ◎ The "low" value indicates a preference for a low level of image interpolation quality. Low-quality image interpolation may be more computationally efficient than higher settings.
`medium@l
中間~品質な画像~補間の選好を指示する。 ◎ The "medium" value indicates a preference for a medium level of image interpolation quality.
`high@l
高~品質な画像~補間の選好を指示する。 計算量は `low$l より多くなり得る。 ◎ The "high" value indicates a preference for a high level of image interpolation quality. High-quality image interpolation may be more computationally expensive than lower settings.

注記: 双線形~拡縮-法は、 比較的~高速に画像を滑らかに補間するが,より低~品質な~algoの例である。 双三次 / Lanczos 拡縮-法は、 より高~品質な出力を生産する画像~拡縮ng~algoの例である。 この仕様は、 値 `pixelated$l を除いて,特定の補間~algoの利用を義務付けない。 ◎ Bilinear scaling is an example of a relatively fast, lower-quality image-smoothing algorithm. Bicubic or Lanczos scaling are examples of image-scaling algorithms that produce higher-quality output. This specification does not mandate that specific interpolation algorithms be used unless the value is "pixelated".

この~APIを利用して、 ~sprite-sheetを事前に切り分けて準備する例: ◎ Using this API, a sprite sheet can be precut and prepared:

var %sprites = {};
function loadMySprites() {
  var %image = new Image();
  %image.src = 'mysprites.png';
  var %resolver;
  var %promise = new Promise(function (%arg) { %resolver = %arg });
  %image.onload = function () {
    %resolver(Promise.all([
      createImageBitmap(%image,  0,  0, 40, 40)
        .then(function (%image) { %sprites.person = %image }),
      createImageBitmap(%image, 40,  0, 40, 40)
        .then(function (%image) { %sprites.grass  = %image }),
      createImageBitmap(%image, 80,  0, 40, 40)
        .then(function (%image) { %sprites.tree  = %image }),
      createImageBitmap(%image,  0, 40, 40, 40)
        .then(function (%image) { %sprites.hut   = %image }),
      createImageBitmap(%image, 40, 40, 40, 40)
        .then(function (%image) { %sprites.apple = %image }),
      createImageBitmap(%image, 80, 40, 40, 40)
        .then(function (%image) { %sprites.snake = %image })
    ]));
  };
  return %promise;
}

function runDemo() {
  var %canvas = document.querySelector('canvas#demo');
  var %context = %canvas.getContext('2d');
  %context.drawImage(%sprites.tree, 30, 10);
  %context.drawImage(%sprites.snake, 70, 10);
}

loadMySprites().then(runDemo);

8.11. ~animation~frame

一部の~objは、 `AnimationFrameProvider$I ~interface~mixinを内包する。 ◎ Some objects include the AnimationFrameProvider interface mixin.

callback `FrameRequestCallback@I = undefined (`DOMHighResTimeStamp$I time);

interface mixin `AnimationFrameProvider@I {
  unsigned long `requestAnimationFrame$m(`FrameRequestCallback$I callback);
  undefined `cancelAnimationFrame$m(unsigned long handle);
};
`Window$I includes `AnimationFrameProvider$I;
`DedicatedWorkerGlobalScope$I includes `AnimationFrameProvider$I;

各 `AnimationFrameProvider$I ~objは、 自身の内部~状態を格納する `~target~obj@ を持つ — それは、 ~objに応じて次で定義される ⇒# `Window$I であるならば,それに`結付けられた文書$ / `DedicatedWorkerGlobalScope$I であるならば ~obj自身 ◎ Each AnimationFrameProvider object also has a target object that stores the provider's internal state. It is defined as follows: ◎ If the AnimationFrameProvider is a Window • The Window's associated Document ◎ If the AnimationFrameProvider is a DedicatedWorkerGlobalScope • The DedicatedWorkerGlobalScope

各`~target~obj$は、 次のものを持つ:

`~animation~frame~callback~map@
`有順序~map$。 初期~時には空になるモノトスル。
`~animation~frame~callback識別子@
~~整数。 初期~時には 0 になるモノトスル。
◎ Each target object has a map of animation frame callbacks, which is an ordered map that must be initially empty, and an animation frame callback identifier, which is a number that must initially be zero.

`AnimationFrameProvider$I は、 ~OR↓ を満たすならば `~supportされて@ いるものと見なされる: ◎ An AnimationFrameProvider provider is considered supported if any of the following are true:


`requestAnimationFrame(callback)@m ~method~手続きは: ◎ The requestAnimationFrame(callback) method steps are:

  1. ~IF[ コレは`~supportされて$いない ] ⇒ ~THROW `NotSupportedError$E ◎ If this is not supported, then throw a "NotSupportedError" DOMException.
  2. %~target ~LET コレの`~target~obj$ ◎ Let target be this's target object.
  3. %~target の`~animation~frame~callback識別子$ ~INCBY 1 ◎ Increment target's animation frame callback identifier by one,\
  4. %~handle ~LET %~target の`~animation~frame~callback識別子$ ◎ and let handle be the result.
  5. %~target の`~animation~frame~callback~map$[ %~handle ] ~SET %~callback ◎ Let callbacks be target's map of animation frame callbacks. ◎ Set callbacks[handle] to callback.
  6. ~RET %~handle ◎ Return handle.

`cancelAnimationFrame(handle)@m ~method~手続きは: ◎ The cancelAnimationFrame(handle) method steps are:

  1. ~IF[ コレは`~supportされて$いない ] ⇒ ~THROW `NotSupportedError$E ◎ If this is not supported, then throw a "NotSupportedError" DOMException.
  2. コレの`~target~obj$の`~animation~frame~callback~map$[ %handle ] ~SET ε ◎ Let callbacks be this's target object's map of animation frame callbacks. ◎ Remove callbacks[handle].

`各~animation~frame~callbackを走らす@ ときは、所与の ( `~target~obj$ %~target, 時刻印 %now ) に対し,次を走らすモノトスル: ◎ To run the animation frame callbacks for a target object target with a timestamp now:

  1. %~callback~map ~LET %~target の`~animation~frame~callback~map$ ◎ Let callbacks be target's map of animation frame callbacks.
  2. %~callback~handle群 ~LET %~callback~map の`~key群$map ◎ Let callbackHandles be the result of getting the keys of callbacks.
  3. %~callback~handle群 を成す ~EACH( %~handle ) に対し: ◎ For each handle in callbackHandles, if handle exists in callbacks:

    1. %~callback ~LET %~callback~map[ %~handle ] ◎ Let callback be callbacks[handle].
    2. ~IF[ %~callback ~EQ ε ] ⇒ ~CONTINUE ◎ ↑
    3. %~callback~map[ %~handle ] ~SET ε ◎ Remove callbacks[handle].
    4. `~callback関数を呼出す$( %~callback, « %now » ) `WEBIDL$r ⇒ %~callback から例外が投出されたときは ⇒ その`例外を報告する$ ◎ Invoke callback, passing now as the only argument, and if an exception is thrown, report the exception.

~workerの内側では、 `requestAnimationFrame()$m は, `canvas$e 要素から転送された `OffscreenCanvas$I と一緒に利用できる。 先ず文書~内で,制御を~workerへ転送する: ◎ Inside workers, requestAnimationFrame() can be used together with an OffscreenCanvas transferred from a canvas element. First, in the document, transfer control to the worker:

const %offscreenCanvas = document.getElementById("c").transferControlToOffscreen();
%worker.postMessage(%offscreenCanvas, [%offscreenCanvas]);

次に,~worker内の次の~codeは、 左から右へ動く矩形を描くことになる: ◎ Then, in the worker, the following code will draw a rectangle moving from left to right:

let %ctx, %pos = 0;
function draw(%dt) {
  %ctx.clearRect(0, 0, 100, 100);
  %ctx.fillRect(%pos, 0, 10, 10);
  %pos += 10 * %dt;
  requestAnimationFrame(%draw);
}

self.onmessage = function(%ev) {
  const %transferredCanvas = %ev.data;
  %ctx = %transferredCanvas.getContext("2d");
  draw();
};