BehavesLikeとButton Activation Behaviors - カスタム組み込み要素
Web Components
今回はElementInternals.typeに続く案であるBehavesLikeとButton Activation Behaviorsを紹介します。
ElementInternals.typeの問題点 #
TODO: 書く
BehavesLike #
この時点のexplainerはこちらです。 https://github.com/MicrosoftEdge/MSEdgeExplainers/blob/4adf38ed104f551748ccdc5bec84d49541e693a2/ElementInternalsType/explainer.md
ElementInternals.type では以下の問題がありました。
typeとして指定できるものに、buttonやlabelなどのHTMLタグ名と、submitやresetなど<button>のtype属性の値が混ざっていたattachInternals()した後に設定され、いつどこで設定されるのかが明確でなかった- 値を1回しか設定できないのに、命令的なのが分かりづらい
これらを改善するために、ElementInternalsを使う形式ではなく、static behavesLike = 'button'という静的プロパティに値を指定することで追加する機能を指定できるようになりました。また、一旦HTMLタグ名に限定し、今回の提案にはbuttonとlabelだけが含まれました。
例えばbehavesLikeの値としてbuttonを指定すると、elementInternals.buttonMixin.disabledやelementInternals.buttonMixin.popoverTargetElementなどのプロパティにアクセス・更新できるようになります。
labelも同様で、elementInternals.labelMixin.htmlForなどにアクセスできます。
class CustomButton extends HTMLElement {
static behavesLike = "button";
constructor() {
super();
this.internals_ = this.attachInternals();
}
get popoverTargetElement() {
return this.internals_.buttonMixin?.popoverTargetElement ?? null;
}
set popoverTargetElement(element) {
if (this.internals_.buttonMixin) {
this.internals_.buttonMixin.popoverTargetElement = element;
}
}
}
customElements.define("custom-button", CustomButton);
<custom-button popovertarget="my-popover">Open popover</custom-button>
<div id="my-popover" popover>This is popover content.</div>
Activation Behaviors #
最新のexplainerでメインで扱われているものです。 https://github.com/MicrosoftEdge/MSEdgeExplainers/blob/main/ElementInternalsType/explainer.md
BehavesLikeと同じく静的プロパティですが、機能ごとにプロパティが分かれています。例えば<button>の機能を追加したければstatic buttonActivationBehaviors = trueのように設定します。
class CustomButton extends HTMLElement {
static buttonActivationBehaviors = true;
}
customElements.define("custom-button", CustomButton);
<custom-button commandfor="my-popover" command="toggle-popover">
Toggle the popover
</custom-button>
<div id="my-popover" popover>
<p>This popover is controlled by the custom button!</p>
</div>
buttonActivationBehaviorsがtrueになっている場合、現段階ではcommandforとcommandのみサポートされます。今後type="submit"、type="reset"をサポート予定とのことです。
また、暗黙的にrole="button"となり、フォーカス可能になりますが、フォームとの関連付けは行われません。これは9月に行われたARIA WGでの議論の結果を踏まえたものです。