| 1 |
/** |
| 2 |
* @license |
| 3 |
* Copyright 2019 Google LLC |
| 4 |
* SPDX-License-Identifier: BSD-3-Clause |
| 5 |
*/ |
| 6 |
import {ElementInternalsShim} from './lib/element-internals.js'; |
| 7 |
import {EventShim, CustomEventShim} from './lib/events.js'; |
| 8 |
|
| 9 |
export { |
| 10 |
ariaMixinAttributes, |
| 11 |
ElementInternals, |
| 12 |
HYDRATE_INTERNALS_ATTR_PREFIX, |
| 13 |
} from './lib/element-internals.js'; |
| 14 |
export { |
| 15 |
CSSRule, |
| 16 |
CSSRuleList, |
| 17 |
CSSStyleSheet, |
| 18 |
MediaList, |
| 19 |
StyleSheet, |
| 20 |
} from './lib/css.js'; |
| 21 |
export {CustomEvent, Event} from './lib/events.js'; |
| 22 |
export { |
| 23 |
IntersectionObserver, |
| 24 |
MutationObserver, |
| 25 |
ResizeObserver, |
| 26 |
} from './lib/observers.js'; |
| 27 |
|
| 28 |
// In an empty Node.js vm, we need to patch the global context. |
| 29 |
// TODO: Remove these globalThis assignments when we remove support |
| 30 |
// for vm modules (--experimental-vm-modules). |
| 31 |
globalThis.Event ??= EventShim; |
| 32 |
globalThis.CustomEvent ??= CustomEventShim; |
| 33 |
|
| 34 |
const constructionToken = Symbol(); |
| 35 |
|
| 36 |
/** |
| 37 |
* Internal type to be used for the event polyfill functionality. |
| 38 |
* @deprecated Use EventTargetShimMeta directly, if needed. |
| 39 |
*/ |
| 40 |
export type HTMLElementWithEventMeta = HTMLElement & EventTargetShimMeta; |
| 41 |
|
| 42 |
/** |
| 43 |
* Properties necessary for the EventTarget shim to work. |
| 44 |
*/ |
| 45 |
export interface EventTargetShimMeta { |
| 46 |
/** |
| 47 |
* The event target parent represents the previous event target for an event |
| 48 |
* in capture phase and the next event target for a bubbling event. |
| 49 |
* Note that this is not the element parent |
| 50 |
*/ |
| 51 |
__eventTargetParent?: globalThis.EventTarget; |
| 52 |
/** |
| 53 |
* The host event target/element of this event target, if this event target |
| 54 |
* is inside a Shadow DOM. |
| 55 |
*/ |
| 56 |
__host?: globalThis.EventTarget; |
| 57 |
/** |
| 58 |
* A map of slot name to the corresponding slot element. |
| 59 |
* For named slots, the key is the name of the slot and for |
| 60 |
* the unnamed slot, the key is `undefined`. |
| 61 |
* |
| 62 |
* These need to be tracked explicitly since the slot elements are not |
| 63 |
* necessarily in the same tree as the event target, so they can't be found |
| 64 |
* by traversing the event path. This is needed to properly retarget events |
| 65 |
* dispatched on slotted nodes. |
| 66 |
* |
| 67 |
* <my-el1> |
| 68 |
* #shadow-dom (open) |
| 69 |
* <slot></slot> |
| 70 |
* <my-el2> |
| 71 |
* #shadow-dom (closed) |
| 72 |
* <slot></slot> |
| 73 |
* <slot name="nested"></slot> |
| 74 |
* </my-el2> |
| 75 |
* <my-el3 slot="nested"></my-el3> |
| 76 |
* </my-el1> |
| 77 |
* |
| 78 |
* With the above example the shadow DOM of `<my-el1>` is rendered before the |
| 79 |
* child elements of `<my-el1>`, so when the slot elements are rendered, they |
| 80 |
* are added and subsequently removed from the eventTargetStack and when |
| 81 |
* `<my-el3>` is rendered it cannot solely rely on the eventTargetStack |
| 82 |
* and need to check for each custom element in the stack if it has a slot |
| 83 |
* with the name of the slot it is trying to fill. |
| 84 |
*/ |
| 85 |
__slots?: Map<string | undefined, globalThis.HTMLSlotElement>; |
| 86 |
} |
| 87 |
|
| 88 |
const isCaptureEventListener = ( |
| 89 |
options: undefined | AddEventListenerOptions | boolean |
| 90 |
) => (typeof options === 'boolean' ? options : (options?.capture ?? false)); |
| 91 |
|
| 92 |
const enumerableProperty: Record<string, unknown> = {__proto__: null}; |
| 93 |
enumerableProperty.enumerable = true; |
| 94 |
Object.freeze(enumerableProperty); |
| 95 |
|
| 96 |
/** |
| 97 |
* This is a basic implementation of an EventTarget. |
| 98 |
* |
| 99 |
* This is not fully spec compliant (e.g. validation), |
| 100 |
* but should work well enough for our use cases. |
| 101 |
* |
| 102 |
* @see https://dom.spec.whatwg.org/#eventtarget |
| 103 |
* |
| 104 |
* Example Event Path |
| 105 |
* ------------------ |
| 106 |
* |
| 107 |
* Note that this depends on the logic in `packages/labs/ssr/src/lib/render-value.ts`. |
| 108 |
* Any element that is not a custom element or a slot element is skipped in the chain. |
| 109 |
* |
| 110 |
* <main> |
| 111 |
* <my-el1> |
| 112 |
* #shadow-dom (open) |
| 113 |
* <div> |
| 114 |
* <slot></slot> |
| 115 |
* <my-el2> |
| 116 |
* #shadow-dom (closed) |
| 117 |
* <slot></slot> |
| 118 |
* <event-dispatcher3></event-dispatcher3> |
| 119 |
* <slot name="nested"></slot> |
| 120 |
* </my-el2> |
| 121 |
* </div> |
| 122 |
* <event-dispatcher1></event-dispatcher1> |
| 123 |
* <event-dispatcher2 slot="nested"></event-dispatcher2> |
| 124 |
* </my-el1> |
| 125 |
* </main> |
| 126 |
* |
| 127 |
* Given the previous structure, the event path of this shim would be as follows, |
| 128 |
* for the given dispatcher with an event that bubbles (document-fragment |
| 129 |
* represents a ShadowRoot/#shadow-dom instance): |
| 130 |
* |
| 131 |
* <event-dispatcher1>: |
| 132 |
* [event-dispatcher1, slot{my-el1}, document-fragment{my-el1}, my-el1, document] |
| 133 |
* |
| 134 |
* <event-dispatcher2>: |
| 135 |
* [ |
| 136 |
* event-dispatcher2, |
| 137 |
* slot[name="nested"]{my-el1}, |
| 138 |
* slot{my-el2}, |
| 139 |
* document-fragment{my-el2}, |
| 140 |
* my-el2, |
| 141 |
* document-fragment{my-el1}, |
| 142 |
* my-el1, |
| 143 |
* document |
| 144 |
* ] |
| 145 |
* |
| 146 |
* <event-dispatcher3> (without composed): |
| 147 |
* [event-dispatcher3, document-fragment{my-el2}] |
| 148 |
* |
| 149 |
* <event-dispatcher3> (composed): |
| 150 |
* [ |
| 151 |
* event-dispatcher3, |
| 152 |
* document-fragment{my-el2}, |
| 153 |
* my-el2, |
| 154 |
* document-fragment{my-el1}, |
| 155 |
* my-el1, |
| 156 |
* document |
| 157 |
* ] |
| 158 |
*/ |
| 159 |
class EventTarget implements globalThis.EventTarget, EventTargetShimMeta { |
| 160 |
private __eventListeners = new Map< |
| 161 |
string, |
| 162 |
Map<EventListenerOrEventListenerObject, AddEventListenerOptions> |
| 163 |
>(); |
| 164 |
private __captureEventListeners = new Map< |
| 165 |
string, |
| 166 |
Map<EventListenerOrEventListenerObject, AddEventListenerOptions> |
| 167 |
>(); |
| 168 |
private __eventPathCache?: EventTarget[]; |
| 169 |
__eventTargetParent?: EventTarget; |
| 170 |
__host?: EventTarget; |
| 171 |
__slots?: Map<string | undefined, globalThis.HTMLSlotElement>; |
| 172 |
|
| 173 |
addEventListener( |
| 174 |
type: string, |
| 175 |
callback: EventListenerOrEventListenerObject | null, |
| 176 |
options?: AddEventListenerOptions | boolean |
| 177 |
): void { |
| 178 |
if (callback === undefined || callback === null) { |
| 179 |
return; |
| 180 |
} |
| 181 |
const eventListenersMap = isCaptureEventListener(options) |
| 182 |
? this.__captureEventListeners |
| 183 |
: this.__eventListeners; |
| 184 |
let eventListeners = eventListenersMap.get(type); |
| 185 |
if (eventListeners === undefined) { |
| 186 |
eventListeners = new Map(); |
| 187 |
eventListenersMap.set(type, eventListeners); |
| 188 |
} else if (eventListeners.has(callback)) { |
| 189 |
return; |
| 190 |
} |
| 191 |
|
| 192 |
const normalizedOptions = |
| 193 |
typeof options === 'object' && options ? options : {}; |
| 194 |
normalizedOptions.signal?.addEventListener('abort', () => |
| 195 |
this.removeEventListener(type, callback, options) |
| 196 |
); |
| 197 |
eventListeners.set(callback, normalizedOptions ?? {}); |
| 198 |
} |
| 199 |
removeEventListener( |
| 200 |
type: string, |
| 201 |
callback: EventListenerOrEventListenerObject | null, |
| 202 |
options?: EventListenerOptions | boolean |
| 203 |
): void { |
| 204 |
if (callback === undefined || callback === null) { |
| 205 |
return; |
| 206 |
} |
| 207 |
const eventListenersMap = isCaptureEventListener(options) |
| 208 |
? this.__captureEventListeners |
| 209 |
: this.__eventListeners; |
| 210 |
const eventListeners = eventListenersMap.get(type); |
| 211 |
if (eventListeners !== undefined) { |
| 212 |
eventListeners.delete(callback); |
| 213 |
if (!eventListeners.size) { |
| 214 |
eventListenersMap.delete(type); |
| 215 |
} |
| 216 |
} |
| 217 |
} |
| 218 |
dispatchEvent(event: Event): boolean { |
| 219 |
let composedPath = this.__resolveFullEventPath(); |
| 220 |
if (!event.composed && this.__host) { |
| 221 |
// If the event is not composed and the event was dispatched inside |
| 222 |
// shadow DOM, we need to stop the event chain before the host of the |
| 223 |
// shadow DOM. |
| 224 |
composedPath = composedPath.slice(0, composedPath.indexOf(this.__host)); |
| 225 |
} |
| 226 |
|
| 227 |
// We need to patch various properties that would either be empty or wrong |
| 228 |
// in this scenario. |
| 229 |
let stopPropagation = false; |
| 230 |
let stopImmediatePropagation = false; |
| 231 |
let eventPhase: number = EventShim.NONE; |
| 232 |
let target: EventTarget | null = null; |
| 233 |
let tmpTarget: EventTarget | null = null; |
| 234 |
let currentTarget: EventTarget | null = null; |
| 235 |
const originalStopPropagation = event.stopPropagation; |
| 236 |
const originalStopImmediatePropagation = event.stopImmediatePropagation; |
| 237 |
Object.defineProperties(event, { |
| 238 |
target: { |
| 239 |
get() { |
| 240 |
return target ?? tmpTarget; |
| 241 |
}, |
| 242 |
...enumerableProperty, |
| 243 |
}, |
| 244 |
srcElement: { |
| 245 |
get() { |
| 246 |
return event.target; |
| 247 |
}, |
| 248 |
...enumerableProperty, |
| 249 |
}, |
| 250 |
currentTarget: { |
| 251 |
get() { |
| 252 |
return currentTarget; |
| 253 |
}, |
| 254 |
...enumerableProperty, |
| 255 |
}, |
| 256 |
eventPhase: { |
| 257 |
get() { |
| 258 |
return eventPhase; |
| 259 |
}, |
| 260 |
...enumerableProperty, |
| 261 |
}, |
| 262 |
composedPath: { |
| 263 |
value: () => composedPath, |
| 264 |
...enumerableProperty, |
| 265 |
}, |
| 266 |
stopPropagation: { |
| 267 |
value: () => { |
| 268 |
stopPropagation = true; |
| 269 |
originalStopPropagation.call(event); |
| 270 |
}, |
| 271 |
...enumerableProperty, |
| 272 |
}, |
| 273 |
stopImmediatePropagation: { |
| 274 |
value: () => { |
| 275 |
stopImmediatePropagation = true; |
| 276 |
originalStopImmediatePropagation.call(event); |
| 277 |
}, |
| 278 |
...enumerableProperty, |
| 279 |
}, |
| 280 |
}); |
| 281 |
|
| 282 |
// An event handler can either be a function, an object with a handleEvent |
| 283 |
// method or null. This function takes care to call the event handler |
| 284 |
// correctly. |
| 285 |
const invokeEventListener = ( |
| 286 |
listener: EventListenerOrEventListenerObject, |
| 287 |
options: AddEventListenerOptions, |
| 288 |
eventListenerMap: Map< |
| 289 |
EventListenerOrEventListenerObject, |
| 290 |
AddEventListenerOptions |
| 291 |
> |
| 292 |
) => { |
| 293 |
if (typeof listener === 'function') { |
| 294 |
listener(event); |
| 295 |
} else if (typeof listener?.handleEvent === 'function') { |
| 296 |
listener.handleEvent(event); |
| 297 |
} |
| 298 |
if (options.once) { |
| 299 |
eventListenerMap.delete(listener); |
| 300 |
} |
| 301 |
}; |
| 302 |
// When an event is finished being dispatched, which can be after the event |
| 303 |
// tree has been traversed or stopPropagation/stopImmediatePropagation has |
| 304 |
// been called. Once that is the case, the currentTarget and eventPhase |
| 305 |
// need to be reset and a value, representing whether the event has not |
| 306 |
// been prevented, needs to be returned. |
| 307 |
const finishDispatch = () => { |
| 308 |
currentTarget = null; |
| 309 |
eventPhase = EventShim.NONE; |
| 310 |
return !event.defaultPrevented; |
| 311 |
}; |
| 312 |
|
| 313 |
// An event starts with the capture order, where it starts from the top. |
| 314 |
// This is done even if bubbles is set to false, which is the default. |
| 315 |
const captureEventPath = composedPath.slice().reverse(); |
| 316 |
// If the event target, which dispatches the event, is either in the light DOM |
| 317 |
// or the event is not composed, the target is always itself. If that is not |
| 318 |
// the case, the target needs to be retargeted: https://dom.spec.whatwg.org/#retarget |
| 319 |
target = !this.__host || !event.composed ? this : null; |
| 320 |
const retarget = (eventTargets: EventTarget[]) => { |
| 321 |
// eslint-disable-next-line @typescript-eslint/no-this-alias |
| 322 |
tmpTarget = this; |
| 323 |
while (tmpTarget.__host && eventTargets.includes(tmpTarget.__host)) { |
| 324 |
tmpTarget = tmpTarget.__host; |
| 325 |
} |
| 326 |
}; |
| 327 |
for (const eventTarget of captureEventPath) { |
| 328 |
if (!target && (!tmpTarget || tmpTarget === eventTarget.__host)) { |
| 329 |
retarget(captureEventPath.slice(captureEventPath.indexOf(eventTarget))); |
| 330 |
} |
| 331 |
currentTarget = eventTarget; |
| 332 |
eventPhase = |
| 333 |
eventTarget === event.target |
| 334 |
? EventShim.AT_TARGET |
| 335 |
: EventShim.CAPTURING_PHASE; |
| 336 |
const captureEventListeners = eventTarget.__captureEventListeners.get( |
| 337 |
event.type |
| 338 |
); |
| 339 |
if (captureEventListeners) { |
| 340 |
for (const [listener, options] of captureEventListeners) { |
| 341 |
invokeEventListener(listener, options, captureEventListeners); |
| 342 |
if (stopImmediatePropagation) { |
| 343 |
// Event.stopImmediatePropagation() stops any following invocation |
| 344 |
// of an event handler even on the same event target. |
| 345 |
return finishDispatch(); |
| 346 |
} |
| 347 |
} |
| 348 |
} |
| 349 |
if (stopPropagation) { |
| 350 |
// Event.stopPropagation() stops any following invocation |
| 351 |
// of an event handler for any following event targets. |
| 352 |
return finishDispatch(); |
| 353 |
} |
| 354 |
} |
| 355 |
|
| 356 |
const bubbleEventPath = event.bubbles ? composedPath : [this]; |
| 357 |
tmpTarget = null; |
| 358 |
for (const eventTarget of bubbleEventPath) { |
| 359 |
if ( |
| 360 |
!target && |
| 361 |
(!tmpTarget || eventTarget === (tmpTarget as EventTarget).__host) |
| 362 |
) { |
| 363 |
retarget( |
| 364 |
bubbleEventPath.slice(0, bubbleEventPath.indexOf(eventTarget) + 1) |
| 365 |
); |
| 366 |
} |
| 367 |
currentTarget = eventTarget; |
| 368 |
eventPhase = |
| 369 |
eventTarget === event.target |
| 370 |
? EventShim.AT_TARGET |
| 371 |
: EventShim.BUBBLING_PHASE; |
| 372 |
const eventListeners = eventTarget.__eventListeners.get(event.type); |
| 373 |
if (eventListeners) { |
| 374 |
for (const [listener, options] of eventListeners) { |
| 375 |
invokeEventListener(listener, options, eventListeners); |
| 376 |
if (stopImmediatePropagation) { |
| 377 |
// Event.stopImmediatePropagation() stops any following invocation |
| 378 |
// of an event handler even on the same event target. |
| 379 |
return finishDispatch(); |
| 380 |
} |
| 381 |
} |
| 382 |
} |
| 383 |
if (stopPropagation) { |
| 384 |
// Event.stopPropagation() stops any following invocation |
| 385 |
// of an event handler for any following event targets. |
| 386 |
return finishDispatch(); |
| 387 |
} |
| 388 |
} |
| 389 |
return finishDispatch(); |
| 390 |
} |
| 391 |
private __resolveFullEventPath(): EventTarget[] { |
| 392 |
if (this.__eventPathCache) { |
| 393 |
return this.__eventPathCache; |
| 394 |
} else if (!this.__eventTargetParent) { |
| 395 |
return (this.__eventPathCache = [this, documentShim, windowShim]); |
| 396 |
} else { |
| 397 |
return (this.__eventPathCache = [ |
| 398 |
this, |
| 399 |
...this.__eventTargetParent.__resolveFullEventPath(), |
| 400 |
]); |
| 401 |
} |
| 402 |
} |
| 403 |
} |
| 404 |
|
| 405 |
const EventTargetShimWithRealType = |
| 406 |
EventTarget as object as typeof globalThis.EventTarget; |
| 407 |
export {EventTargetShimWithRealType as EventTarget}; |
| 408 |
|
| 409 |
const attributes = new WeakMap< |
| 410 |
InstanceType<typeof HTMLElementShim>, |
| 411 |
Map<string, string> |
| 412 |
>(); |
| 413 |
const attributesForElement = ( |
| 414 |
element: InstanceType<typeof HTMLElementShim> |
| 415 |
) => { |
| 416 |
let attrs = attributes.get(element); |
| 417 |
if (attrs === undefined) { |
| 418 |
attributes.set(element, (attrs = new Map())); |
| 419 |
} |
| 420 |
return attrs; |
| 421 |
}; |
| 422 |
|
| 423 |
// The typings around the exports below are a little funky: |
| 424 |
// |
| 425 |
// 1. We want the `name` of the shim classes to match the real ones at runtime, |
| 426 |
// hence e.g. `class Element`. |
| 427 |
// 2. We can't shadow the global types with a simple class declaration, because |
| 428 |
// then we can't reference the global types for casting, hence e.g. |
| 429 |
// `const ElementShim = class Element`. |
| 430 |
// 3. We want to export the classes typed as the real ones, hence e.g. |
| 431 |
// `const ElementShimWithRealType = ElementShim as object as typeof Element;`. |
| 432 |
// 4. We want the exported names to match the real ones, hence e.g. |
| 433 |
// `export {ElementShimWithRealType as Element}`. |
| 434 |
const NodeShim = class Node extends EventTarget { |
| 435 |
getRootNode(options?: GetRootNodeOptions): globalThis.Node { |
| 436 |
if (options?.composed) { |
| 437 |
return document; |
| 438 |
} |
| 439 |
// getRootNode returns the containing ShadowRoot instance, even if that was |
| 440 |
// created in closed mode. |
| 441 |
const host = (this as Partial<EventTargetShimMeta>).__host as |
| 442 |
| typeof ElementShim |
| 443 |
| undefined; |
| 444 |
return ( |
| 445 |
(host as {__shadowRoot?: null | ShadowRoot})?.__shadowRoot ?? document |
| 446 |
); |
| 447 |
} |
| 448 |
}; |
| 449 |
const NodeShimWithRealType = NodeShim as object as typeof Node; |
| 450 |
export {NodeShimWithRealType as Node}; |
| 451 |
|
| 452 |
type DocumentInterface = Document; |
| 453 |
|
| 454 |
const DocumentShim = class Document |
| 455 |
extends NodeShim |
| 456 |
implements Partial<DocumentInterface> |
| 457 |
{ |
| 458 |
get adoptedStyleSheets() { |
| 459 |
return []; |
| 460 |
} |
| 461 |
createTreeWalker() { |
| 462 |
return {} as TreeWalker; |
| 463 |
} |
| 464 |
createTextNode() { |
| 465 |
return {} as Text; |
| 466 |
} |
| 467 |
createElement() { |
| 468 |
return {} as HTMLElement; |
| 469 |
} |
| 470 |
}; |
| 471 |
const DocumentShimWithRealType = DocumentShim as object as typeof Document; |
| 472 |
export {DocumentShimWithRealType as Document}; |
| 473 |
|
| 474 |
const documentShim = new DocumentShim(); |
| 475 |
const document: Document = documentShim as object as typeof document; |
| 476 |
export {document}; |
| 477 |
|
| 478 |
type WindowInterface = Window; |
| 479 |
|
| 480 |
const WindowShim = class Window |
| 481 |
extends NodeShim |
| 482 |
implements Partial<WindowInterface> |
| 483 |
{ |
| 484 |
[index: number]: WindowInterface; |
| 485 |
|
| 486 |
constructor(); |
| 487 |
/** |
| 488 |
* @internal |
| 489 |
*/ |
| 490 |
constructor(constructionToken: Symbol); |
| 491 |
constructor(token?: Symbol) { |
| 492 |
super(); |
| 493 |
if (token !== constructionToken) { |
| 494 |
throw new TypeError('Illegal constructor'); |
| 495 |
} |
| 496 |
|
| 497 |
Object.assign(this, globalThis, { |
| 498 |
CustomElementRegistry, |
| 499 |
customElements, |
| 500 |
document, |
| 501 |
Document: DocumentShim, |
| 502 |
Element: ElementShim, |
| 503 |
EventTarget, |
| 504 |
HTMLElement: HTMLElementShim, |
| 505 |
Node: NodeShim, |
| 506 |
ShadowRoot: ShadowRootShim, |
| 507 |
window: this, |
| 508 |
Window: WindowShim, |
| 509 |
}); |
| 510 |
} |
| 511 |
}; |
| 512 |
const WindowShimWithRealType = WindowShim as object as typeof Window; |
| 513 |
export {WindowShimWithRealType as Window}; |
| 514 |
|
| 515 |
const ElementShim = class Element extends NodeShim { |
| 516 |
get attributes() { |
| 517 |
return Array.from(attributesForElement(this)).map(([name, value]) => ({ |
| 518 |
name, |
| 519 |
value, |
| 520 |
})); |
| 521 |
} |
| 522 |
private __shadowRootMode: null | ShadowRootMode = null; |
| 523 |
protected __shadowRoot: null | ShadowRoot = null; |
| 524 |
protected __internals: null | ElementInternals = null; |
| 525 |
|
| 526 |
get shadowRoot() { |
| 527 |
if (this.__shadowRootMode === 'closed') { |
| 528 |
return null; |
| 529 |
} |
| 530 |
return this.__shadowRoot; |
| 531 |
} |
| 532 |
get localName() { |
| 533 |
return (this.constructor as NamedCustomHTMLElementConstructor).__localName; |
| 534 |
} |
| 535 |
get tagName() { |
| 536 |
return this.localName?.toUpperCase(); |
| 537 |
} |
| 538 |
setAttribute(name: string, value: unknown): void { |
| 539 |
// Emulate browser behavior that silently casts all values to string. E.g. |
| 540 |
// `42` becomes `"42"` and `{}` becomes `"[object Object]""`. |
| 541 |
attributesForElement(this).set(name, String(value)); |
| 542 |
} |
| 543 |
removeAttribute(name: string) { |
| 544 |
attributesForElement(this).delete(name); |
| 545 |
} |
| 546 |
toggleAttribute(name: string, force?: boolean): boolean { |
| 547 |
// Steps reference https://dom.spec.whatwg.org/#dom-element-toggleattribute |
| 548 |
if (this.hasAttribute(name)) { |
| 549 |
// Step 5 |
| 550 |
if (force === undefined || !force) { |
| 551 |
this.removeAttribute(name); |
| 552 |
return false; |
| 553 |
} |
| 554 |
} else { |
| 555 |
// Step 4 |
| 556 |
if (force === undefined || force) { |
| 557 |
// Step 4.1 |
| 558 |
this.setAttribute(name, ''); |
| 559 |
return true; |
| 560 |
} else { |
| 561 |
// Step 4.2 |
| 562 |
return false; |
| 563 |
} |
| 564 |
} |
| 565 |
// Step 6 |
| 566 |
return true; |
| 567 |
} |
| 568 |
hasAttribute(name: string) { |
| 569 |
return attributesForElement(this).has(name); |
| 570 |
} |
| 571 |
attachShadow(init: ShadowRootInit): ShadowRoot { |
| 572 |
this.__shadowRootMode = init.mode; |
| 573 |
const shadowRoot: Partial<ShadowRootInterface> & EventTargetShimMeta = |
| 574 |
new ShadowRootShim(constructionToken, init); |
| 575 |
shadowRoot.__eventTargetParent = this; |
| 576 |
shadowRoot.__host = this; |
| 577 |
return (this.__shadowRoot = shadowRoot as ShadowRootInterface); |
| 578 |
} |
| 579 |
attachInternals(): ElementInternals { |
| 580 |
if (this.__internals !== null) { |
| 581 |
throw new Error( |
| 582 |
`Failed to execute 'attachInternals' on 'HTMLElement': ` + |
| 583 |
`ElementInternals for the specified element was already attached.` |
| 584 |
); |
| 585 |
} |
| 586 |
const internals = new ElementInternalsShim(this as unknown as HTMLElement); |
| 587 |
this.__internals = internals; |
| 588 |
return internals as ElementInternals; |
| 589 |
} |
| 590 |
getAttribute(name: string) { |
| 591 |
const value = attributesForElement(this).get(name); |
| 592 |
return value ?? null; |
| 593 |
} |
| 594 |
}; |
| 595 |
const ElementShimWithRealType = ElementShim as object as typeof Element; |
| 596 |
export {ElementShimWithRealType as Element}; |
| 597 |
|
| 598 |
const HTMLElementShim = class HTMLElement extends ElementShim {}; |
| 599 |
const HTMLElementShimWithRealType = |
| 600 |
HTMLElementShim as object as typeof HTMLElement; |
| 601 |
export {HTMLElementShimWithRealType as HTMLElement}; |
| 602 |
|
| 603 |
const HTMLSlotElementShim = class HTMLSlotElement extends HTMLElementShim { |
| 604 |
name!: string; |
| 605 |
override get localName(): string { |
| 606 |
return 'slot'; |
| 607 |
} |
| 608 |
}; |
| 609 |
const HTMLSlotElementShimWithRealType = |
| 610 |
HTMLSlotElementShim as object as typeof HTMLSlotElement; |
| 611 |
export {HTMLSlotElementShimWithRealType as HTMLSlotElement}; |
| 612 |
|
| 613 |
type ShadowRootInterface = ShadowRoot; |
| 614 |
|
| 615 |
const ShadowRootShim = class ShadowRoot |
| 616 |
extends NodeShim |
| 617 |
implements Partial<ShadowRootInterface> |
| 618 |
{ |
| 619 |
get host(): Element { |
| 620 |
return (this as Partial<EventTargetShimMeta>).__host! as Element; |
| 621 |
} |
| 622 |
mode: 'open' | 'closed'; |
| 623 |
|
| 624 |
constructor(); |
| 625 |
/** |
| 626 |
* @internal |
| 627 |
*/ |
| 628 |
constructor(constructionToken: Symbol, init: ShadowRootInit); |
| 629 |
constructor(constructionToken?: Symbol, init?: ShadowRootInit) { |
| 630 |
super(); |
| 631 |
if (constructionToken !== constructionToken) { |
| 632 |
throw new TypeError('Illegal constructor'); |
| 633 |
} |
| 634 |
this.mode = init!.mode; |
| 635 |
} |
| 636 |
}; |
| 637 |
const ShadowRootShimWithRealType = |
| 638 |
ShadowRootShim as object as typeof ShadowRoot; |
| 639 |
export {ShadowRootShimWithRealType as ShadowRoot}; |
| 640 |
|
| 641 |
// For convenience, we provide a global instance of a HTMLElement as an event |
| 642 |
// target. This facilitates registering global event handlers |
| 643 |
// (e.g. for @lit/context ContextProvider). |
| 644 |
// We use this in in the SSR render function. |
| 645 |
// Note, this is a bespoke element and not simply `document` or `window` since |
| 646 |
// user code relies on these being undefined in the server environment. |
| 647 |
globalThis.litServerRoot ??= Object.defineProperty( |
| 648 |
new HTMLElementShimWithRealType(), |
| 649 |
'localName', |
| 650 |
{ |
| 651 |
// Patch localName (and tagName) to return a unique name. |
| 652 |
get() { |
| 653 |
return 'lit-server-root'; |
| 654 |
}, |
| 655 |
} |
| 656 |
); |
| 657 |
|
| 658 |
interface CustomHTMLElementConstructor { |
| 659 |
new (): HTMLElement; |
| 660 |
observedAttributes?: string[]; |
| 661 |
} |
| 662 |
|
| 663 |
interface NamedCustomHTMLElementConstructor |
| 664 |
extends CustomHTMLElementConstructor { |
| 665 |
__localName: string; |
| 666 |
} |
| 667 |
|
| 668 |
type CustomElementRegistration = { |
| 669 |
ctor: {new (): HTMLElement}; |
| 670 |
observedAttributes: string[]; |
| 671 |
}; |
| 672 |
|
| 673 |
type RealCustomElementRegistry = (typeof globalThis)['customElements']; |
| 674 |
type RealCustomElementRegistryClass = |
| 675 |
(typeof globalThis)['CustomElementRegistry']; |
| 676 |
|
| 677 |
// Ponyfill for PromiseWithResolvers, remove once we can assume its presence. |
| 678 |
type PromiseWithResolvers<T> = { |
| 679 |
promise: Promise<T>; |
| 680 |
resolve: (value: T) => void; |
| 681 |
reject: (reason?: unknown) => void; |
| 682 |
}; |
| 683 |
function promiseWithResolvers<T>(): PromiseWithResolvers<T> { |
| 684 |
let resolve: (value: T) => void; |
| 685 |
let reject: (reason?: unknown) => void; |
| 686 |
const promise = new Promise<T>((res, rej) => { |
| 687 |
resolve = res; |
| 688 |
reject = rej; |
| 689 |
}); |
| 690 |
return {promise, resolve: resolve!, reject: reject!}; |
| 691 |
} |
| 692 |
|
| 693 |
class CustomElementRegistry implements RealCustomElementRegistry { |
| 694 |
private __definitions = new Map<string, CustomElementRegistration>(); |
| 695 |
private __reverseDefinitions = new Map< |
| 696 |
CustomHTMLElementConstructor, |
| 697 |
string |
| 698 |
>(); |
| 699 |
private __pendingWhenDefineds = new Map< |
| 700 |
string, |
| 701 |
PromiseWithResolvers<CustomElementConstructor> |
| 702 |
>(); |
| 703 |
|
| 704 |
define(name: string, ctor: CustomHTMLElementConstructor) { |
| 705 |
if (this.__definitions.has(name)) { |
| 706 |
if (process.env.NODE_ENV === 'development') { |
| 707 |
console.warn( |
| 708 |
`'CustomElementRegistry' already has "${name}" defined. ` + |
| 709 |
`This may have been caused by live reload or hot module ` + |
| 710 |
`replacement in which case it can be safely ignored.\n` + |
| 711 |
`Make sure to test your application with a production build as ` + |
| 712 |
`repeat registrations will throw in production.` |
| 713 |
); |
| 714 |
} else { |
| 715 |
throw new Error( |
| 716 |
`Failed to execute 'define' on 'CustomElementRegistry': ` + |
| 717 |
`the name "${name}" has already been used with this registry` |
| 718 |
); |
| 719 |
} |
| 720 |
} |
| 721 |
if (this.__reverseDefinitions.has(ctor)) { |
| 722 |
throw new Error( |
| 723 |
`Failed to execute 'define' on 'CustomElementRegistry': ` + |
| 724 |
`the constructor has already been used with this registry for the ` + |
| 725 |
`tag name ${this.__reverseDefinitions.get(ctor)}` |
| 726 |
); |
| 727 |
} |
| 728 |
// Provide tagName and localName for the component. |
| 729 |
(ctor as NamedCustomHTMLElementConstructor).__localName = name; |
| 730 |
this.__definitions.set(name, { |
| 731 |
ctor, |
| 732 |
// Note it's important we read `observedAttributes` in case it is a getter |
| 733 |
// with side-effects, as is the case in Lit, where it triggers class |
| 734 |
// finalization. |
| 735 |
// |
| 736 |
// TODO(aomarks) To be spec compliant, we should also capture the |
| 737 |
// registration-time lifecycle methods like `connectedCallback`. For them |
| 738 |
// to be actually accessible to e.g. the Lit SSR element renderer, though, |
| 739 |
// we'd need to introduce a new API for accessing them (since `get` only |
| 740 |
// returns the constructor). |
| 741 |
observedAttributes: ctor.observedAttributes ?? [], |
| 742 |
}); |
| 743 |
this.__reverseDefinitions.set(ctor, name); |
| 744 |
this.__pendingWhenDefineds.get(name)?.resolve(ctor); |
| 745 |
this.__pendingWhenDefineds.delete(name); |
| 746 |
} |
| 747 |
|
| 748 |
get(name: string) { |
| 749 |
const definition = this.__definitions.get(name); |
| 750 |
return definition?.ctor; |
| 751 |
} |
| 752 |
|
| 753 |
getName(ctor: CustomHTMLElementConstructor) { |
| 754 |
return this.__reverseDefinitions.get(ctor) ?? null; |
| 755 |
} |
| 756 |
|
| 757 |
initialize(_root: Node): void { |
| 758 |
throw new Error( |
| 759 |
`customElements.initialize is not currently supported in SSR. ` + |
| 760 |
`Please file a bug if you need it.` |
| 761 |
); |
| 762 |
} |
| 763 |
|
| 764 |
upgrade(_element: HTMLElement) { |
| 765 |
// In SSR this doesn't make a lot of sense, so we do nothing. |
| 766 |
throw new Error( |
| 767 |
`customElements.upgrade is not currently supported in SSR. ` + |
| 768 |
`Please file a bug if you need it.` |
| 769 |
); |
| 770 |
} |
| 771 |
|
| 772 |
async whenDefined(name: string): Promise<CustomElementConstructor> { |
| 773 |
const definition = this.__definitions.get(name); |
| 774 |
if (definition) { |
| 775 |
return definition.ctor; |
| 776 |
} |
| 777 |
let withResolvers = this.__pendingWhenDefineds.get(name); |
| 778 |
if (!withResolvers) { |
| 779 |
withResolvers = promiseWithResolvers<CustomElementConstructor>(); |
| 780 |
this.__pendingWhenDefineds.set(name, withResolvers); |
| 781 |
} |
| 782 |
return withResolvers.promise; |
| 783 |
} |
| 784 |
} |
| 785 |
|
| 786 |
const CustomElementRegistryShimWithRealType = |
| 787 |
CustomElementRegistry as object as RealCustomElementRegistryClass; |
| 788 |
export {CustomElementRegistryShimWithRealType as CustomElementRegistry}; |
| 789 |
|
| 790 |
export const customElements = new CustomElementRegistryShimWithRealType(); |
| 791 |
|
| 792 |
// The window variable instantiation must happen after all shims |
| 793 |
// have been declared, as they will be included in the window instance. |
| 794 |
const windowShim = new WindowShim(constructionToken); |
| 795 |
const window: Window = windowShim as object as typeof window; |
| 796 |
export {window}; |