Skip to content

Commit

Permalink
Support inner morph
Browse files Browse the repository at this point in the history
  • Loading branch information
joeldrapper committed Apr 1, 2024
1 parent 5d8e976 commit efeddc0
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 10 deletions.
1 change: 1 addition & 0 deletions dist/morphlex.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,5 @@ interface Options {
afterPropertyUpdated?: (node: Node, propertyName: PropertyKey, previousValue: unknown) => void;
}
export declare function morph(node: ChildNode, reference: ChildNode | string, options?: Options): void;
export declare function innerMorph(node: Element, reference: Element | string, options?: Options): void;
export {};
33 changes: 28 additions & 5 deletions dist/morphlex.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

38 changes: 33 additions & 5 deletions src/morphlex.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,11 @@ interface Options {

export function morph(node: ChildNode, reference: ChildNode | string, options: Options = {}): void {
if (typeof reference === "string") {
const template = document.createElement("template");
template.innerHTML = reference.trim();
reference = template.content.firstChild as ChildNode;
if (!reference) {
const parsedReferenceNode = parseNodeFromString(reference);

if (parsedReferenceNode) {
reference = parsedReferenceNode;
} else {
throw new Error("[Morphlex] The string did not contain any nodes.");
}
}
Expand All @@ -69,6 +70,33 @@ export function morph(node: ChildNode, reference: ChildNode | string, options: O
}
}

export function innerMorph(node: Element, reference: Element | string, options: Options = {}): void {
if (typeof reference === "string") {
const parsedReferenceNode = parseNodeFromString(reference);

if (parsedReferenceNode && isElement(parsedReferenceNode)) {
reference = parsedReferenceNode;
} else {
throw new Error("[Morphlex] The string did not contain any nodes.");
}
}

if (isElement(node)) {
const originalAriaBusy = node.ariaBusy;
node.ariaBusy = "true";
new Morph(options).innerMorph([node, reference]);
node.ariaBusy = originalAriaBusy;
} else {
new Morph(options).innerMorph([node, reference]);
}
}

function parseNodeFromString(string: string): ChildNode | null {
const parser = new DOMParser();
const doc = parser.parseFromString(string, "text/html");
return doc.body.firstChild;
}

class Morph {
readonly #idMap: IdMap;
readonly #sensivityMap: SensivityMap;
Expand Down Expand Up @@ -111,7 +139,7 @@ class Morph {
this.#morphNode(pair);
}

morphInner(pair: NodeReferencePair<Element>): void {
innerMorph(pair: NodeReferencePair<Element>): void {
if (isMatchingElementPair(pair)) {
this.#buildMaps(pair);
this.#morphMatchingElementContent(pair);
Expand Down

0 comments on commit efeddc0

Please sign in to comment.