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

H-3370: Expand and expose graph visualization configuration settings #5242

Merged
merged 2 commits into from
Sep 27, 2024
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
1 change: 1 addition & 0 deletions apps/hash-frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
"@react-sigma/core": "4.0.3",
"@sentry/nextjs": "7.119.0",
"@sentry/react": "7.119.0",
"@sigma/edge-curve": "3.0.0-beta.15",
"@sigma/node-border": "3.0.0-beta.4",
"@svgr/webpack": "8.1.0",
"@tldraw/editor": "2.0.0-alpha.12",
Expand Down
71 changes: 55 additions & 16 deletions apps/hash-frontend/src/components/hooks/use-orgs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { mapGqlSubgraphFieldsFragmentToSubgraph } from "@local/hash-isomorphic-u
import { systemEntityTypes } from "@local/hash-isomorphic-utils/ontology-type-ids";
import type { EntityRootType } from "@local/hash-subgraph";
import { getRoots } from "@local/hash-subgraph/stdlib";
import { useMemo } from "react";

import type {
QueryEntitiesQuery,
Expand All @@ -14,6 +13,7 @@ import { queryEntitiesQuery } from "../../graphql/queries/knowledge/entity.queri
import type { MinimalOrg } from "../../lib/user-and-org";
import { constructMinimalOrg, isEntityOrgEntity } from "../../lib/user-and-org";
import { entityHasEntityTypeByVersionedUrlFilter } from "../../shared/filters";
import { useMemoCompare } from "../../shared/use-memo-compare";

/**
* Retrieves a list of organizations
Expand Down Expand Up @@ -53,24 +53,63 @@ export const useOrgs = (): {

const { queryEntities: subgraphAndPermissions } = data ?? {};

const orgs = useMemo(() => {
if (!subgraphAndPermissions) {
return undefined;
}
const orgs = useMemoCompare(
() => {
if (!subgraphAndPermissions) {
return undefined;
}

const subgraph = mapGqlSubgraphFieldsFragmentToSubgraph<EntityRootType>(
subgraphAndPermissions.subgraph,
);

const subgraph = mapGqlSubgraphFieldsFragmentToSubgraph<EntityRootType>(
subgraphAndPermissions.subgraph,
);
return getRoots(subgraph).map((orgEntity) => {
if (!isEntityOrgEntity(orgEntity)) {
throw new Error(
`Entity with type ${orgEntity.metadata.entityTypeId} is not an org entity`,
);
}
return constructMinimalOrg({ orgEntity });
});
},
[subgraphAndPermissions],
/**
* Check if the previous and new orgs are the same.
* If they are, the return value from the hook won't change, avoiding unnecessary re-renders.
*
* This assumes that the UX/performance benefit of avoiding re-renders outweighs the cost of the comparison.
*
* An alternative approach would be to not use a 'cache-and-network' fetch policy, which also makes a network request
* for all the orgs every time the hook is run, but instead use polling (or a subscription) to get updates.
*
* An identical approach is taken in {@link useUsers}. Update that too if this is changed.
*/ (a, b) => {
if (a === undefined || b === undefined) {
return false;
}

return getRoots(subgraph).map((orgEntity) => {
if (!isEntityOrgEntity(orgEntity)) {
throw new Error(
`Entity with type ${orgEntity.metadata.entityTypeId} is not an org entity`,
);
if (a.length !== b.length) {
return false;
}
return constructMinimalOrg({ orgEntity });
});
}, [subgraphAndPermissions]);

return (
a
.map(
({ entity }) =>
`${entity.metadata.recordId.entityId}${entity.metadata.recordId.editionId}`,
)
.sort()
.join(",") ===
b
.map(
({ entity }) =>
`${entity.metadata.recordId.entityId}${entity.metadata.recordId.editionId}`,
)
.sort()
.join(",")
);
},
);

