@augment-vir/web 30.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/LICENSE-CC0 +121 -0
  2. package/LICENSE-MIT +21 -0
  3. package/dist/augments/animation-frame.d.ts +1 -0
  4. package/dist/augments/animation-frame.js +17 -0
  5. package/dist/augments/elements/element-children.d.ts +19 -0
  6. package/dist/augments/elements/element-children.js +39 -0
  7. package/dist/augments/elements/element-focus.d.ts +1 -0
  8. package/dist/augments/elements/element-focus.js +3 -0
  9. package/dist/augments/elements/element-parent.d.ts +2 -0
  10. package/dist/augments/elements/element-parent.js +25 -0
  11. package/dist/augments/elements/element-position.d.ts +5 -0
  12. package/dist/augments/elements/element-position.js +34 -0
  13. package/dist/augments/elements/element-text.d.ts +1 -0
  14. package/dist/augments/elements/element-text.js +17 -0
  15. package/dist/augments/elements/element-visibility.d.ts +2 -0
  16. package/dist/augments/elements/element-visibility.js +5 -0
  17. package/dist/augments/elements/overflow-parent.d.ts +1 -0
  18. package/dist/augments/elements/overflow-parent.js +9 -0
  19. package/dist/augments/elements/tag-or-definition.d.ts +8 -0
  20. package/dist/augments/elements/tag-or-definition.js +15 -0
  21. package/dist/augments/elements/text-dimensions.d.ts +8 -0
  22. package/dist/augments/elements/text-dimensions.js +59 -0
  23. package/dist/augments/event-target.d.ts +11 -0
  24. package/dist/augments/event-target.js +12 -0
  25. package/dist/augments/image.d.ts +1 -0
  26. package/dist/augments/image.js +13 -0
  27. package/dist/augments/query-through-shadow.d.ts +17 -0
  28. package/dist/augments/query-through-shadow.js +79 -0
  29. package/dist/augments/video.d.ts +1 -0
  30. package/dist/augments/video.js +14 -0
  31. package/dist/index.d.ts +14 -0
  32. package/dist/index.js +14 -0
  33. package/package.json +49 -0
  34. package/video.mock.webm +0 -0
