Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: instances re-instancing when not needed #374

Merged
merged 4 commits into from
Aug 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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