Skip to content

Commit

Permalink
fix: instances re-instancing when not needed (#374)
Browse files Browse the repository at this point in the history
* fix: instances re-instancing when not needed

* chore: remove console

* chore: minor changes concerning re-instancing

---------

Co-authored-by: Tino Koch <[email protected]>
  • Loading branch information
alvarosabu and Tinoooo authored Aug 22, 2023
1 parent dee4b97 commit f2ae46b
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
12 changes: 10 additions & 2 deletions src/core/nodeOps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,13 @@ export const nodeOps: RendererOptions<TresObject, TresObject> = {
if (props?.geometry?.isBufferGeometry) (instance as TresObject3D).userData.tres__geometryViaProp = true
}

// Since THREE instances properties are not consistent, (Orbit Controls doesn't have a `type` property)
// we take the tag name and we save it on the userData for later use in the re-instancing process.
instance.userData = {
...instance.userData,
tres__name: name
}

return instance
},
insert(child, parent) {
Expand Down Expand Up @@ -188,9 +195,10 @@ export const nodeOps: RendererOptions<TresObject, TresObject> = {
const prevNode = node as TresObject3D
const prevArgs = _prevValue ?? []
const args = nextValue ?? []
const instanceName = node.userData.tres__name || node.type

if (node.type && !deepArrayEqual(prevArgs, args)) {
root = Object.assign(prevNode, new catalogue.value[node.type](...nextValue))
if (instanceName && prevArgs.length && !deepArrayEqual(prevArgs, args)) {
root = Object.assign(prevNode, new catalogue.value[instanceName](...nextValue))
}
return
}
Expand Down
12 changes: 12 additions & 0 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ const HTML_TAGS =

export const isHTMLTag = /*#__PURE__*/ makeMap(HTML_TAGS)

export function isDOMElement(obj: any): obj is HTMLElement {
return obj && obj.nodeType === 1;
}

export function kebabToCamel(str: string) {
return str.replace(/-([a-z])/g, (_, c) => c.toUpperCase())
}
Expand Down Expand Up @@ -77,6 +81,14 @@ export const set = (obj: any, path: string | string[], value: any): void => {


export function deepEqual(a: any, b: any): boolean {
if (isDOMElement(a) && isDOMElement(b)) {
const attrsA = a.attributes;
const attrsB = b.attributes;

if (attrsA.length !== attrsB.length) return false;

return Array.from(attrsA).every(({ name, value }) => b.getAttribute(name) === value);
}
// If both are primitives, return true if they are equal
if (a === b) return true;

Expand Down

0 comments on commit f2ae46b

Please sign in to comment.