package/LICENSE-CC0 ADDED
@@ -0,0 +1,121 @@
1
+ CC0 1.0 Universal
2
+
3
+ Creative Commons Legal Code
4
+
5
+ CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
6
+ LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
7
+ ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
8
+ INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
9
+ REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
10
+ PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
11
+ THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
12
+ HEREUNDER.
13
+
14
+ Statement of Purpose
15
+
16
+ The laws of most jurisdictions throughout the world automatically confer
17
+ exclusive Copyright and Related Rights (defined below) upon the creator
18
+ and subsequent owner(s) (each and all, an "owner") of an original work of
19
+ authorship and/or a database (each, a "Work").
20
+
21
+ Certain owners wish to permanently relinquish those rights to a Work for
22
+ the purpose of contributing to a commons of creative, cultural and
23
+ scientific works ("Commons") that the public can reliably and without fear
24
+ of later claims of infringement build upon, modify, incorporate in other
25
+ works, reuse and redistribute as freely as possible in any form whatsoever
26
+ and for any purposes, including without limitation commercial purposes.
27
+ These owners may contribute to the Commons to promote the ideal of a free
28
+ culture and the further production of creative, cultural and scientific
29
+ works, or to gain reputation or greater distribution for their Work in
30
+ part through the use and efforts of others.
31
+
32
+ For these and/or other purposes and motivations, and without any
33
+ expectation of additional consideration or compensation, the person
34
+ associating CC0 with a Work (the "Affirmer"), to the extent that he or she
35
+ is an owner of Copyright and Related Rights in the Work, voluntarily
36
+ elects to apply CC0 to the Work and publicly distribute the Work under its
37
+ terms, with knowledge of his or her Copyright and Related Rights in the
38
+ Work and the meaning and intended legal effect of CC0 on those rights.
39
+
40
+ 1. Copyright and Related Rights. A Work made available under CC0 may be
41
+ protected by copyright and related or neighboring rights ("Copyright and
42
+ Related Rights"). Copyright and Related Rights include, but are not
43
+ limited to, the following:
44
+
45
+ i. the right to reproduce, adapt, distribute, perform, display,
46
+ communicate, and translate a Work;
47
+ ii. moral rights retained by the original author(s) and/or performer(s);
48
+ iii. publicity and privacy rights pertaining to a person's image or
49
+ likeness depicted in a Work;
50
+ iv. rights protecting against unfair competition in regards to a Work,
51
+ subject to the limitations in paragraph 4(a), below;
52
+ v. rights protecting the extraction, dissemination, use and reuse of data
53
+ in a Work;
54
+ vi. database rights (such as those arising under Directive 96/9/EC of the
55
+ European Parliament and of the Council of 11 March 1996 on the legal
56
+ protection of databases, and under any national implementation
57
+ thereof, including any amended or successor version of such
58
+ directive); and
59
+ vii. other similar, equivalent or corresponding rights throughout the
60
+ world based on applicable law or treaty, and any national
61
+ implementations thereof.
62
+
63
+ 2. Waiver. To the greatest extent permitted by, but not in contravention
64
+ of, applicable law, Affirmer hereby overtly, fully, permanently,
65
+ irrevocably and unconditionally waives, abandons, and surrenders all of
66
+ Affirmer's Copyright and Related Rights and associated claims and causes
67
+ of action, whether now known or unknown (including existing as well as
68
+ future claims and causes of action), in the Work (i) in all territories
69
+ worldwide, (ii) for the maximum duration provided by applicable law or
70
+ treaty (including future time extensions), (iii) in any current or future
71
+ medium and for any number of copies, and (iv) for any purpose whatsoever,
72
+ including without limitation commercial, advertising or promotional
73
+ purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
74
+ member of the public at large and to the detriment of Affirmer's heirs and
75
+ successors, fully intending that such Waiver shall not be subject to
76
+ revocation, rescission, cancellation, termination, or any other legal or
77
+ equitable action to disrupt the quiet enjoyment of the Work by the public
78
+ as contemplated by Affirmer's express Statement of Purpose.
79
+
80
+ 3. Public License Fallback. Should any part of the Waiver for any reason
81
+ be judged legally invalid or ineffective under applicable law, then the
82
+ Waiver shall be preserved to the maximum extent permitted taking into
83
+ account Affirmer's express Statement of Purpose. In addition, to the
84
+ extent the Waiver is so judged Affirmer hereby grants to each affected
85
+ person a royalty-free, non transferable, non sublicensable, non exclusive,
86
+ irrevocable and unconditional license to exercise Affirmer's Copyright and
87
+ Related Rights in the Work (i) in all territories worldwide, (ii) for the
88
+ maximum duration provided by applicable law or treaty (including future
89
+ time extensions), (iii) in any current or future medium and for any number
90
+ of copies, and (iv) for any purpose whatsoever, including without
91
+ limitation commercial, advertising or promotional purposes (the
92
+ "License"). The License shall be deemed effective as of the date CC0 was
93
+ applied by Affirmer to the Work. Should any part of the License for any
94
+ reason be judged legally invalid or ineffective under applicable law, such
95
+ partial invalidity or ineffectiveness shall not invalidate the remainder
96
+ of the License, and in such case Affirmer hereby affirms that he or she
97
+ will not (i) exercise any of his or her remaining Copyright and Related
98
+ Rights in the Work or (ii) assert any associated claims and causes of
99
+ action with respect to the Work, in either case contrary to Affirmer's
100
+ express Statement of Purpose.
101
+
102
+ 4. Limitations and Disclaimers.
103
+
104
+ a. No trademark or patent rights held by Affirmer are waived, abandoned,
105
+ surrendered, licensed or otherwise affected by this document.
106
+ b. Affirmer offers the Work as-is and makes no representations or
107
+ warranties of any kind concerning the Work, express, implied,
108
+ statutory or otherwise, including without limitation warranties of
109
+ title, merchantability, fitness for a particular purpose, non
110
+ infringement, or the absence of latent or other defects, accuracy, or
111
+ the present or absence of errors, whether or not discoverable, all to
112
+ the greatest extent permissible under applicable law.
113
+ c. Affirmer disclaims responsibility for clearing rights of other persons
114
+ that may apply to the Work or any use thereof, including without
115
+ limitation any person's Copyright and Related Rights in the Work.
116
+ Further, Affirmer disclaims responsibility for obtaining any necessary
117
+ consents, permissions or other rights required for any use of the
118
+ Work.
119
+ d. Affirmer understands and acknowledges that Creative Commons is not a
120
+ party to this document and has no duty or obligation with respect to
121
+ this CC0 or use of the Work.
package/LICENSE-MIT ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 electrovir
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ export declare function waitForAnimationFrame(frameCount?: number): Promise<void>;
@@ -0,0 +1,17 @@
1
+ import { DeferredPromise } from '@augment-vir/common';
2
+ export async function waitForAnimationFrame(frameCount = 1) {
3
+ const deferredPromise = new DeferredPromise();
4
+ function requestNextFrame() {
5
+ requestAnimationFrame(() => {
6
+ frameCount--;
7
+ if (frameCount) {
8
+ requestNextFrame();
9
+ }
10
+ else {
11
+ deferredPromise.resolve();
12
+ }
13
+ });
14
+ }
15
+ requestNextFrame();
16
+ return deferredPromise.promise;
17
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Gets all deeply nested elements contained within the given element. Shadow DOMs are traversed.
3
+ *
4
+ * Note that `<slot>` elements are included, as well as their nested elements (even if a slot filler
5
+ * is provided by the parent) and the slot filler itself (if provided).
6
+ *
7
+ * Optionally define a second "depth" input to control how far nestings should be pursued. Leave
8
+ * depth out or set it to undefined or any value <= 0 to allow full depth search.
9
+ */
10
+ export declare function getNestedChildren(startingElement: Readonly<Element>, depth?: number | undefined): Element[];
11
+ /**
12
+ * Gets an element's direct children. Includes slotted elements, direct `<slot>` children
13
+ * themselves, and all direct children of a shadow DOM. Default `<slot>` children are not included
14
+ * (since they're not "direct" children as they are nested under `<slot>`).
15
+ *
16
+ * Note that that slotted elements and light dom elements will always be shown above shadow dom
17
+ * elements. Besides that, the order of children is preserved.
18
+ */
19
+ export declare function getDirectChildren(startingElement: Readonly<Element>): Element[];
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Gets all deeply nested elements contained within the given element. Shadow DOMs are traversed.
3
+ *
4
+ * Note that `<slot>` elements are included, as well as their nested elements (even if a slot filler
5
+ * is provided by the parent) and the slot filler itself (if provided).
6
+ *
7
+ * Optionally define a second "depth" input to control how far nestings should be pursued. Leave
8
+ * depth out or set it to undefined or any value <= 0 to allow full depth search.
9
+ */
10
+ export function getNestedChildren(startingElement, depth) {
11
+ return recursivelyGetNestedChildren(startingElement, depth ?? 0, 0);
12
+ }
13
+ function recursivelyGetNestedChildren(startingElement, maxDepth, currentDepth) {
14
+ const children = getDirectChildren(startingElement);
15
+ return children.flatMap((child) => {
16
+ const nextDepth = currentDepth + 1;
17
+ const nested = maxDepth && nextDepth >= maxDepth
18
+ ? []
19
+ : recursivelyGetNestedChildren(child, maxDepth, nextDepth);
20
+ return [
21
+ child,
22
+ nested,
23
+ ].flat();
24
+ });
25
+ }
26
+ /**
27
+ * Gets an element's direct children. Includes slotted elements, direct `<slot>` children
28
+ * themselves, and all direct children of a shadow DOM. Default `<slot>` children are not included
29
+ * (since they're not "direct" children as they are nested under `<slot>`).
30
+ *
31
+ * Note that that slotted elements and light dom elements will always be shown above shadow dom
32
+ * elements. Besides that, the order of children is preserved.
33
+ */
34
+ export function getDirectChildren(startingElement) {
35
+ return [
36
+ ...startingElement.children,
37
+ ...(startingElement.shadowRoot?.children ?? []),
38
+ ];
39
+ }
@@ -0,0 +1 @@
1
+ export declare function isElementFocused(element: Element): boolean;
@@ -0,0 +1,3 @@
1
+ export function isElementFocused(element) {
2
+ return element.matches(':focus');
3
+ }
@@ -0,0 +1,2 @@
1
+ export declare function getParentElement(element: Node): Element | undefined;
2
+ export declare function findMatchingAncestor(start: Element, testParent: (parent: Element) => boolean): Element | undefined;
@@ -0,0 +1,25 @@
1
+ export function getParentElement(element) {
2
+ if (element instanceof ShadowRoot) {
3
+ return getParentElement(element.host);
4
+ }
5
+ const parentNode = element.parentNode;
6
+ if (!parentNode) {
7
+ return undefined;
8
+ }
9
+ else if (parentNode instanceof Element) {
10
+ return parentNode;
11
+ }
12
+ else {
13
+ return getParentElement(parentNode);
14
+ }
15
+ }
16
+ export function findMatchingAncestor(start, testParent) {
17
+ if (testParent(start)) {
18
+ return start;
19
+ }
20
+ const parent = getParentElement(start);
21
+ if (!parent) {
22
+ return undefined;
23
+ }
24
+ return findMatchingAncestor(parent, testParent);
25
+ }
@@ -0,0 +1,5 @@
1
+ import type { Coords } from '@augment-vir/common';
2
+ export declare function checkIfEntirelyInScrollView(element: Element): Promise<unknown>;
3
+ export declare function checkIfInScrollView(element: Element, ratio: number): Promise<unknown>;
4
+ export declare function getCenterOfElement(element: Element): Coords;
5
+ export declare function appendPositionDebugDiv(position: Coords): HTMLDivElement;
@@ -0,0 +1,34 @@
1
+ import { assert } from '@augment-vir/assert';
2
+ export async function checkIfEntirelyInScrollView(element) {
3
+ return checkIfInScrollView(element, 1);
4
+ }
5
+ export async function checkIfInScrollView(element, ratio) {
6
+ return new Promise((resolve) => {
7
+ const observer = new IntersectionObserver((entries, observerItself) => {
8
+ assert.isLengthAtLeast(entries, 1);
9
+ observerItself.disconnect();
10
+ resolve(entries[0].intersectionRatio >= ratio);
11
+ });
12
+ observer.observe(element);
13
+ });
14
+ }
15
+ export function getCenterOfElement(element) {
16
+ const rect = element.getBoundingClientRect();
17
+ return {
18
+ x: Math.floor((rect.left + rect.right) / 2),
19
+ y: Math.floor((rect.bottom + rect.top) / 2),
20
+ };
21
+ }
22
+ export function appendPositionDebugDiv(position) {
23
+ const div = document.createElement('div');
24
+ div.classList.add('debug');
25
+ div.style.backgroundColor = 'blue';
26
+ div.style.height = '10px';
27
+ div.style.left = `${position.x}px`;
28
+ div.style.position = 'absolute';
29
+ div.style.top = `${position.y}px`;
30
+ div.style.width = '10px';
31
+ div.style.zIndex = '9999';
32
+ document.body.append(div);
33
+ return div;
34
+ }
@@ -0,0 +1 @@
1
+ export declare function extractElementText(element: Element | ShadowRoot): string;
@@ -0,0 +1,17 @@
1
+ export function extractElementText(element) {
2
+ const value = element.value;
3
+ const shadowRoot = element.shadowRoot;
4
+ const textContent = element.textContent?.trim();
5
+ if (textContent) {
6
+ return textContent;
7
+ }
8
+ else if (shadowRoot) {
9
+ return extractElementText(shadowRoot);
10
+ }
11
+ else if (value) {
12
+ return value;
13
+ }
14
+ else {
15
+ return '';
16
+ }
17
+ }
@@ -0,0 +1,2 @@
1
+ /** Detects `display: none` and only works if the element does not have `position: fixed;`. */
2
+ export declare function isElementVisible(element: HTMLElement): boolean;
@@ -0,0 +1,5 @@
1
+ /** Detects `display: none` and only works if the element does not have `position: fixed;`. */
2
+ export function isElementVisible(element) {
3
+ // https://stackoverflow.com/a/21696585
4
+ return element.offsetParent !== null;
5
+ }
@@ -0,0 +1 @@
1
+ export declare function findOverflowParent(start: Element): Element;
@@ -0,0 +1,9 @@
1
+ import { findMatchingAncestor, getParentElement } from './element-parent.js';
2
+ export function findOverflowParent(start) {
3
+ const parentElement = getParentElement(start);
4
+ return ((parentElement &&
5
+ findMatchingAncestor(parentElement, (element) => {
6
+ return globalThis.getComputedStyle(element).overflowY !== 'visible';
7
+ })) ||
8
+ document.body);
9
+ }
@@ -0,0 +1,8 @@
1
+ import { DeclarativeElementDefinition } from 'element-vir';
2
+ import { SpecTagName } from 'html-spec-tags';
3
+ /**
4
+ * Reduce an element down to its tag name or its element definition if it's a custom element defined
5
+ * by element-vir. Note that the types for this won't work in your project if you use custom element
6
+ * tag names that aren't generated via element-vir.
7
+ */
8
+ export declare function toTagOrDefinition(element: Element): DeclarativeElementDefinition | SpecTagName;
@@ -0,0 +1,15 @@
1
+ import { DeclarativeElement } from 'element-vir';
2
+ import { ensureSpecTagName } from 'html-spec-tags';
3
+ /**
4
+ * Reduce an element down to its tag name or its element definition if it's a custom element defined
5
+ * by element-vir. Note that the types for this won't work in your project if you use custom element
6
+ * tag names that aren't generated via element-vir.
7
+ */
8
+ export function toTagOrDefinition(element) {
9
+ if (element instanceof DeclarativeElement) {
10
+ return element.definition;
11
+ }
12
+ else {
13
+ return ensureSpecTagName(element.tagName.toLowerCase());
14
+ }
15
+ }
@@ -0,0 +1,8 @@
1
+ import { Dimensions, type PartialWithUndefined } from '@augment-vir/common';
2
+ import type { AnyDuration } from '@date-vir/duration';
3
+ export declare function calculateTextDimensions(parentElement: Element, text: string, customOptions?: PartialWithUndefined<{
4
+ timeout: AnyDuration;
5
+ errorMessage: string;
6
+ /** Set to true to leave the text element in the DOM. */
7
+ debug: boolean;
8
+ }>): Promise<Dimensions>;
@@ -0,0 +1,59 @@
1
+ import { waitUntil } from '@augment-vir/assert';
2
+ export async function calculateTextDimensions(parentElement, text, customOptions) {
3
+ if (!text) {
4
+ return {
5
+ width: 0,
6
+ height: 0,
7
+ };
8
+ }
9
+ const textWrapperElement = document.createElement('span');
10
+ textWrapperElement.style.visibility = 'hidden';
11
+ textWrapperElement.style.position = 'absolute';
12
+ textWrapperElement.style.zIndex = '-9999';
13
+ textWrapperElement.style.opacity = '0';
14
+ textWrapperElement.style.pointerEvents = 'none';
15
+ textWrapperElement.style.userSelect = 'none';
16
+ // eslint-disable-next-line sonarjs/deprecation, @typescript-eslint/no-deprecated
17
+ textWrapperElement.style.webkitUserSelect = 'none';
18
+ textWrapperElement.style.animation = 'none';
19
+ textWrapperElement.style.transition = 'none';
20
+ textWrapperElement.setAttribute('aria-hidden', 'true');
21
+ /** Automatically account for shadow roots. */
22
+ const childAttachPoint = parentElement.shadowRoot || parentElement;
23
+ childAttachPoint.append(textWrapperElement);
24
+ let latestSize;
25
+ /**
26
+ * Use resize observer instead of clientWidth, getComputedStyle, or getBoundingClientRect to
27
+ * prevent a forced re-layout. See https://gist.github.com/paulirish/5d52fb081b3570c81e3a.
28
+ */
29
+ const resizeObserver = new ResizeObserver((entries) => {
30
+ latestSize = entries[0]?.contentRect;
31
+ });
32
+ resizeObserver.observe(textWrapperElement);
33
+ textWrapperElement.innerText = text;
34
+ try {
35
+ await waitUntil.isTruthy(() => !!latestSize, {
36
+ interval: { milliseconds: 0 },
37
+ timeout: customOptions?.timeout || { seconds: 10 },
38
+ }, customOptions?.errorMessage ||
39
+ `Failed to calculate text size in '${parentElement.tagName}'.`);
40
+ /**
41
+ * No way to intentionally trigger this edge case, we're just catching it here for type
42
+ * purposes
43
+ */
44
+ /* node:coverage ignore next 3 */
45
+ if (!latestSize) {
46
+ throw new Error('Failed to calculate text size.');
47
+ }
48
+ return {
49
+ height: latestSize.height,
50
+ width: latestSize.width,
51
+ };
52
+ }
53
+ finally {
54
+ if (!customOptions?.debug) {
55
+ textWrapperElement.remove();
56
+ }
57
+ resizeObserver.disconnect();
58
+ }
59
+ }
@@ -0,0 +1,11 @@
1
+ import { PartialWithUndefined } from '@augment-vir/common';
2
+ import { Constructor } from 'type-fest';
3
+ export declare function extractEventTarget<ExpectedTargetClassConstructor extends Constructor<Element>>(event: Event, expectedTargetClass: ExpectedTargetClassConstructor, options?: PartialWithUndefined<{
4
+ /**
5
+ * By default `extractEventTarget` uses the `Event.currentTarget` field to extract the event
6
+ * target so that it extract the target to which the event handler was attached to. However,
7
+ * if you wish to instead use the `Event.target` property, to extract the element which
8
+ * originally fired the event, set this to true.
9
+ */
10
+ useOriginalTarget: boolean;
11
+ }>): InstanceType<ExpectedTargetClassConstructor>;
@@ -0,0 +1,12 @@
1
+ export function extractEventTarget(event, expectedTargetClass, options = {}) {
2
+ const target = options.useOriginalTarget ? event.target : event.currentTarget;
3
+ if (!(target instanceof expectedTargetClass)) {
4
+ const expectedName = expectedTargetClass.name;
5
+ const actualName = target?.constructor.name;
6
+ const message = options.useOriginalTarget
7
+ ? `Current target from event '${event.type}' was not of type '${expectedName}'. Got '${actualName}'.`
8
+ : `Target from event '${event.type}' was not of type '${expectedName}'. Got '${actualName}'.`;
9
+ throw new Error(message);
10
+ }
11
+ return target;
12
+ }
@@ -0,0 +1 @@
1
+ export declare function loadImage(imageUrl: string): Promise<HTMLImageElement>;
@@ -0,0 +1,13 @@
1
+ import { DeferredPromise } from '@augment-vir/common';
2
+ export async function loadImage(imageUrl) {
3
+ const deferredPromise = new DeferredPromise();
4
+ const newImage = new Image();
5
+ newImage.onload = () => {
6
+ deferredPromise.resolve(newImage);
7
+ };
8
+ newImage.onerror = () => {
9
+ deferredPromise.reject(new Error(`Failed to load '${imageUrl}'`));
10
+ };
11
+ newImage.src = imageUrl;
12
+ return deferredPromise.promise;
13
+ }
@@ -0,0 +1,17 @@
1
+ import type { PartialWithUndefined } from '@augment-vir/common';
2
+ export type QueryThroughShadowOptions = PartialWithUndefined<{
3
+ all: boolean;
4
+ }>;
5
+ export declare function queryThroughShadow(element: Element | ShadowRoot, query: string | {
6
+ tagName: string;
7
+ }, options: {
8
+ all: true;
9
+ }): Element[];
10
+ export declare function queryThroughShadow(element: Element | ShadowRoot, query: string | {
11
+ tagName: string;
12
+ }, options: {
13
+ all?: false | undefined;
14
+ }): Element | undefined;
15
+ export declare function queryThroughShadow(element: Element | ShadowRoot, query: string | {
16
+ tagName: string;
17
+ }, options: QueryThroughShadowOptions): Element | Element[] | undefined;
@@ -0,0 +1,79 @@
1
+ import { check } from '@augment-vir/assert';
2
+ import { stringify } from '@augment-vir/core';
3
+ export function queryThroughShadow(element, rawQuery, options) {
4
+ if (!rawQuery) {
5
+ if (element instanceof Element) {
6
+ return element;
7
+ }
8
+ else {
9
+ return element.host;
10
+ }
11
+ }
12
+ const query = check.isString(rawQuery) ? rawQuery : rawQuery.tagName;
13
+ const splitQuery = query.split(' ').filter(check.isTruthy);
14
+ if (splitQuery.length > 1) {
15
+ return handleNestedQueries(element, query, options, splitQuery);
16
+ }
17
+ else if ('shadowRoot' in element && element.shadowRoot) {
18
+ return queryThroughShadow(element.shadowRoot, query, options);
19
+ }
20
+ const shadowRootChildren = getShadowRootChildren(element);
21
+ if (options.all) {
22
+ const outerResults = Array.from(element.querySelectorAll(query));
23
+ const nestedResults = shadowRootChildren.flatMap((shadowRootChild) => {
24
+ return queryThroughShadow(shadowRootChild, query, options);
25
+ });
26
+ return [
27
+ ...outerResults,
28
+ ...nestedResults,
29
+ ];
30
+ }
31
+ else {
32
+ const basicResult = element.querySelector(query);
33
+ if (basicResult) {
34
+ return basicResult;
35
+ }
36
+ else {
37
+ for (const shadowRootChild of shadowRootChildren) {
38
+ const nestedResult = queryThroughShadow(shadowRootChild, query, options);
39
+ if (nestedResult) {
40
+ return nestedResult;
41
+ }
42
+ }
43
+ return undefined;
44
+ }
45
+ }
46
+ }
47
+ function getShadowRootChildren(element) {
48
+ return Array.from(element.querySelectorAll('*'))
49
+ .filter((child) => !!child.shadowRoot)
50
+ .map((child) => child.shadowRoot);
51
+ }
52
+ function handleNestedQueries(element, originalQuery, options, queries) {
53
+ const firstQuery = queries[0];
54
+ /**
55
+ * No way to intentionally trigger this edge case, we're just catching it here for type
56
+ * purposes.
57
+ */
58
+ /* node:coverage ignore next 7 */
59
+ if (!firstQuery) {
60
+ throw new Error(`Somehow the first query was empty in '[${queries.join(',')}]' for query '${stringify(originalQuery)}'`);
61
+ }
62
+ const results = queryThroughShadow(element, firstQuery, options);
63
+ if (queries.length <= 1) {
64
+ return results;
65
+ }
66
+ if (check.isArray(results)) {
67
+ return results
68
+ .flatMap((result) => {
69
+ return handleNestedQueries(result, originalQuery, options, queries.slice(1));
70
+ })
71
+ .filter(check.isTruthy);
72
+ }
73
+ else if (results) {
74
+ return handleNestedQueries(results, originalQuery, options, queries.slice(1));
75
+ }
76
+ else {
77
+ return undefined;
78
+ }
79
+ }
@@ -0,0 +1 @@
1
+ export declare function loadVideo(videoUrl: string): Promise<HTMLVideoElement>;
@@ -0,0 +1,14 @@
1
+ import { DeferredPromise } from '@augment-vir/common';
2
+ export async function loadVideo(videoUrl) {
3
+ const deferredPromise = new DeferredPromise();
4
+ const videoElement = document.createElement('video');
5
+ videoElement.addEventListener('loadeddata', () => {
6
+ deferredPromise.resolve(videoElement);
7
+ });
8
+ videoElement.onerror = () => {
9
+ deferredPromise.reject(new Error(`Failed to load '${videoUrl}'`));
10
+ };
11
+ videoElement.src = videoUrl;
12
+ videoElement.load();
13
+ return deferredPromise.promise;
14
+ }
@@ -0,0 +1,14 @@
1
+ export * from './augments/animation-frame.js';
2
+ export * from './augments/elements/element-children.js';
3
+ export * from './augments/elements/element-focus.js';
4
+ export * from './augments/elements/element-parent.js';
5
+ export * from './augments/elements/element-position.js';
6
+ export * from './augments/elements/element-text.js';
7
+ export * from './augments/elements/element-visibility.js';
8
+ export * from './augments/elements/overflow-parent.js';
9
+ export * from './augments/elements/tag-or-definition.js';
10
+ export * from './augments/elements/text-dimensions.js';
11
+ export * from './augments/event-target.js';
12
+ export * from './augments/image.js';
13
+ export * from './augments/query-through-shadow.js';
14
+ export * from './augments/video.js';
package/dist/index.js ADDED
@@ -0,0 +1,14 @@
1
+ export * from './augments/animation-frame.js';
2
+ export * from './augments/elements/element-children.js';
3
+ export * from './augments/elements/element-focus.js';
4
+ export * from './augments/elements/element-parent.js';
5
+ export * from './augments/elements/element-position.js';
6
+ export * from './augments/elements/element-text.js';
7
+ export * from './augments/elements/element-visibility.js';
8
+ export * from './augments/elements/overflow-parent.js';
9
+ export * from './augments/elements/tag-or-definition.js';
10
+ export * from './augments/elements/text-dimensions.js';
11
+ export * from './augments/event-target.js';
12
+ export * from './augments/image.js';
13
+ export * from './augments/query-through-shadow.js';
14
+ export * from './augments/video.js';
package/package.json ADDED
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "@augment-vir/web",
3
+ "version": "30.0.0",
4
+ "homepage": "https://github.com/electrovir/augment-vir",
5
+ "bugs": {
6
+ "url": "https://github.com/electrovir/augment-vir/issues"
7
+ },
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/electrovir/augment-vir.git"
11
+ },
12
+ "license": "(MIT or CC0 1.0)",
13
+ "author": {
14
+ "name": "electrovir",
15
+ "url": "https://github.com/electrovir"
16
+ },
17
+ "type": "module",
18
+ "main": "dist/index.js",
19
+ "module": "dist/index.js",
20
+ "types": "dist/index.d.ts",
21
+ "scripts": {
22
+ "compile": "virmator compile",
23
+ "docs": "virmator docs",
24
+ "test": "virmator --no-deps test web",
25
+ "test:coverage": "virmator --no-deps test web coverage",
26
+ "test:docs": "virmator docs check",
27
+ "test:update": "npm test"
28
+ },
29
+ "dependencies": {
30
+ "@augment-vir/assert": "^30.0.0",
31
+ "@augment-vir/common": "^30.0.0",
32
+ "@date-vir/duration": "^6.0.0",
33
+ "html-spec-tags": "^2.2.0",
34
+ "type-fest": "^4.25.0"
35
+ },
36
+ "devDependencies": {
37
+ "@augment-vir/test": "^30.0.0",
38
+ "typescript": "^5.5.4"
39
+ },
40
+ "peerDependencies": {
41
+ "element-vir": ">=22.0.0"
42
+ },
43
+ "engines": {
44
+ "node": ">=22"
45
+ },
46
+ "publishConfig": {
47
+ "access": "public"
48
+ }
49
+ }
Binary file