return {
loading,
Expand Down
73 changes: 57 additions & 16 deletions apps/hash-frontend/src/components/hooks/use-users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { mapGqlSubgraphFieldsFragmentToSubgraph } from "@local/hash-isomorphic-u
import { systemEntityTypes } from "@local/hash-isomorphic-utils/ontology-type-ids";
import type { EntityRootType } from "@local/hash-subgraph";
import { getRoots } from "@local/hash-subgraph/stdlib";
import { useMemo } from "react";

import type {
QueryEntitiesQuery,
Expand All @@ -16,6 +15,7 @@ import {
isEntityUserEntity,
} from "../../lib/user-and-org";
import { entityHasEntityTypeByVersionedUrlFilter } from "../../shared/filters";
import { useMemoCompare } from "../../shared/use-memo-compare";

export const useUsers = (): {
loading: boolean;
Expand Down Expand Up @@ -53,25 +53,66 @@ export const useUsers = (): {

const { queryEntities: queryEntitiesData } = data ?? {};

const users = useMemo(() => {
if (!queryEntitiesData) {
return undefined;
}
const users = useMemoCompare(
() => {
if (!queryEntitiesData) {
return undefined;
}

const subgraph = mapGqlSubgraphFieldsFragmentToSubgraph<EntityRootType>(
queryEntitiesData.subgraph,
);

return getRoots(subgraph).map((userEntity) => {
if (!isEntityUserEntity(userEntity)) {
throw new Error(
`Entity with type ${userEntity.metadata.entityTypeId} is not a user entity`,
);
}

const subgraph = mapGqlSubgraphFieldsFragmentToSubgraph<EntityRootType>(
queryEntitiesData.subgraph,
);
return constructMinimalUser({ userEntity });
});
},
[queryEntitiesData],
/**
* Check if the previous and new users are the same.
* If they are, the return value from the hook won't change, avoiding unnecessary re-renders.
*
* This assumes that the UX/performance benefit of avoiding re-renders outweighs the cost of the comparison.
*
* An alternative approach would be to not use a 'cache-and-network' fetch policy, which also makes a network
* request for all the users every time the hook is run, but instead use polling (or a subscription) to get
* updates.
*
* An identical approach is taken in {@link useOrgs}. Update that too if this is changed.
*/
(a, b) => {
if (a === undefined || b === undefined) {
return false;
}

return getRoots(subgraph).map((userEntity) => {
if (!isEntityUserEntity(userEntity)) {
throw new Error(
`Entity with type ${userEntity.metadata.entityTypeId} is not a user entity`,
);
if (a.length !== b.length) {
return false;
}

return constructMinimalUser({ userEntity });
});
}, [queryEntitiesData]);
return (
a
.map(
({ entity }) =>
`${entity.metadata.recordId.entityId}${entity.metadata.recordId.editionId}`,
)
.sort()
.join(",") ===
b
.map(
({ entity }) =>
`${entity.metadata.recordId.entityId}${entity.metadata.recordId.editionId}`,
)
.sort()
.join(",")
);
},
);

return {
loading,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,66 +1,99 @@
import { Box } from "@mui/material";
import { SigmaContainer } from "@react-sigma/core";
import { EdgeCurvedArrowProgram } from "@sigma/edge-curve";
import { createNodeBorderProgram } from "@sigma/node-border";
import { MultiDirectedGraph } from "graphology";
import { useState } from "react";
import { memo, useRef, useState } from "react";
import { EdgeArrowProgram } from "sigma/rendering";

import { Config } from "./graph-container/config";
import { FullScreenButton } from "./graph-container/full-screen-button";
import type { GraphLoaderProps } from "./graph-container/graph-data-loader";
import { GraphDataLoader } from "./graph-container/graph-data-loader";
import { FullScreenContextProvider } from "./graph-container/shared/full-screen";

export type GraphContainerProps = Omit<GraphLoaderProps, "highlightDepth">;
export type GraphContainerProps = Omit<GraphLoaderProps, "config">;

export const GraphContainer = ({
edges,
nodes,
onEdgeClick,
onNodeClick,
}: GraphContainerProps) => {
/**
* When a node is hovered or selected, we highlight its neighbors up to this depth.
*
* Not currently exposed as a user setting but could be, thus the state.
*/
const [highlightDepth, _setHighlightDepth] = useState(2);

return (
<FullScreenContextProvider>
<SigmaContainer
graph={MultiDirectedGraph}
settings={{
/**
* @see {@link useDefaultSettings} for more settings
*/
/**
* These settings need to be set before the graph is rendered.
*/
defaultNodeType: "bordered",
nodeProgramClasses: {
bordered: createNodeBorderProgram({
borders: [
{
size: { value: 2, mode: "pixels" },
color: { attribute: "borderColor" },
},
{ size: { fill: true }, color: { attribute: "color" } },
],
}),
},
/**
* This setting is dependent on props, and is easiest to set here.
*/
enableEdgeEvents: !!onEdgeClick,
}}
>
<FullScreenButton />
<GraphDataLoader
highlightDepth={highlightDepth}
nodes={nodes}
edges={edges}
onEdgeClick={onEdgeClick}
onNodeClick={onNodeClick}
/>
</SigmaContainer>
</FullScreenContextProvider>
);
const borderRadii = {
borderBottomLeftRadius: "8px",
borderBottomRightRadius: "8px",
};

export const GraphContainer = memo(
({ edges, nodes, onEdgeClick, onNodeClick }: GraphContainerProps) => {
const [config, setConfig] = useState<GraphLoaderProps["config"]>({
/**
* When a node is hovered or clicked, the depth around it to which other nodes will be highlighted
*/
highlightDepth: 4,
/**
* When a node is hovered or clicked, the links from it that will be followed to highlight neighbors,
* i.e. 'All', 'In'wards and 'Out'wards
*/
highlightDirection: "All",
});

const containerRef = useRef<HTMLDivElement>(null);

return (
<FullScreenContextProvider>
<Box
ref={containerRef}
sx={({ palette }) => ({
border: `1px solid ${palette.gray[30]}`,
borderTopWidth: 0,
height: "100%",
...borderRadii,
})}
>
<SigmaContainer
graph={MultiDirectedGraph}
settings={{
/**
* @see {@link useDefaultSettings} for more settings
*/
/**
* These settings need to be set before the graph is rendered.
*/
defaultNodeType: "bordered",
edgeProgramClasses: {
arrow: EdgeArrowProgram,
curved: EdgeCurvedArrowProgram,
},
nodeProgramClasses: {
bordered: createNodeBorderProgram({
borders: [
{
size: { value: 2, mode: "pixels" },
color: { attribute: "borderColor" },
},
{ size: { fill: true }, color: { attribute: "color" } },
],
}),
},
/**
* This setting is dependent on props, and is easiest to set here.
*/
enableEdgeEvents: !!onEdgeClick,
}}
style={{ position: "relative", overflow: "hidden", ...borderRadii }}
>
<FullScreenButton />
<Config
containerRef={containerRef}
config={config}
setConfig={setConfig}
/>
<GraphDataLoader
config={config}
nodes={nodes}
edges={edges}
onEdgeClick={onEdgeClick}
onNodeClick={onNodeClick}
/>
</SigmaContainer>
</Box>
</FullScreenContextProvider>
);
},
);
Loading
Loading