Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

wip: gantt view

Brad Barbin648b8e993411
diff --git a/apps/carbon/app/assets/icons/ShowParentIcon.tsx b/apps/carbon/app/assets/icons/ShowParentIcon.tsx
new file mode 100644
index 0000000000..656f311124
--- /dev/null
+++ b/apps/carbon/app/assets/icons/ShowParentIcon.tsx
@@ -0,0 +1,35 @@
+export function ShowParentIcon({ className }: { className?: string }) {
+ return (
+ <svg
+ className={className}
+ viewBox="0 0 16 16"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ fill="currentColor"
+ fillRule="evenodd"
+ clipRule="evenodd"
+ d="M3.125 16H3.625H4.125V15H3.125H2C1.89733 15 1.8 14.9848 1.70919 14.9573L1.19765 14.8024L1.04267 14.2908C1.01515 14.2 1 14.1027 1 14V12.875V11.875H0V12.375V12.875V14C0 14.202 0.0299409 14.397 0.0856265 14.5808C0.135047 14.7439 0.204744 14.8982 0.291786 15.0407C0.363386 15.158 0.446722 15.2673 0.540161 15.3671C0.570065 15.399 0.601004 15.4299 0.632924 15.4598C0.732663 15.5533 0.841982 15.6366 0.95925 15.7082C1.10181 15.7953 1.25612 15.865 1.41923 15.9144C1.60303 15.9701 1.79802 16 2 16H3.125ZM10.125 15V16H9.625H9.125H6.875H6.375H5.875V15H6.875H9.125H10.125ZM15 5.875H16V6.375V6.875V9.125V9.625V10.125H15V9.125V6.875V5.875ZM5.875 1V0H6.375H6.875H9.125H9.625H10.125V1H9.125H6.875H5.875ZM1 10.125H0V9.625V9.125V6.875V6.375V5.875H1V6.875V9.125V10.125ZM0 3.625V4.125H1V3.125V2C1 1.89733 1.01515 1.8 1.04267 1.70919L1.19765 1.19765L1.70919 1.04267C1.8 1.01515 1.89733 1 2 1H3.125H4.125V0H3.625H3.125H2C1.79802 0 1.60303 0.0299409 1.41923 0.0856264C1.25612 0.135047 1.10181 0.204744 0.95925 0.291786C0.841983 0.363386 0.732663 0.446722 0.632924 0.540161C0.601004 0.570065 0.570065 0.601004 0.540161 0.632924C0.446722 0.732663 0.363386 0.841982 0.291786 0.95925C0.204744 1.10181 0.135047 1.25612 0.0856265 1.41923C0.0299409 1.60303 0 1.79802 0 2V3.125V3.625ZM12.375 0H11.875V1H12.875H14C14.1027 1 14.2 1.01515 14.2908 1.04267L14.8024 1.19765L14.9573 1.70919C14.9848 1.8 15 1.89733 15 2V3.125V4.125H16V3.625V3.125V2C16 1.79802 15.9701 1.60303 15.9144 1.41923C15.865 1.25612 15.7953 1.10181 15.7082 0.95925C15.6366 0.841982 15.5533 0.732663 15.4598 0.632924C15.4299 0.601004 15.399 0.570065 15.3671 0.540161C15.2673 0.446722 15.158 0.363386 15.0407 0.291786C14.8982 0.204744 14.7439 0.135047 14.5808 0.0856265C14.397 0.0299409 14.202 0 14 0H12.875H12.375ZM16 12.375V11.875H15V12.875V14C15 14.1027 14.9848 14.2 14.9573 14.2908L14.8024 14.8024L14.2908 14.9573C14.2 14.9848 14.1027 15 14 15H12.875H11.875V16H12.375H12.875H14C14.202 16 14.397 15.9701 14.5808 15.9144C14.7439 15.865 14.8982 15.7953 15.0407 15.7082C15.158 15.6366 15.2673 15.5533 15.3671 15.4598C15.399 15.4299 15.4299 15.399 15.4598 15.3671C15.5533 15.2673 15.6366 15.158 15.7082 15.0407C15.7953 14.8982 15.865 14.7439 15.9144 14.5808C15.9701 14.397 16 14.202 16 14V12.875V12.375ZM8.75 6.26758L10.4523 7.96991C10.7452 8.26281 11.2201 8.26281 11.513 7.96991C11.8059 7.67702 11.8059 7.20215 11.513 6.90925L8.59099 3.98725C8.43431 3.83057 8.22556 3.7577 8.02045 3.76865C7.81604 3.75834 7.60821 3.83124 7.45209 3.98736L4.53009 6.90937C4.23719 7.20226 4.23719 7.67713 4.53009 7.97003C4.82298 8.26292 5.29785 8.26292 5.59075 7.97003L7.25 6.31077L7.25 11.25C7.25 11.6642 7.58579 12 8 12C8.41421 12 8.75 11.6642 8.75 11.25L8.75 6.26758Z"
+ />
+ </svg>
+ );
+}
+
+export function ShowParentIconSelected({ className }: { className?: string }) {
+ return (
+ <svg
+ className={className}
+ viewBox="0 0 16 16"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ fill="currentColor"
+ fillRule="evenodd"
+ clipRule="evenodd"
+ d="M2 0C0.895431 0 0 0.895431 0 2V14C0 15.1046 0.895431 16 2 16H14C15.1046 16 16 15.1046 16 14V2C16 0.895431 15.1046 0 14 0H2ZM8.75 6.26758L10.4523 7.96991C10.7452 8.26281 11.2201 8.26281 11.513 7.96991C11.8059 7.67702 11.8059 7.20215 11.513 6.90925L8.59099 3.98725C8.43344 3.8297 8.22324 3.7569 8.01703 3.76884C7.8138 3.75958 7.60752 3.83254 7.45234 3.98773L4.53033 6.90973C4.23744 7.20263 4.23744 7.6775 4.53033 7.97039C4.82322 8.26329 5.2981 8.26329 5.59099 7.97039L7.25 6.31138L7.25 11.25C7.25 11.6642 7.58579 12 8 12C8.41421 12 8.75 11.6642 8.75 11.25L8.75 6.26758Z"
+ />
+ </svg>
+ );
+}
diff --git a/apps/carbon/app/assets/images/[email protected] b/apps/carbon/app/assets/images/[email protected]
new file mode 100644
index 0000000000..2d601bfced
Binary files /dev/null and b/apps/carbon/app/assets/images/[email protected] differ
diff --git a/apps/carbon/app/components/Grid/Grid.tsx b/apps/carbon/app/components/Grid/Grid.tsx
index 4199667ae7..d4522a4c9c 100644
--- a/apps/carbon/app/components/Grid/Grid.tsx
+++ b/apps/carbon/app/components/Grid/Grid.tsx
@@ -11,7 +11,7 @@ import {
useEscape,
useMount,
} from "@carbon/react";
-import { clip } from "@carbon/utils";
+import { clamp } from "@carbon/utils";
import type { ColumnDef, ColumnOrderState } from "@tanstack/react-table";
import {
flexRender,
@@ -252,10 +252,10 @@ const Grid = <T extends object>({
}
}
} else {
- x1 = clip(x1, 0, lastColumn);
+ x1 = clamp(x1, 0, lastColumn);
}
- y1 = clip(y1, 0, lastRow);
+ y1 = clamp(y1, 0, lastRow);
return [x1, y1];
};
diff --git a/apps/carbon/app/components/Layout/Navigation/useModules.tsx b/apps/carbon/app/components/Layout/Navigation/useModules.tsx
index 033933ec07..a27aa2eb08 100644
--- a/apps/carbon/app/components/Layout/Navigation/useModules.tsx
+++ b/apps/carbon/app/components/Layout/Navigation/useModules.tsx
@@ -1,15 +1,6 @@
-import {
- LuBox,
- LuComponent,
- LuCreditCard,
- LuFiles,
- LuLandmark,
- LuReceipt,
- LuSettings,
- LuShield,
- LuShoppingCart,
- LuUsers,
-} from "react-icons/lu";
+import { BiListCheck } from "react-icons/bi";
+import { BsCalendar2Week } from "react-icons/bs";
+import { LuSettings, LuShield, LuUsers } from "react-icons/lu";
import { usePermissions } from "~/hooks";
import type { Authenticated, NavItem } from "~/types";
import { path } from "~/utils/path";
@@ -18,72 +9,72 @@ export function useModules() {
const permissions = usePermissions();
const modules: Authenticated<NavItem>[] = [
- {
- permission: "parts",
- name: "Parts",
- to: path.to.partsSearch,
- icon: LuComponent,
- },
// {
- // permission: "jobs",
- // name: "Jobs",
- // to: path.to.jobs,
- // icon: BiListCheck,
+ // permission: "parts",
+ // name: "Parts",
+ // to: path.to.partsSearch,
+ // icon: LuComponent,
// },
{
- permission: "inventory",
- name: "Inventory",
- to: path.to.receipts,
- icon: LuBox,
+ permission: "jobs",
+ name: "Jobs",
+ to: path.to.jobs,
+ icon: BiListCheck,
},
// {
- // permission: "scheduling",
- // name: "Scheduling",
- // to: path.to.scheduling,
- // icon: BsCalendar2Week,
+ // permission: "inventory",
+ // name: "Inventory",
+ // to: path.to.receipts,
+ // icon: LuBox,
// },
+ {
+ permission: "scheduling",
+ name: "Scheduling",
+ to: path.to.scheduling,
+ icon: BsCalendar2Week,
+ },
// {
// permission: "timecards",
// name: "Timecards",
// to: path.to.timecards,
// icon: AiOutlineFieldTime,
// },
- {
- permission: "sales",
- name: "Sales",
- to: path.to.salesOrders,
- icon: LuReceipt,
- },
- {
- permission: "purchasing",
- name: "Purchasing",
- to: path.to.purchaseOrders,
- icon: LuShoppingCart,
- },
- {
- permission: "documents",
- name: "Documents",
- to: path.to.documents,
- icon: LuFiles,
- },
+ // {
+ // permission: "sales",
+ // name: "Sales",
+ // to: path.to.salesOrders,
+ // icon: LuReceipt,
+ // },
+ // {
+ // permission: "purchasing",
+ // name: "Purchasing",
+ // to: path.to.purchaseOrders,
+ // icon: LuShoppingCart,
+ // },
+ // {
+ // permission: "documents",
+ // name: "Documents",
+ // to: path.to.documents,
+ // icon: LuFiles,
+ // },
// {
// permission: "messages",
// name: "Messaging",
// to: path.to.messaging,
// icon: BiMessage,
// },
- {
- permission: "accounting",
- name: "Accounting",
- to: path.to.chartOfAccounts,
- icon: LuLandmark,
- },
- {
- permission: "invoicing",
- name: "Invoicing",
- to: path.to.purchaseInvoices,
- icon: LuCreditCard,
- },
+ // {
+ // permission: "accounting",
+ // name: "Accounting",
+ // to: path.to.chartOfAccounts,
+ // icon: LuLandmark,
+ // },
+ // {
+ // permission: "invoicing",
+ // name: "Invoicing",
+ // to: path.to.purchaseInvoices,
+ // icon: LuCreditCard,
+ // },
{
permission: "resources",
name: "Resources",
diff --git a/apps/carbon/app/components/Layout/Topbar/Topbar.tsx b/apps/carbon/app/components/Layout/Topbar/Topbar.tsx
index 96e76e8a63..a190718d6e 100644
--- a/apps/carbon/app/components/Layout/Topbar/Topbar.tsx
+++ b/apps/carbon/app/components/Layout/Topbar/Topbar.tsx
@@ -3,7 +3,6 @@ import { Search } from "~/components/Search";
import { usePermissions } from "~/hooks";
import AvatarMenu from "./AvatarMenu";
import Breadcrumbs from "./Breadcrumbs";
-import CreateMenu from "./CreateMenu";
import HelpMenu from "./HelpMenu";
import ModeSwitcher from "./ModeSwitcher";
@@ -14,7 +13,7 @@ const Topbar = () => {
<Breadcrumbs />
{permissions.is("employee") ? <Search /> : <div />}
<HStack spacing={1} className="justify-end py-2">
- <CreateMenu />
+ {/* <CreateMenu /> */}
<HelpMenu />
<ModeSwitcher />
<AvatarMenu />
diff --git a/apps/carbon/app/components/Search/DebouncedInput/DebouncedInput.tsx b/apps/carbon/app/components/Search/DebouncedInput/DebouncedInput.tsx
index 0063e2e45a..5a6647f4a8 100644
--- a/apps/carbon/app/components/Search/DebouncedInput/DebouncedInput.tsx
+++ b/apps/carbon/app/components/Search/DebouncedInput/DebouncedInput.tsx
@@ -1,6 +1,6 @@
import type { InputProps } from "@carbon/react";
import { Input, useDebounce } from "@carbon/react";
-import { useEffect, useRef, useState } from "react";
+import { useRef, useState } from "react";
import { useUrlParams } from "~/hooks";
type DebounceInputProps = InputProps & {
@@ -11,21 +11,21 @@ const DebouncedInput = ({ param, ...props }: DebounceInputProps) => {
const initialLoad = useRef(true);
const [params, setParams] = useUrlParams();
const [query, setQuery] = useState(params.get(param) || "");
- const [debouncedQuery] = useDebounce(query, 500);
-
- useEffect(() => {
+ const debounceQuery = useDebounce((q: string) => {
if (initialLoad.current) {
initialLoad.current = false;
} else {
- setParams({ [param]: debouncedQuery });
+ setParams({ [param]: q });
}
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [debouncedQuery]);
+ }, 500);
return (
<Input
- defaultValue={params.get(param) || ""}
- onChange={(e) => setQuery(e.target.value)}
+ value={query}
+ onChange={(e) => {
+ setQuery(e.target.value);
+ debounceQuery(e.target.value);
+ }}
className="w-[100px] sm:w-[200px]"
{...props}
/>
diff --git a/apps/carbon/app/components/Search/Search/Search.tsx b/apps/carbon/app/components/Search/Search/Search.tsx
index cdb4a7788b..c5cd935d55 100644
--- a/apps/carbon/app/components/Search/Search/Search.tsx
+++ b/apps/carbon/app/components/Search/Search/Search.tsx
@@ -68,7 +68,13 @@ const SearchModal = ({
const [loading, setLoading] = useState(false);
const [input, setInput] = useState("");
- const [debouncedInput] = useDebounce(input, 500);
+ const debounceSearch = useDebounce((q: string) => {
+ if (q) {
+ getSearchResults(q);
+ } else {
+ setSearchResults([]);
+ }
+ }, 500);
useEffect(() => {
if (isOpen) {
@@ -118,16 +124,9 @@ const SearchModal = ({
[company.id, supabase]
);
- useEffect(() => {
- if (debouncedInput) {
- getSearchResults(debouncedInput);
- } else {
- setSearchResults([]);
- }
- }, [debouncedInput, getSearchResults]);
-
const onInputChange = (value: string) => {
setInput(value);
+ debounceSearch(value);
};
const onSelect = async (route: Route) => {
diff --git a/apps/carbon/app/components/Table/Table.tsx b/apps/carbon/app/components/Table/Table.tsx
index bac2af04fa..d9b1c9d5ab 100644
--- a/apps/carbon/app/components/Table/Table.tsx
+++ b/apps/carbon/app/components/Table/Table.tsx
@@ -14,7 +14,7 @@ import {
useEscape,
useMount,
} from "@carbon/react";
-import { clip } from "@carbon/utils";
+import { clamp } from "@carbon/utils";
import type {
ColumnDef,
ColumnOrderState,
@@ -339,10 +339,10 @@ const Table = <T extends object>({
}
}
} else {
- x1 = clip(x1, 0, lastColumn);
+ x1 = clamp(x1, 0, lastColumn);
}
- y1 = clip(y1, 0, lastRow);
+ y1 = clamp(y1, 0, lastRow);
return [x1, y1];
};
diff --git a/apps/carbon/app/components/Timeline.tsx b/apps/carbon/app/components/Timeline.tsx
new file mode 100644
index 0000000000..f9749b0e98
--- /dev/null
+++ b/apps/carbon/app/components/Timeline.tsx
@@ -0,0 +1,244 @@
+import { inverseLerp, lerp } from "@carbon/utils";
+import type { ComponentPropsWithoutRef, ReactNode } from "react";
+import {
+ Fragment,
+ createContext,
+ useCallback,
+ useContext,
+ useRef,
+ useState,
+} from "react";
+
+interface MousePosition {
+ x: number;
+ y: number;
+}
+const MousePositionContext = createContext<MousePosition | undefined>(
+ undefined
+);
+export function MousePositionProvider({ children }: { children: ReactNode }) {
+ const ref = useRef<HTMLDivElement>(null);
+ const [position, setPosition] = useState<MousePosition | undefined>(
+ undefined
+ );
+
+ const handleMouseMove = useCallback(
+ (e: React.MouseEvent) => {
+ if (!ref.current) {
+ setPosition(undefined);
+ return;
+ }
+
+ const { top, left, width, height } = ref.current.getBoundingClientRect();
+ const x = (e.clientX - left) / width;
+ const y = (e.clientY - top) / height;
+
+ if (x < 0 || x > 1 || y < 0 || y > 1) {
+ setPosition(undefined);
+ return;
+ }
+
+ setPosition({ x, y });
+ },
+ [ref.current]
+ );
+
+ return (
+ <div
+ ref={ref}
+ onMouseEnter={handleMouseMove}
+ onMouseLeave={() => setPosition(undefined)}
+ onMouseMove={handleMouseMove}
+ style={{ width: "100%", height: "100%" }}
+ >
+ <MousePositionContext.Provider value={position}>
+ {children}
+ </MousePositionContext.Provider>
+ </div>
+ );
+}
+export const useMousePosition = () => {
+ return useContext(MousePositionContext);
+};
+
+type TimelineContextState = {
+ startMs: number;
+ durationMs: number;
+};
+const TimelineContext = createContext<TimelineContextState>(
+ {} as TimelineContextState
+);
+
+function useTimeline() {
+ return useContext(TimelineContext);
+}
+
+export type RootProps = {
+ /** If the timeline doesn't start at zero. Doesn't impact layout but gives you the times back */
+ startMs?: number;
+ durationMs: number;
+ /** A number between 0 and 1, determines the width between min and max */
+ scale: number;
+ minWidth: number;
+ maxWidth: number;
+ children?: ReactNode;
+ className?: string;
+};
+
+/** The main element that determines the dimensions for all sub-elements */
+export function Root({
+ startMs = 0,
+ durationMs,
+ scale,
+ minWidth,
+ maxWidth,
+ children,
+ className,
+}: RootProps) {
+ const pixelWidth = calculatePixelWidth(minWidth, maxWidth, scale);
+
+ return (
+ <TimelineContext.Provider value={{ startMs, durationMs }}>
+ <div
+ className={className}
+ style={{
+ position: "relative",
+ width: `${pixelWidth}px`,
+ }}
+ >
+ <MousePositionProvider>{children}</MousePositionProvider>
+ </div>
+ </TimelineContext.Provider>
+ );
+}
+
+export type RowProps = ComponentPropsWithoutRef<"div">;
+
+/** This simply acts as a container, with position relative.
+ * This allows you to nest "Rows" and put heights on them */
+export function Row({ className, children, ...props }: RowProps) {
+ return (
+ <div
+ {...props}
+ className={className}
+ style={{ ...props.style, position: "relative" }}
+ >
+ {children}
+ </div>
+ );
+}
+
+export type PointProps = {
+ ms: number;
+ className?: string;
+ children?: (ms: number) => ReactNode;
+};
+
+/** A point in time, it has no duration */
+export function Point({ ms, className, children }: PointProps) {
+ const { startMs, durationMs } = useTimeline();
+ const position = inverseLerp(startMs, startMs + durationMs, ms);
+ return (
+ <div
+ className={className}
+ style={{
+ position: "absolute",
+ left: `${position * 100}%`,
+ }}
+ >
+ {children && children(ms)}
+ </div>
+ );
+}
+
+export type SpanProps = {
+ startMs: number;
+ durationMs: number;
+ className?: string;
+ children?: ReactNode;
+};
+
+/** As span of time with a start and duration */
+export function Span({ startMs, durationMs, className, children }: SpanProps) {
+ const { startMs: rootStartMs, durationMs: rootDurationMs } = useTimeline();
+ const position = inverseLerp(
+ rootStartMs,
+ rootStartMs + rootDurationMs,
+ startMs
+ );
+ const width =
+ inverseLerp(
+ rootStartMs,
+ rootStartMs + rootDurationMs,
+ startMs + durationMs
+ ) - position;
+ return (
+ <div
+ className={className}
+ style={{
+ position: "absolute",
+ left: `${position * 100}%`,
+ width: `${width * 100}%`,
+ }}
+ >
+ {children}
+ </div>
+ );
+}
+
+export type EquallyDistributeProps = {
+ count: number;
+ children: (ms: number, index: number) => ReactNode;
+};
+
+/** Render a child equally distributed across the duration */
+export function EquallyDistribute({ count, children }: EquallyDistributeProps) {
+ const { startMs, durationMs } = useTimeline();
+
+ return (
+ <>
+ {Array.from({ length: count }).map((_, index) => {
+ const ms = startMs + (durationMs / (count - 1)) * index;
+ return <Fragment key={index}>{children(ms, index)}</Fragment>;
+ })}
+ </>
+ );
+}
+
+export type FollowCursorProps = {
+ children: (ms: number) => ReactNode;
+};
+
+/** Renders a child that follows the cursor */
+export function FollowCursor({ children }: FollowCursorProps) {
+ const { startMs, durationMs } = useTimeline();
+ const relativeMousePosition = useMousePosition();
+ const ms = relativeMousePosition?.x
+ ? lerp(startMs, startMs + durationMs, relativeMousePosition.x)
+ : undefined;
+
+ if (ms === undefined) return null;
+
+ return (
+ <div
+ style={{
+ position: "absolute",
+ top: 0,
+ left: relativeMousePosition ? `${relativeMousePosition?.x * 100}%` : 0,
+ height: "100%",
+ pointerEvents: "none",
+ }}
+ >
+ {children(ms)}
+ </div>
+ );
+}
+
+/** Gives the total width of the root */
+function calculatePixelWidth(
+ minWidth: number,
+ maxWidth: number,
+ scale: number
+) {
+ return lerp(minWidth, maxWidth, scale);
+}
diff --git a/apps/carbon/app/components/TreeView/TreeView.tsx b/apps/carbon/app/components/TreeView/TreeView.tsx
new file mode 100644
index 0000000000..f41bb19527
--- /dev/null
+++ b/apps/carbon/app/components/TreeView/TreeView.tsx
@@ -0,0 +1,619 @@
+import { cn } from "@carbon/react";
+import type { VirtualItem, Virtualizer } from "@tanstack/react-virtual";
+import { useVirtualizer } from "@tanstack/react-virtual";
+import { motion } from "framer-motion";
+import type { MutableRefObject, RefObject } from "react";
+import { useCallback, useEffect, useReducer, useRef } from "react";
+import type { NodeState, NodesState } from "./reducer";
+import { reducer } from "./reducer";
+import { concreteStateFromInput, selectedIdFromState } from "./utils";
+
+export type TreeViewProps<TData> = {
+ tree: FlatTree<TData>;
+ parentClassName?: string;
+ renderNode: (params: {
+ node: FlatTreeItem<TData>;
+ state: NodeState;
+ index: number;
+ virtualizer: Virtualizer<HTMLElement, Element>;
+ virtualItem: VirtualItem;
+ }) => React.ReactNode;
+ nodes: UseTreeStateOutput["nodes"];
+ autoFocus?: boolean;
+ virtualizer: Virtualizer<HTMLElement, Element>;
+ parentRef?: MutableRefObject<HTMLElement | null>;
+ scrollRef?: MutableRefObject<HTMLElement | null>;
+ onScroll?: (scrollTop: number) => void;
+} & Pick<UseTreeStateOutput, "getTreeProps" | "getNodeProps">;
+
+export type GetTreePropsFn = UseTreeStateOutput["getTreeProps"];
+export type GetNodePropsFn = UseTreeStateOutput["getNodeProps"];
+
+export function TreeView<TData>({
+ tree,
+ renderNode,
+ nodes,
+ autoFocus = false,
+ getTreeProps,
+ getNodeProps,
+ parentClassName,
+ virtualizer,
+ parentRef,
+ scrollRef,
+ onScroll,
+}: TreeViewProps<TData>) {
+ useEffect(() => {
+ if (autoFocus) {
+ parentRef?.current?.focus();
+ }
+ }, [autoFocus, parentRef?.current]);
+
+ const virtualItems = virtualizer.getVirtualItems();
+
+ const scrollCallback = useCallback(
+ (event: Event) => {
+ if (!onScroll) return;
+ const target = event.target as HTMLElement;
+ onScroll?.(target.scrollTop);
+ },
+ [onScroll]
+ );
+
+ useEffect(() => {
+ //subscribe to scrollRef scroll event
+ if (!scrollRef?.current || onScroll === undefined) return;
+ scrollRef.current.addEventListener("scroll", scrollCallback);
+ return () =>
+ scrollRef.current?.removeEventListener("scroll", scrollCallback);
+ }, [scrollRef?.current]);
+
+ return (
+ <motion.div
+ ref={(element) => {
+ if (parentRef) {
+ parentRef.current = element;
+ }
+ if (scrollRef) {
+ scrollRef.current = element;
+ }
+ }}
+ className={cn(
+ "w-full overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-charcoal-600 focus-within:outline-none",
+ parentClassName
+ )}
+ layoutScroll
+ {...getTreeProps()}
+ >
+ <div
+ style={{
+ height: `${virtualizer.getTotalSize()}px`,
+ width: "100%",
+ position: "relative",
+ overflowY: "visible",
+ }}
+ >
+ <div
+ style={{
+ position: "absolute",
+ overflowY: "visible",
+ top: 0,
+ left: 0,
+ width: "100%",
+ transform: `translateY(${virtualItems.at(0)?.start ?? 0}px)`,
+ }}
+ >
+ {virtualItems.map((virtualItem) => {
+ const node = tree.find((node) => node.id === virtualItem.key);
+ if (!node) return null;
+ const state = nodes[node.id];
+ if (!state) return null;
+ if (!state.visible) return null;
+ return (
+ <div
+ key={node.id}
+ data-index={virtualItem.index}
+ ref={virtualizer.measureElement}
+ className="overflow-clip"
+ {...getNodeProps(node.id)}
+ >
+ {renderNode({
+ node,
+ state,
+ index: virtualItem.index,
+ virtualizer: virtualizer,
+ virtualItem,
+ })}
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ </motion.div>
+ );
+}
+
+export type Filter<TData, TFilterValue> = {
+ value?: TFilterValue;
+ fn: (value: TFilterValue, node: FlatTreeItem<TData>) => boolean;
+};
+
+type TreeStateHookProps<TData, TFilterValue> = {
+ tree: FlatTree<TData>;
+ selectedId?: string;
+ collapsedIds?: string[];
+ onSelectedIdChanged?: (selectedId: string | undefined) => void;
+ estimatedRowHeight: (params: {
+ node: FlatTreeItem<TData>;
+ state: NodeState;
+ index: number;
+ }) => number;
+ parentRef: RefObject<any>;
+ filter?: Filter<TData, TFilterValue>;
+};
+
+//this is so Framer Motion can be used to render the components
+type HTMLAttributes = Omit<
+ React.HTMLAttributes<HTMLElement>,
+ "onAnimationStart" | "onDragStart" | "onDragEnd" | "onDrag"
+>;
+
+export type UseTreeStateOutput = {
+ selected: string | undefined;
+ nodes: NodesState;
+ virtualizer: Virtualizer<HTMLElement, Element>;
+
+ getTreeProps: () => HTMLAttributes;
+ getNodeProps: (id: string) => HTMLAttributes;
+ selectNode: (id: string, scrollToNode?: boolean) => void;
+ deselectNode: (id: string) => void;
+ deselectAllNodes: () => void;
+ toggleNodeSelection: (id: string, scrollToNode?: boolean) => void;
+ expandNode: (id: string, scrollToNode?: boolean) => void;
+ collapseNode: (id: string) => void;
+ toggleExpandNode: (id: string, scrollToNode?: boolean) => void;
+ expandAllBelowDepth: (depth: number) => void;
+ collapseAllBelowDepth: (depth: number) => void;
+ expandLevel: (level: number) => void;
+ collapseLevel: (level: number) => void;
+ toggleExpandLevel: (level: number) => void;
+ selectFirstVisibleNode: (scrollToNode?: boolean) => void;
+ selectLastVisibleNode: (scrollToNode?: boolean) => void;
+ selectNextVisibleNode: (scrollToNode?: boolean) => void;
+ selectPreviousVisibleNode: (scrollToNode?: boolean) => void;
+ selectParentNode: (scrollToNode?: boolean) => void;
+ scrollToNode: (id: string) => void;
+};
+
+export function useTree<TData, TFilterValue>({
+ tree,
+ selectedId,
+ collapsedIds,
+ onSelectedIdChanged,
+ parentRef,
+ estimatedRowHeight,
+ filter,
+}: TreeStateHookProps<TData, TFilterValue>): UseTreeStateOutput {
+ const previousNodeCount = useRef(tree.length);
+ const previousSelectedId = useRef<string | undefined>(selectedId);
+
+ const [state, dispatch] = useReducer(
+ reducer,
+ concreteStateFromInput({ tree, selectedId, collapsedIds, filter })
+ );
+
+ //fire onSelectedIdChanged()
+ useEffect(() => {
+ const selectedId = selectedIdFromState(state.nodes);
+ if (selectedId !== previousSelectedId.current) {
+ previousSelectedId.current = selectedId;
+ onSelectedIdChanged?.(selectedId);
+ }
+ }, [state.changes.selectedId]);
+
+ //update tree when the number of nodes changes
+ useEffect(() => {
+ if (tree.length !== previousNodeCount.current) {
+ previousNodeCount.current = tree.length;
+ dispatch({ type: "UPDATE_TREE", payload: { tree } });
+ }
+ }, [previousNodeCount.current, tree.length]);
+
+ //update the filter, if it's changed
+ const previousFilter = useRef(filter);
+ useEffect(() => {
+ //check if the value (not reference) of the filter is the same
+ const previousValue = previousFilter.current
+ ? JSON.stringify(previousFilter.current.value)
+ : undefined;
+ const newValue = filter ? JSON.stringify(filter.value) : undefined;
+
+ previousFilter.current = filter;
+
+ if (previousValue !== newValue) {
+ dispatch({ type: "UPDATE_FILTER", payload: { filter } });
+ }
+ }, [filter?.value]);
+
+ const virtualizer = useVirtualizer({
+ count: state.visibleNodeIds.length,
+ getItemKey: (index) => state.visibleNodeIds[index],
+ getScrollElement: () => parentRef.current,
+ estimateSize: (index: number) => {
+ return estimatedRowHeight({
+ node: tree[index],
+ state: state.nodes[tree[index].id],
+ index,
+ });
+ },
+ overscan: 20,
+ });
+
+ const scrollToNodeFn = useCallback(
+ (id: string) => {
+ const itemIndex = state.visibleNodeIds.findIndex((n) => n === id);
+
+ if (itemIndex !== -1) {
+ virtualizer.scrollToIndex(itemIndex, { align: "auto" });
+ }
+ },
+ [state]
+ );
+
+ const selectNode = useCallback(
+ (id: string, scrollToNode = true) => {
+ dispatch({
+ type: "SELECT_NODE",
+ payload: { id, scrollToNode, scrollToNodeFn },
+ });
+ },
+ [state]
+ );
+
+ const deselectNode = useCallback(
+ (id: string) => {
+ dispatch({ type: "DESELECT_NODE", payload: { id } });
+ },
+ [state]
+ );
+
+ const deselectAllNodes = useCallback(() => {
+ dispatch({ type: "DESELECT_ALL_NODES" });
+ }, [state]);
+
+ const toggleNodeSelection = useCallback(
+ (id: string, scrollToNode = true) => {
+ dispatch({
+ type: "TOGGLE_NODE_SELECTION",
+ payload: { id, scrollToNode, scrollToNodeFn },
+ });
+ },
+ [state]
+ );
+
+ const expandNode = useCallback(
+ (id: string, scrollToNode = true) => {
+ dispatch({
+ type: "EXPAND_NODE",
+ payload: { id, scrollToNode, scrollToNodeFn },
+ });
+ },
+ [state]
+ );
+
+ const collapseNode = useCallback(
+ (id: string) => {
+ dispatch({ type: "COLLAPSE_NODE", payload: { id } });
+ },
+ [state]
+ );
+
+ const toggleExpandNode = useCallback(
+ (id: string, scrollToNode = true) => {
+ dispatch({
+ type: "TOGGLE_EXPAND_NODE",
+ payload: { id, scrollToNode, scrollToNodeFn },
+ });
+ },
+ [state]
+ );
+
+ const selectFirstVisibleNode = useCallback(
+ (scrollToNode = true) => {
+ dispatch({
+ type: "SELECT_FIRST_VISIBLE_NODE",
+ payload: { scrollToNode, scrollToNodeFn },
+ });
+ },
+ [tree, state]
+ );
+
+ const selectLastVisibleNode = useCallback(
+ (scrollToNode = true) => {
+ dispatch({
+ type: "SELECT_LAST_VISIBLE_NODE",
+ payload: { scrollToNode, scrollToNodeFn },
+ });
+ },
+ [tree, state]
+ );
+
+ const selectNextVisibleNode = useCallback(
+ (scrollToNode = true) => {
+ dispatch({
+ type: "SELECT_NEXT_VISIBLE_NODE",
+ payload: { scrollToNode, scrollToNodeFn },
+ });
+ },
+ [state]
+ );
+
+ const selectPreviousVisibleNode = useCallback(
+ (scrollToNode = true) => {
+ dispatch({
+ type: "SELECT_PREVIOUS_VISIBLE_NODE",
+ payload: { scrollToNode, scrollToNodeFn },
+ });
+ },
+ [state]
+ );
+
+ const selectParentNode = useCallback(
+ (scrollToNode = true) => {
+ dispatch({
+ type: "SELECT_PARENT_NODE",
+ payload: { scrollToNode, scrollToNodeFn },
+ });
+ },
+ [state]
+ );
+
+ const expandAllBelowDepth = useCallback(
+ (depth: number) => {
+ dispatch({ type: "EXPAND_ALL_BELOW_DEPTH", payload: { depth } });
+ },
+ [state]
+ );
+
+ const collapseAllBelowDepth = useCallback(
+ (depth: number) => {
+ dispatch({ type: "COLLAPSE_ALL_BELOW_DEPTH", payload: { depth } });
+ },
+ [state]
+ );
+
+ const expandLevel = useCallback(
+ (level: number) => {
+ dispatch({ type: "EXPAND_LEVEL", payload: { level } });
+ },
+ [state]
+ );
+
+ const collapseLevel = useCallback(
+ (level: number) => {
+ dispatch({ type: "COLLAPSE_LEVEL", payload: { level } });
+ },
+ [state]
+ );
+
+ const toggleExpandLevel = useCallback(
+ (level: number) => {
+ dispatch({ type: "TOGGLE_EXPAND_LEVEL", payload: { level } });
+ },
+ [state]
+ );
+
+ const getTreeProps = useCallback(() => {
+ return {
+ role: "tree",
+ "aria-multiselectable": true,
+ tabIndex: -1,
+ onKeyDown: (e: React.KeyboardEvent<HTMLElement>) => {
+ if (e.defaultPrevented) {
+ return; // Do nothing if the event was already processed
+ }
+
+ switch (e.key) {
+ case "Home": {
+ selectFirstVisibleNode(true);
+ e.preventDefault();
+ break;
+ }
+ case "End": {
+ selectLastVisibleNode(true);
+ e.preventDefault();
+ break;
+ }
+ case "Down":
+ case "ArrowDown": {
+ selectNextVisibleNode(true);
+ e.preventDefault();
+ break;
+ }
+ case "Up":
+ case "ArrowUp": {
+ selectPreviousVisibleNode(true);
+ e.preventDefault();
+ break;
+ }
+ case "Left":
+ case "ArrowLeft": {
+ e.preventDefault();
+
+ const selected = selectedIdFromState(state.nodes);
+ if (selected) {
+ const treeNode = tree.find((node) => node.id === selected);
+
+ if (e.altKey) {
+ if (treeNode && treeNode.hasChildren) {
+ collapseLevel(treeNode.level);
+ }
+ break;
+ }
+
+ const shouldCollapse =
+ treeNode &&
+ treeNode.hasChildren &&
+ state.nodes[selected].expanded;
+ if (shouldCollapse) {
+ collapseNode(selected);
+ } else {
+ selectParentNode(true);
+ }
+ }
+
+ break;
+ }
+ case "Right":
+ case "ArrowRight": {
+ e.preventDefault();
+
+ const selected = selectedIdFromState(state.nodes);
+
+ if (selected) {
+ const treeNode = tree.find((node) => node.id === selected);
+
+ if (e.altKey) {
+ if (treeNode && treeNode.hasChildren) {
+ expandLevel(treeNode.level);
+ }
+ break;
+ }
+
+ expandNode(selected, true);
+ }
+ break;
+ }
+ case "Escape": {
+ deselectAllNodes();
+ e.preventDefault();
+ break;
+ }
+ }
+ },
+ };
+ }, [state]);
+
+ const getNodeProps = useCallback(
+ (id: string) => {
+ const node = state.nodes[id];
+ if (!node) return {};
+ const treeItemIndex = tree.findIndex((node) => node.id === id);
+ const treeItem = tree[treeItemIndex];
+ return {
+ "aria-expanded": node.expanded,
+ "aria-level": treeItem.level + 1,
+ role: "treeitem",
+ tabIndex: node.selected ? -1 : undefined,
+ };
+ },
+ [state]
+ );
+
+ return {
+ selected: selectedIdFromState(state.nodes),
+ nodes: state.nodes,
+ getTreeProps,
+ getNodeProps,
+ selectNode,
+ deselectNode,
+ deselectAllNodes,
+ toggleNodeSelection,
+ expandNode,
+ collapseNode,
+ toggleExpandNode,
+ expandAllBelowDepth,
+ collapseAllBelowDepth,
+ expandLevel,
+ collapseLevel,
+ toggleExpandLevel,
+ selectFirstVisibleNode,
+ selectLastVisibleNode,
+ selectNextVisibleNode,
+ selectPreviousVisibleNode,
+ selectParentNode,
+ scrollToNode: scrollToNodeFn,
+ virtualizer,
+ };
+}
+
+/** An actual tree structure with custom data */
+export type Tree<TData> = {
+ id: string;
+ children?: Tree<TData>[];
+ data: TData;
+};
+
+/** A tree but flattened so it can easily be used for DOM elements */
+export type FlatTreeItem<TData> = {
+ id: string;
+ parentId: string | undefined;
+ children: string[];
+ hasChildren: boolean;
+ /** The indentation level, the root is 0 */
+ level: number;
+ data: TData;
+};
+
+export type FlatTree<TData> = FlatTreeItem<TData>[];
+
+export function flattenTree<TData>(tree: Tree<TData>): FlatTree<TData> {
+ const flatTree: FlatTree<TData> = [];
+
+ function flattenNode(
+ node: Tree<TData>,
+ parentId: string | undefined,
+ level: number
+ ) {
+ const children = node.children?.map((child) => child.id) ?? [];
+ flatTree.push({
+ id: node.id,
+ parentId,
+ children,
+ hasChildren: children.length > 0,
+ level,
+ data: node.data,
+ });
+
+ node.children?.forEach((child) => {
+ flattenNode(child, node.id, level + 1);
+ });
+ }
+
+ flattenNode(tree, undefined, 0);
+
+ return flatTree;
+}
+
+type FlatTreeWithoutChildren<TData> = {
+ id: string;
+ parentId: string | undefined;
+ data: TData;
+};
+
+export function createTreeFromFlatItems<TData>(
+ withoutChildren: FlatTreeWithoutChildren<TData>[],
+ rootId: string
+): Tree<TData> | undefined {
+ // Index items by id
+ const indexedItems: { [id: string]: Tree<TData> } = withoutChildren.reduce(
+ (acc, item) => {
+ acc[item.id] = { id: item.id, data: item.data, children: [] };
+ return acc;
+ },
+ {} as { [id: string]: Tree<TData> }
+ );
+
+ // Add items to parent's children array
+ withoutChildren.forEach((item) => {
+ const indexedItem = indexedItems[item.id];
+ if (item.parentId !== undefined) {
+ const parentItem = indexedItems[item.parentId];
+ if (parentItem) {
+ // If parent ID doesn't exist, this is also a root item
+ parentItem.children?.push(indexedItem);
+ }
+ }
+ });
+
+ return indexedItems[rootId];
+}
diff --git a/apps/carbon/app/components/TreeView/index.ts b/apps/carbon/app/components/TreeView/index.ts
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/apps/carbon/app/components/TreeView/reducer.ts b/apps/carbon/app/components/TreeView/reducer.ts
new file mode 100644
index 0000000000..30041850c4
--- /dev/null
+++ b/apps/carbon/app/components/TreeView/reducer.ts
@@ -0,0 +1,586 @@
+import assertNever from "assert-never";
+import type { Filter, FlatTree } from "./TreeView";
+import {
+ applyFilterToState,
+ applyVisibility,
+ collapsedIdsFromState,
+ concreteStateFromInput,
+ firstVisibleNode,
+ generateChanges,
+ lastVisibleNode,
+ selectedIdFromState,
+ visibleNodes,
+} from "./utils";
+
+export type NodeState = {
+ selected: boolean;
+ expanded: boolean;
+ visible: boolean;
+};
+
+export type Changes = {
+ selectedId: string | undefined;
+};
+
+export type TreeState = {
+ tree: FlatTree<any>;
+ nodes: NodesState;
+ filteredNodes: NodesState;
+ changes: Changes;
+ filter: Filter<any, any> | undefined;
+ visibleNodeIds: string[];
+};
+
+export type NodesState = Record<string, NodeState>;
+
+type ScrollToNodeFn = (id: string) => void;
+
+type WithScrollToNode = {
+ scrollToNode: boolean;
+ scrollToNodeFn: ScrollToNodeFn;
+};
+
+type UpdateTreeAction = {
+ type: "UPDATE_TREE";
+ payload: {
+ tree: FlatTree<any>;
+ };
+};
+
+type SelectNodeAction = {
+ type: "SELECT_NODE";
+ payload: {
+ id: string;
+ } & WithScrollToNode;
+};
+
+type DeselectNodeAction = {
+ type: "DESELECT_NODE";
+ payload: {
+ id: string;
+ };
+};
+
+type DeselectAllNodesAction = {
+ type: "DESELECT_ALL_NODES";
+};
+
+type ToggleNodeSelection = {
+ type: "TOGGLE_NODE_SELECTION";
+ payload: {
+ id: string;
+ } & WithScrollToNode;
+};
+
+type ExpandNodeAction = {
+ type: "EXPAND_NODE";
+ payload: {
+ id: string;
+ } & WithScrollToNode;
+};
+
+type CollapseNodeAction = {
+ type: "COLLAPSE_NODE";
+ payload: {
+ id: string;
+ };
+};
+
+type ToggleExpandNodeAction = {
+ type: "TOGGLE_EXPAND_NODE";
+ payload: {
+ id: string;
+ } & WithScrollToNode;
+};
+
+type ExpandAllBelowDepthAction = {
+ type: "EXPAND_ALL_BELOW_DEPTH";
+ payload: {
+ depth: number;
+ };
+};
+
+type CollapseAllBelowDepthAction = {
+ type: "COLLAPSE_ALL_BELOW_DEPTH";
+ payload: {
+ depth: number;
+ };
+};
+
+type ExpandLevelAction = {
+ type: "EXPAND_LEVEL";
+ payload: {
+ level: number;
+ };
+};
+
+type CollapseLevelAction = {
+ type: "COLLAPSE_LEVEL";
+ payload: {
+ level: number;
+ };
+};
+
+type ToggleExpandLevelAction = {
+ type: "TOGGLE_EXPAND_LEVEL";
+ payload: {
+ level: number;
+ };
+};
+
+type SelectFirstVisibleNodeAction = {
+ type: "SELECT_FIRST_VISIBLE_NODE";
+ payload: {} & WithScrollToNode;
+};
+
+type SelectLastVisibleNodeAction = {
+ type: "SELECT_LAST_VISIBLE_NODE";
+ payload: {} & WithScrollToNode;
+};
+
+type SelectNextVisibleNodeAction = {
+ type: "SELECT_NEXT_VISIBLE_NODE";
+ payload: {} & WithScrollToNode;
+};
+
+type SelectPreviousVisibleNodeAction = {
+ type: "SELECT_PREVIOUS_VISIBLE_NODE";
+ payload: {} & WithScrollToNode;
+};
+
+type SelectParentNodeAction = {
+ type: "SELECT_PARENT_NODE";
+ payload: {} & WithScrollToNode;
+};
+
+type UpdateFilterAction = {
+ type: "UPDATE_FILTER";
+ payload: {
+ filter: Filter<any, any> | undefined;
+ };
+};
+
+export type Action =
+ | UpdateTreeAction
+ | SelectNodeAction
+ | DeselectNodeAction
+ | DeselectAllNodesAction
+ | ToggleNodeSelection
+ | ExpandNodeAction
+ | CollapseNodeAction
+ | ToggleExpandNodeAction
+ | ExpandAllBelowDepthAction
+ | CollapseAllBelowDepthAction
+ | ExpandLevelAction
+ | CollapseLevelAction
+ | ToggleExpandLevelAction
+ | SelectFirstVisibleNodeAction
+ | SelectLastVisibleNodeAction
+ | SelectNextVisibleNodeAction
+ | SelectPreviousVisibleNodeAction
+ | SelectParentNodeAction
+ | UpdateFilterAction;
+
+export function reducer(state: TreeState, action: Action): TreeState {
+ switch (action.type) {
+ case "SELECT_NODE": {
+ //if the node was already selected, do nothing. The user needs to use deselectNode to deselect
+ const alreadySelected = state.nodes[action.payload.id]?.selected ?? false;
+ if (alreadySelected) {
+ return state;
+ }
+
+ const newNodes = Object.fromEntries(
+ Object.entries(state.nodes).map(([key, value]) => [
+ key,
+ { ...value, selected: false },
+ ])
+ );
+ newNodes[action.payload.id] = {
+ ...newNodes[action.payload.id],
+ selected: true,
+ };
+
+ if (action.payload.scrollToNode) {
+ action.payload.scrollToNodeFn(action.payload.id);
+ }
+
+ return applyFilterToState({
+ ...state,
+ tree: state.tree,
+ nodes: newNodes,
+ changes: generateChanges(state.nodes, newNodes),
+ });
+ }
+ case "DESELECT_NODE": {
+ const nodes = {
+ ...state.nodes,
+ [action.payload.id]: {
+ ...state.nodes[action.payload.id],
+ selected: false,
+ },
+ };
+
+ return applyFilterToState({
+ ...state,
+ nodes,
+ changes: generateChanges(state.nodes, nodes),
+ });
+ }
+ case "DESELECT_ALL_NODES": {
+ const nodes = Object.fromEntries(
+ Object.entries(state.nodes).map(([key, value]) => [
+ key,
+ { ...value, selected: false },
+ ])
+ );
+ return applyFilterToState({
+ ...state,
+ nodes,
+ changes: generateChanges(state.nodes, nodes),
+ });
+ }
+ case "TOGGLE_NODE_SELECTION": {
+ const currentlySelected =
+ state.nodes[action.payload.id]?.selected ?? false;
+ if (currentlySelected) {
+ return reducer(state, {
+ type: "DESELECT_NODE",
+ payload: { id: action.payload.id },
+ });
+ }
+
+ return reducer(state, {
+ type: "SELECT_NODE",
+ payload: {
+ id: action.payload.id,
+ scrollToNode: action.payload.scrollToNode,
+ scrollToNodeFn: action.payload.scrollToNodeFn,
+ },
+ });
+ }
+ case "EXPAND_NODE": {
+ const newNodes = {
+ ...state.nodes,
+ [action.payload.id]: {
+ ...state.nodes[action.payload.id],
+ expanded: true,
+ },
+ };
+
+ if (action.payload.scrollToNode) {
+ action.payload.scrollToNodeFn(action.payload.id);
+ }
+
+ const visibleNodes = applyVisibility(state.tree, newNodes);
+ return applyFilterToState({
+ ...state,
+ nodes: visibleNodes,
+ changes: generateChanges(state.nodes, visibleNodes),
+ });
+ }
+ case "COLLAPSE_NODE": {
+ const visibleNodes = applyVisibility(state.tree, {
+ ...state.nodes,
+ [action.payload.id]: {
+ ...state.nodes[action.payload.id],
+ expanded: false,
+ },
+ });
+ return applyFilterToState({
+ ...state,
+ nodes: visibleNodes,
+ changes: generateChanges(state.nodes, visibleNodes),
+ });
+ }
+ case "TOGGLE_EXPAND_NODE": {
+ const currentlyExpanded =
+ state.nodes[action.payload.id]?.expanded ?? true;
+ if (currentlyExpanded) {
+ return reducer(state, {
+ type: "COLLAPSE_NODE",
+ payload: { id: action.payload.id },
+ });
+ }
+
+ return reducer(state, {
+ type: "EXPAND_NODE",
+ payload: {
+ id: action.payload.id,
+ scrollToNode: action.payload.scrollToNode,
+ scrollToNodeFn: action.payload.scrollToNodeFn,
+ },
+ });
+ }
+ case "EXPAND_ALL_BELOW_DEPTH": {
+ const nodesToExpand = state.tree.filter(
+ (n) => n.level >= action.payload.depth && n.hasChildren
+ );
+
+ const newNodes = Object.fromEntries(
+ Object.entries(state.nodes).map(([key, value]) => [
+ key,
+ {
+ ...value,
+ expanded: nodesToExpand.find((n) => n.id === key)
+ ? true
+ : value.expanded,
+ },
+ ])
+ );
+
+ const visibleNodes = applyVisibility(state.tree, newNodes);
+ return applyFilterToState({
+ ...state,
+ nodes: visibleNodes,
+ changes: generateChanges(state.nodes, visibleNodes),
+ });
+ }
+ case "COLLAPSE_ALL_BELOW_DEPTH": {
+ const nodesToCollapse = state.tree.filter(
+ (n) => n.level >= action.payload.depth && n.hasChildren
+ );
+
+ const newNodes = Object.fromEntries(
+ Object.entries(state.nodes).map(([key, value]) => [
+ key,
+ {
+ ...value,
+ expanded: nodesToCollapse.find((n) => n.id === key)
+ ? false
+ : value.expanded,
+ },
+ ])
+ );
+
+ const visibleNodes = applyVisibility(state.tree, newNodes);
+ return applyFilterToState({
+ ...state,
+ nodes: visibleNodes,
+ changes: generateChanges(state.nodes, visibleNodes),
+ });
+ }
+ case "EXPAND_LEVEL": {
+ const nodesToExpand = state.tree.filter(
+ (n) => n.level <= action.payload.level && n.hasChildren
+ );
+
+ const newNodes = Object.fromEntries(
+ Object.entries(state.nodes).map(([key, value]) => [
+ key,
+ {
+ ...value,
+ expanded: nodesToExpand.find((n) => n.id === key)
+ ? true
+ : value.expanded,
+ },
+ ])
+ );
+
+ const visibleNodes = applyVisibility(state.tree, newNodes);
+ return applyFilterToState({
+ ...state,
+ nodes: visibleNodes,
+ changes: generateChanges(state.nodes, visibleNodes),
+ });
+ }
+ case "COLLAPSE_LEVEL": {
+ const nodesToCollapse = state.tree.filter(
+ (n) => n.level === action.payload.level && n.hasChildren
+ );
+
+ const newNodes = Object.fromEntries(
+ Object.entries(state.nodes).map(([key, value]) => [
+ key,
+ {
+ ...value,
+ expanded: nodesToCollapse.find((n) => n.id === key)
+ ? false
+ : value.expanded,
+ },
+ ])
+ );
+
+ const visibleNodes = applyVisibility(state.tree, newNodes);
+ return applyFilterToState({
+ ...state,
+ nodes: visibleNodes,
+ changes: generateChanges(state.nodes, visibleNodes),
+ });
+ }
+ case "TOGGLE_EXPAND_LEVEL": {
+ //first get the first item at that level in the tree. If it is expanded, collapse all nodes at that level
+ //if it is collapsed, expand all nodes at that level
+ const nodesAtLevel = state.tree.filter(
+ (n) => n.level === action.payload.level && n.hasChildren
+ );
+ const firstNode = nodesAtLevel[0];
+ if (!firstNode) {
+ return state;
+ }
+
+ const currentlyExpanded = state.nodes[firstNode.id]?.expanded ?? true;
+ const currentVisible = state.nodes[firstNode.id]?.visible ?? true;
+ if (currentlyExpanded && currentVisible) {
+ return reducer(state, {
+ type: "COLLAPSE_LEVEL",
+ payload: {
+ level: action.payload.level,
+ },
+ });
+ }
+
+ return reducer(state, {
+ type: "EXPAND_LEVEL",
+ payload: {
+ level: action.payload.level,
+ },
+ });
+ }
+ case "SELECT_FIRST_VISIBLE_NODE": {
+ const node = firstVisibleNode(state.tree, state.filteredNodes);
+ if (node) {
+ return reducer(state, {
+ type: "SELECT_NODE",
+ payload: {
+ id: node.id,
+ scrollToNode: action.payload.scrollToNode,
+ scrollToNodeFn: action.payload.scrollToNodeFn,
+ },
+ });
+ }
+
+ return state;
+ }
+ case "SELECT_LAST_VISIBLE_NODE": {
+ const node = lastVisibleNode(state.tree, state.filteredNodes);
+ if (node) {
+ return reducer(state, {
+ type: "SELECT_NODE",
+ payload: {
+ id: node.id,
+ scrollToNode: action.payload.scrollToNode,
+ scrollToNodeFn: action.payload.scrollToNodeFn,
+ },
+ });
+ }
+
+ return state;
+ }
+ case "SELECT_NEXT_VISIBLE_NODE": {
+ const selected = selectedIdFromState(state.nodes);
+ if (!selected) {
+ return reducer(state, {
+ type: "SELECT_FIRST_VISIBLE_NODE",
+ payload: {
+ scrollToNode: action.payload.scrollToNode,
+ scrollToNodeFn: action.payload.scrollToNodeFn,
+ },
+ });
+ }
+
+ const visible = visibleNodes(state.tree, state.filteredNodes);
+ const selectedIndex = visible.findIndex((node) => node.id === selected);
+ const nextNode = visible[selectedIndex + 1];
+ if (nextNode) {
+ return reducer(state, {
+ type: "SELECT_NODE",
+ payload: {
+ id: nextNode.id,
+ scrollToNode: action.payload.scrollToNode,
+ scrollToNodeFn: action.payload.scrollToNodeFn,
+ },
+ });
+ }
+
+ return state;
+ }
+ case "SELECT_PREVIOUS_VISIBLE_NODE": {
+ const selected = selectedIdFromState(state.nodes);
+
+ if (!selected) {
+ return reducer(state, {
+ type: "SELECT_FIRST_VISIBLE_NODE",
+ payload: {
+ scrollToNode: action.payload.scrollToNode,
+ scrollToNodeFn: action.payload.scrollToNodeFn,
+ },
+ });
+ }
+
+ const visible = visibleNodes(state.tree, state.filteredNodes);
+ const selectedIndex = visible.findIndex((node) => node.id === selected);
+ const previousNode = visible[Math.max(0, selectedIndex - 1)];
+ if (previousNode) {
+ return reducer(state, {
+ type: "SELECT_NODE",
+ payload: {
+ id: previousNode.id,
+ scrollToNode: action.payload.scrollToNode,
+ scrollToNodeFn: action.payload.scrollToNodeFn,
+ },
+ });
+ }
+
+ return state;
+ }
+ case "SELECT_PARENT_NODE": {
+ const selected = selectedIdFromState(state.nodes);
+
+ if (!selected) {
+ return reducer(state, {
+ type: "SELECT_FIRST_VISIBLE_NODE",
+ payload: {
+ scrollToNode: action.payload.scrollToNode,
+ scrollToNodeFn: action.payload.scrollToNodeFn,
+ },
+ });
+ }
+
+ const selectedNode = state.tree.find((node) => node.id === selected);
+ if (!selectedNode) {
+ return state;
+ }
+
+ const parentNode = state.tree.find(
+ (node) => node.id === selectedNode.parentId
+ );
+ if (parentNode) {
+ return reducer(state, {
+ type: "SELECT_NODE",
+ payload: {
+ id: parentNode.id,
+ scrollToNode: action.payload.scrollToNode,
+ scrollToNodeFn: action.payload.scrollToNodeFn,
+ },
+ });
+ }
+
+ return state;
+ }
+ case "UPDATE_TREE": {
+ //update the tree but try and keep the selected and expanded states
+ const selectedId = selectedIdFromState(state.nodes);
+ const collapsedIds = collapsedIdsFromState(state.nodes);
+ const newState = concreteStateFromInput({
+ ...state,
+ tree: action.payload.tree,
+ selectedId,
+ collapsedIds,
+ });
+ return newState;
+ }
+ case "UPDATE_FILTER": {
+ const newState = applyFilterToState({
+ ...state,
+ filter: action.payload.filter,
+ });
+ return newState;
+ }
+ default: {
+ assertNever(action);
+ }
+ }
+
+ throw new Error(`Unhandled action type: ${(action as any).type}`);
+}
diff --git a/apps/carbon/app/components/TreeView/utils.ts b/apps/carbon/app/components/TreeView/utils.ts
new file mode 100644
index 0000000000..1d430e4b58
--- /dev/null
+++ b/apps/carbon/app/components/TreeView/utils.ts
@@ -0,0 +1,256 @@
+import type { Filter, FlatTree } from "./TreeView";
+import type { Changes, NodeState, NodesState, TreeState } from "./reducer";
+
+type PartialNodeState = Record<string, Partial<NodeState>>;
+
+const defaultSelected = false;
+const defaultExpanded = true;
+
+export function concreteStateFromInput({
+ tree,
+ filter,
+ selectedId,
+ collapsedIds,
+}: {
+ tree: FlatTree<any>;
+ filter: Filter<any, any> | undefined;
+ selectedId: string | undefined;
+ collapsedIds: string[] | undefined;
+}): TreeState {
+ const state: PartialNodeState = {};
+ collapsedIds?.forEach((id) => {
+ const hasTreeItem = tree.some((item) => item.id === id);
+ if (hasTreeItem) {
+ state[id] = { expanded: false };
+ }
+ });
+ if (selectedId) {
+ const selectedNode = tree.find((node) => node.id === selectedId);
+ if (selectedNode) {
+ state[selectedId] = { selected: true };
+ //make sure all parents are expanded
+ let parentId = selectedNode.parentId;
+ while (parentId) {
+ state[parentId] = { expanded: true };
+ const parent = tree.find((node) => node.id === parentId);
+ parentId = parent?.parentId;
+ }
+ }
+ }
+ const nodes = concreteStateFromPartialState(tree, state);
+
+ return {
+ tree,
+ nodes,
+ changes: { selectedId },
+ filter,
+ filteredNodes: nodes,
+ visibleNodeIds: visibleNodes(tree, nodes).map((node) => node.id),
+ };
+}
+
+export function concreteStateFromPartialState<TData>(
+ tree: FlatTree<TData>,
+ state: PartialNodeState
+): NodesState {
+ const concreteState = tree.reduce((acc, node) => {
+ acc[node.id] = {
+ selected: acc[node.id]?.selected ?? defaultSelected,
+ expanded: acc[node.id]?.expanded ?? defaultExpanded,
+ visible: acc[node.id]?.visible ?? true,
+ };
+ return acc;
+ }, state as Record<string, NodeState>);
+
+ return applyVisibility(tree, concreteState);
+}
+
+export function applyVisibility<TData>(
+ tree: FlatTree<TData>,
+ state: NodesState
+): NodesState {
+ const newState = tree.reduce((acc, node) => {
+ //groups are open by default
+ const nodeState = state[node.id] ?? {
+ selected: defaultSelected,
+ expanded: node.hasChildren ? defaultExpanded : !defaultExpanded,
+ };
+ const parent = node.parentId
+ ? acc[node.parentId]
+ : { selected: defaultSelected, expanded: defaultExpanded, visible: true };
+ const visible = parent.expanded && parent.visible === true ? true : false;
+ acc[node.id] = { ...nodeState, visible };
+
+ return acc;
+ }, {} as NodesState);
+
+ return newState;
+}
+
+export function selectedIdFromState(state: NodesState): string | undefined {
+ const selected = Object.entries(state).find(([id, node]) => node.selected);
+ return selected?.[0];
+}
+
+export function applyFilterToState<TData>({
+ tree,
+ nodes,
+ filter,
+ visibleNodeIds,
+ changes,
+}: TreeState): TreeState {
+ if (!filter || !filter.value) {
+ return {
+ tree,
+ nodes,
+ filteredNodes: nodes,
+ changes,
+ filter,
+ visibleNodeIds: visibleNodes(tree, nodes).map((node) => node.id),
+ };
+ }
+
+ //we need to do two passes, first collect all the nodes that are results
+ const newFilteredOut = new Set<string>();
+ for (const node of tree) {
+ if (!filter.fn(filter.value, node)) {
+ newFilteredOut.add(node.id);
+ }
+ }
+
+ //nothing is filtered out
+ if (newFilteredOut.size === 0) {
+ return {
+ tree,
+ nodes,
+ filteredNodes: nodes,
+ changes,
+ filter,
+ visibleNodeIds: visibleNodes(tree, nodes).map((node) => node.id),
+ };
+ }
+
+ //copy of nodes
+ const filteredNodes = { ...nodes };
+
+ const selected = selectedIdFromState(filteredNodes);
+
+ const visible = new Set<string>();
+ const expanded = new Set<string>();
+
+ //figure out the state of each node
+ for (const node of tree) {
+ const shouldDisplay = !newFilteredOut.has(node.id);
+
+ //if the node is visible, make all the parents visible and expanded
+ if (shouldDisplay) {
+ //should be visible
+ visible.add(node.id);
+ //if it has children it should be expanded
+ if (node.hasChildren) {
+ expanded.add(node.id);
+ }
+
+ //parents need to be both visible and expanded
+ let parentId = node.parentId;
+ while (parentId) {
+ visible.add(parentId);
+ expanded.add(parentId);
+ parentId = tree.find((node) => node.id === parentId)?.parentId;
+ }
+
+ //children should be visible and if they have children expanded
+ if (node.hasChildren) {
+ const children = tree.filter((child) => child.parentId === node.id);
+ for (const child of children) {
+ visible.add(child.id);
+ if (child.hasChildren) {
+ expanded.add(child.id);
+ }
+ }
+ }
+ }
+ }
+
+ const allItems = new Set(tree.map((node) => node.id));
+ const hidden = difference(allItems, visible);
+ const collapsed = difference(visible, expanded);
+
+ //now set the visibility and expanded state
+ for (const id of hidden) {
+ filteredNodes[id] = { ...filteredNodes[id], visible: false };
+ }
+ for (const id of visible) {
+ filteredNodes[id] = { ...filteredNodes[id], visible: true };
+ }
+
+ for (const id of collapsed) {
+ filteredNodes[id] = { ...filteredNodes[id], expanded: false };
+ }
+ for (const id of expanded) {
+ filteredNodes[id] = { ...filteredNodes[id], expanded: true };
+ }
+
+ if (selected) {
+ if (visible.has(selected)) {
+ filteredNodes[selected] = { ...filteredNodes[selected], selected: true };
+ } else {
+ filteredNodes[selected] = { ...filteredNodes[selected], selected: false };
+ }
+ }
+
+ return {
+ tree,
+ nodes,
+ filteredNodes,
+ changes,
+ filter,
+ visibleNodeIds: visibleNodes(tree, filteredNodes).map((node) => node.id),
+ };
+}
+
+export function visibleNodes(tree: FlatTree<any>, nodes: NodesState) {
+ return tree.filter((node) => nodes[node.id].visible === true);
+}
+
+export function firstVisibleNode(tree: FlatTree<any>, nodes: NodesState) {
+ return tree.find((node) => nodes[node.id].visible === true);
+}
+
+export function lastVisibleNode(tree: FlatTree<any>, nodes: NodesState) {
+ return tree
+ .slice()
+ .reverse()
+ .find((node) => nodes[node.id].visible === true);
+}
+
+function areSetsEqual<T>(a: Set<T>, b: Set<T>): boolean {
+ return a.size === b.size && [...a].every((value) => b.has(value));
+}
+
+function difference<T>(a: Set<T>, b: Set<T>): Set<T> {
+ return new Set([...a].filter((x) => !b.has(x)));
+}
+
+export function collapsedIdsFromState(state: NodesState): string[] {
+ return Object.entries(state)
+ .filter(([_, s]) => s.expanded === false)
+ .map(([id]) => id);
+}
+
+export function generateChanges(a: NodesState, b: NodesState): Changes {
+ //if selected === defaultSelected, remove it
+ //if expanded === defaultExpanded, remove it
+ //if both are default, remove the node
+ const selectedIdA = selectedIdFromState(a);
+ const selectedIdB = selectedIdFromState(b);
+
+ const collapsedIdsA = new Set(collapsedIdsFromState(a));
+ const collapsedIdsB = new Set(collapsedIdsFromState(b));
+
+ const collapsedChanges = [...difference(collapsedIdsA, collapsedIdsB)];
+
+ return {
+ selectedId: selectedIdA !== selectedIdB ? selectedIdB : undefined,
+ };
+}
diff --git a/apps/carbon/app/hooks/useRealtime.tsx b/apps/carbon/app/hooks/useRealtime.tsx
index 8224fbd455..e65a19967b 100644
--- a/apps/carbon/app/hooks/useRealtime.tsx
+++ b/apps/carbon/app/hooks/useRealtime.tsx
@@ -37,13 +37,7 @@ export function useRealtime(table: string, filter?: string) {
return () => {
if (channel) supabase?.removeChannel(channel);
};
- }, [
- revalidator.revalidate,
- supabase,
- table,
- filter,
- accessToken,
- revalidator,
- company.id,
- ]);
+ // Don't put the revalidator in the deps array
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [supabase, table, filter, accessToken, company.id]);
}
diff --git a/apps/carbon/app/hooks/useReplaceLocation.tsx b/apps/carbon/app/hooks/useReplaceLocation.tsx
new file mode 100644
index 0000000000..911c68b64c
--- /dev/null
+++ b/apps/carbon/app/hooks/useReplaceLocation.tsx
@@ -0,0 +1,35 @@
+import type { Location } from "@remix-run/react";
+import { useCallback, useState } from "react";
+import { useOptimisticLocation } from "./useOptimisticLocation";
+
+export function useReplaceLocation() {
+ const optimisticLocation = useOptimisticLocation();
+ const [location, setLocation] = useState(optimisticLocation);
+
+ const replaceLocation = useCallback((location: Location<any>) => {
+ const fullPath = location.pathname + location.search + location.hash;
+ //replace the URL in the browser
+ history.replaceState(null, "", fullPath);
+ //update the state (new object in case the same location ref was modified)
+ const newLocation = { ...location };
+ setLocation(newLocation);
+ }, []);
+
+ const replaceSearchParam = useCallback(
+ (key: string, value?: string) => {
+ const searchParams = new URLSearchParams(location.search);
+ if (value) {
+ searchParams.set(key, value);
+ } else {
+ searchParams.delete(key);
+ }
+ replaceLocation({
+ ...optimisticLocation,
+ search: "?" + searchParams.toString(),
+ });
+ },
+ [optimisticLocation, replaceLocation]
+ );
+
+ return { location, replaceLocation, replaceSearchParam };
+}
diff --git a/apps/carbon/app/modules/documents/ui/Documents/DocumentsTable.tsx b/apps/carbon/app/modules/documents/ui/Documents/DocumentsTable.tsx
index 42ba67aa36..9f255a1a01 100644
--- a/apps/carbon/app/modules/documents/ui/Documents/DocumentsTable.tsx
+++ b/apps/carbon/app/modules/documents/ui/Documents/DocumentsTable.tsx
@@ -355,6 +355,8 @@ const DocumentsTable = memo(
cell: (item) => formatDate(item.getValue<string>()),
},
];
+ // Don't put the revalidator in the deps array
+ // eslint-disable-next-line react-hooks/exhaustive-deps
}, [
extensions,
labelOptions,
@@ -362,7 +364,6 @@ const DocumentsTable = memo(
onFavorite,
onLabel,
people,
- revalidator,
setLabel,
view,
]);
diff --git a/apps/carbon/app/modules/resources/ui/useResourcesSubmodules.tsx b/apps/carbon/app/modules/resources/ui/useResourcesSubmodules.tsx
index c704e5a4b0..53801ad7ca 100644
--- a/apps/carbon/app/modules/resources/ui/useResourcesSubmodules.tsx
+++ b/apps/carbon/app/modules/resources/ui/useResourcesSubmodules.tsx
@@ -1,11 +1,8 @@
-import { FaPeopleArrows } from "react-icons/fa";
import {
LuCalendarClock,
LuCalendarHeart,
LuGroup,
LuHammer,
- LuHardHat,
- LuListChecks,
LuMapPin,
LuNetwork,
LuShapes,
@@ -23,16 +20,16 @@ const resourcesRoutes: RouteGroup[] = [
to: path.to.people,
icon: <LuUsers />,
},
- {
- name: "Contractors",
- to: path.to.contractors,
- icon: <LuHardHat />,
- },
- {
- name: "Partners",
- to: path.to.partners,
- icon: <FaPeopleArrows />,
- },
+ // {
+ // name: "Contractors",
+ // to: path.to.contractors,
+ // icon: <LuHardHat />,
+ // },
+ // {
+ // name: "Partners",
+ // to: path.to.partners,
+ // icon: <FaPeopleArrows />,
+ // },
{
name: "Work Cells",
to: path.to.workCells,
@@ -53,11 +50,11 @@ const resourcesRoutes: RouteGroup[] = [
to: path.to.abilities,
icon: <LuHammer />,
},
- {
- name: "Attributes",
- to: path.to.attributes,
- icon: <LuListChecks />,
- },
+ // {
+ // name: "Attributes",
+ // to: path.to.attributes,
+ // icon: <LuListChecks />,
+ // },
{
name: "Departments",
to: path.to.departments,
diff --git a/apps/carbon/app/modules/settings/ui/useSettingsSubmodules.tsx b/apps/carbon/app/modules/settings/ui/useSettingsSubmodules.tsx
index dfb72fb675..8394ab0e3e 100644
--- a/apps/carbon/app/modules/settings/ui/useSettingsSubmodules.tsx
+++ b/apps/carbon/app/modules/settings/ui/useSettingsSubmodules.tsx
@@ -1,5 +1,4 @@
-import { LuFactory, LuSheet, LuWorkflow } from "react-icons/lu";
-import { MdOutlineDashboardCustomize } from "react-icons/md";
+import { LuFactory } from "react-icons/lu";
import { usePermissions } from "~/hooks";
import type { AuthenticatedRouteGroup } from "~/types";
import { path } from "~/utils/path";
@@ -16,29 +15,29 @@ const settingsRoutes: AuthenticatedRouteGroup[] = [
},
],
},
- {
- name: "System",
- routes: [
- {
- name: "Custom Fields",
- to: path.to.customFields,
- role: "employee",
- icon: <MdOutlineDashboardCustomize />,
- },
- {
- name: "Integrations",
- to: path.to.integrations,
- role: "employee",
- icon: <LuWorkflow />,
- },
- {
- name: "Sequences",
- to: path.to.sequences,
- role: "employee",
- icon: <LuSheet />,
- },
- ],
- },
+ // {
+ // name: "System",
+ // routes: [
+ // {
+ // name: "Custom Fields",
+ // to: path.to.customFields,
+ // role: "employee",
+ // icon: <MdOutlineDashboardCustomize />,
+ // },
+ // {
+ // name: "Integrations",
+ // to: path.to.integrations,
+ // role: "employee",
+ // icon: <LuWorkflow />,
+ // },
+ // {
+ // name: "Sequences",
+ // to: path.to.sequences,
+ // role: "employee",
+ // icon: <LuSheet />,
+ // },
+ // ],
+ // },
];
export default function usePurchasingSubmodules() {
diff --git a/apps/carbon/app/modules/users/ui/useUsersSubmodules.tsx b/apps/carbon/app/modules/users/ui/useUsersSubmodules.tsx
index a733a91085..a887d57090 100644
--- a/apps/carbon/app/modules/users/ui/useUsersSubmodules.tsx
+++ b/apps/carbon/app/modules/users/ui/useUsersSubmodules.tsx
@@ -1,10 +1,4 @@
-import {
- LuContainer,
- LuFileBadge2,
- LuGroup,
- LuUserSquare,
- LuUsers,
-} from "react-icons/lu";
+import { LuFileBadge2, LuGroup, LuUsers } from "react-icons/lu";
import type { RouteGroup } from "~/types";
import { path } from "~/utils/path";
@@ -17,16 +11,16 @@ const usersRoutes: RouteGroup[] = [
to: path.to.employeeAccounts,
icon: <LuUsers />,
},
- {
- name: "Customers",
- to: path.to.customerAccounts,
- icon: <LuUserSquare />,
- },
- {
- name: "Suppliers",
- to: path.to.supplierAccounts,
- icon: <LuContainer />,
- },
+ // {
+ // name: "Customers",
+ // to: path.to.customerAccounts,
+ // icon: <LuUserSquare />,
+ // },
+ // {
+ // name: "Suppliers",
+ // to: path.to.supplierAccounts,
+ // icon: <LuContainer />,
+ // },
{
name: "Groups",
to: path.to.groups,
diff --git a/apps/carbon/app/modules/users/users.service.ts b/apps/carbon/app/modules/users/users.service.ts
index 68adc5a428..21735431f8 100644
--- a/apps/carbon/app/modules/users/users.service.ts
+++ b/apps/carbon/app/modules/users/users.service.ts
@@ -91,7 +91,7 @@ export async function getEmployees(
.eq("companyId", companyId);
if (args.search) {
- query = query.ilike("fullName", `%${args.search}%`);
+ query = query.ilike("name", `%${args.search}%`);
}
query = setGenericQueryFilters(query, args, [
diff --git a/apps/carbon/app/routes/x+/scheduling+/index.tsx b/apps/carbon/app/routes/x+/scheduling+/index.tsx
new file mode 100644
index 0000000000..aa010e5481
--- /dev/null
+++ b/apps/carbon/app/routes/x+/scheduling+/index.tsx
@@ -0,0 +1,1061 @@
+import {
+ Badge,
+ Heading,
+ Input,
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+ ResizableHandle,
+ ResizablePanel,
+ ResizablePanelGroup,
+ cn,
+ useDebounce,
+ useKeyboardShortcuts,
+} from "@carbon/react";
+import type { Location } from "@remix-run/react";
+import { useLoaderData, useParams } from "@remix-run/react";
+import type { LoaderFunctionArgs } from "@remix-run/server-runtime";
+import type { Virtualizer } from "@tanstack/react-virtual";
+import {
+ formatDurationMilliseconds,
+ millisecondsToNanoseconds,
+ nanosecondsToMilliseconds,
+} from "@trigger.dev/core/v3";
+import { motion } from "framer-motion";
+import { useCallback, useEffect, useRef, useState } from "react";
+import {
+ LuChevronDown,
+ LuChevronUp,
+ LuZoomIn,
+ LuZoomOut,
+} from "react-icons/lu";
+
+import {
+ ShowParentIcon,
+ ShowParentIconSelected,
+} from "~/assets/icons/ShowParentIcon";
+import tileBgPath from "~/assets/images/[email protected]";
+
+import { PageBody } from "~/components/layout/AppLayout";
+
+import {
+ NavBar,
+ PageAccessories,
+ PageTitle,
+} from "~/components/primitives/PageHeader";
+import { Paragraph } from "~/components/primitives/Paragraph";
+
+import { lerp } from "@carbon/utils";
+import * as Timeline from "~/components/Timeline";
+import type { UseTreeStateOutput } from "~/components/TreeView/TreeView";
+import { TreeView, useTree } from "~/components/TreeView/TreeView";
+import type { NodesState } from "~/components/TreeView/reducer";
+import { Property, PropertyTable } from "~/components/primitives/PropertyTable";
+import { ShortcutKey, variants } from "~/components/primitives/ShortcutKey";
+import { Slider } from "~/components/primitives/Slider";
+import { Switch } from "~/components/primitives/Switch";
+import { RunIcon } from "~/components/runs/v3/RunIcon";
+import {
+ SpanTitle,
+ eventBackgroundClassName,
+} from "~/components/runs/v3/SpanTitle";
+import {
+ TaskRunStatusIcon,
+ runStatusClassNameColor,
+} from "~/components/runs/v3/TaskRunStatus";
+import { useInitialDimensions } from "~/hooks/useInitialDimensions";
+import { useReplaceLocation } from "~/hooks/useReplaceLocation";
+import type { Shortcut } from "~/hooks/useShortcutKeys";
+import { useShortcutKeys } from "~/hooks/useShortcutKeys";
+import { useUser } from "~/hooks/useUser";
+import type { RunEvent } from "~/presenters/v3/RunPresenter.server";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { setResizableRunSettings } from "~/services/resizablePanel";
+import { path } from "~/utils/path";
+import { v3RunPath, v3RunSpanPath } from "~/utils/pathBuilder";
+import { SpanView } from "../resources.orgs.$organizationSlug.projects.v3.$projectParam.runs.$runParam.spans.$spanParam/route";
+
+export const loader = async ({ request, params }: LoaderFunctionArgs) => {
+ const { companyId, userId } = await requirePermissions(request, {
+ view: "scheduling",
+ });
+
+ console.log({ companyId, userId });
+
+ return {
+ data: [],
+ };
+};
+
+function getSpanId(location: Location<any>): string | undefined {
+ const search = new URLSearchParams(location.search);
+ return search.get("span") ?? undefined;
+}
+
+export default function Page() {
+ const { data } = useLoaderData<typeof loader>();
+ const user = useUser();
+ const { location, replaceSearchParam } = useReplaceLocation();
+ const selectedSpanId = getSpanId(location);
+
+ const {
+ events,
+ parentRunFriendlyId,
+ duration,
+ rootSpanStatus,
+ rootStartedAt,
+ } = trace;
+
+ const changeToSpan = useDebounce((selectedSpan: string) => {
+ replaceSearchParam("span", selectedSpan);
+ }, 250);
+
+ return (
+ <>
+ <NavBar>
+ <PageTitle
+ backButton={{
+ to: path.to.authenticatedRoot,
+ text: "Jobs",
+ }}
+ title={`Job #${1234}`}
+ />
+ <PageAccessories>
+ <PropertyTable>
+ <Property label="ID">
+ <div className="flex items-center gap-2">
+ <Paragraph variant="extra-small/bright/mono">ID</Paragraph>
+ </div>
+ </Property>
+ <Property label="Trace ID">
+ <div className="flex items-center gap-2">
+ <Paragraph variant="extra-small/bright/mono">
+ Trace ID
+ </Paragraph>
+ </div>
+ </Property>
+ </PropertyTable>
+ </PageAccessories>
+ </NavBar>
+ <PageBody scrollable={false}>
+ <div
+ className={cn("grid h-full max-h-full grid-cols-1 overflow-hidden")}
+ >
+ <ResizablePanelGroup
+ direction="horizontal"
+ className="h-full max-h-full"
+ onLayout={(layout) => {
+ if (layout.length !== 2) return;
+ if (!selectedSpanId) return;
+ setResizableRunSettings(document, layout);
+ }}
+ >
+ <ResizablePanel
+ order={1}
+ minSize={30}
+ defaultSize={resizeSettings.layout?.[0]}
+ >
+ <TasksTreeView
+ selectedId={selectedSpanId}
+ key={events[0]?.id ?? "-"}
+ events={events}
+ parentRunFriendlyId={parentRunFriendlyId}
+ onSelectedIdChanged={(selectedSpan) => {
+ //instantly close the panel if no span is selected
+ if (!selectedSpan) {
+ replaceSearchParam("span");
+ return;
+ }
+
+ changeToSpan(selectedSpan);
+ }}
+ totalDuration={duration}
+ rootSpanStatus={rootSpanStatus}
+ rootStartedAt={rootStartedAt}
+ />
+ </ResizablePanel>
+ <ResizableHandle withHandle />
+ {selectedSpanId && (
+ <ResizablePanel
+ order={2}
+ minSize={30}
+ defaultSize={resizeSettings.layout?.[1]}
+ >
+ <SpanView
+ runParam={run.friendlyId}
+ spanId={selectedSpanId}
+ closePanel={() => replaceSearchParam("span")}
+ />
+ </ResizablePanel>
+ )}
+ </ResizablePanelGroup>
+ </div>
+ </PageBody>
+ </>
+ );
+}
+
+type TasksTreeViewProps = {
+ events: RunEvent[];
+ selectedId?: string;
+ parentRunFriendlyId?: string;
+ onSelectedIdChanged: (selectedId: string | undefined) => void;
+ totalDuration: number;
+ rootSpanStatus: "executing" | "completed" | "failed";
+ rootStartedAt: Date | undefined;
+};
+
+function TasksTreeView({
+ events,
+ selectedId,
+ parentRunFriendlyId,
+ onSelectedIdChanged,
+ totalDuration,
+ rootSpanStatus,
+ rootStartedAt,
+}: TasksTreeViewProps) {
+ const [filterText, setFilterText] = useState("");
+ const [errorsOnly, setErrorsOnly] = useState(false);
+ const [showDurations, setShowDurations] = useState(false);
+ const [scale, setScale] = useState(0);
+ const parentRef = useRef<HTMLDivElement>(null);
+ const treeScrollRef = useRef<HTMLDivElement>(null);
+ const timelineScrollRef = useRef<HTMLDivElement>(null);
+
+ const {
+ nodes,
+ getTreeProps,
+ getNodeProps,
+ toggleNodeSelection,
+ toggleExpandNode,
+ expandAllBelowDepth,
+ toggleExpandLevel,
+ collapseAllBelowDepth,
+ selectNode,
+ scrollToNode,
+ virtualizer,
+ } = useTree({
+ tree: events,
+ selectedId,
+ // collapsedIds,
+ onSelectedIdChanged,
+ estimatedRowHeight: () => 32,
+ parentRef,
+ filter: {
+ value: { text: filterText, errorsOnly },
+ fn: (value, node) => {
+ const nodePassesErrorTest =
+ (value.errorsOnly && node.data.isError) || !value.errorsOnly;
+ if (!nodePassesErrorTest) return false;
+
+ if (value.text === "") return true;
+ if (
+ node.data.message.toLowerCase().includes(value.text.toLowerCase())
+ ) {
+ return true;
+ }
+ return false;
+ },
+ },
+ });
+
+ return (
+ <div className="grid h-full grid-rows-[2.5rem_1fr_3.25rem] overflow-hidden">
+ <div className="mx-3 flex items-center justify-between gap-2 border-b border-grid-dimmed">
+ <SearchField onChange={setFilterText} />
+ <div className="flex items-center gap-2">
+ <Switch
+ variant="small"
+ label="Errors only"
+ checked={errorsOnly}
+ onCheckedChange={(e) => setErrorsOnly(e.valueOf())}
+ />
+ </div>
+ </div>
+ <ResizablePanelGroup
+ direction="horizontal"
+ onLayout={(layout) => {
+ if (layout.length !== 2) return;
+ setResizableRunSettings(document, layout);
+ }}
+ >
+ {/* Tree list */}
+ <ResizablePanel
+ order={1}
+ minSize={20}
+ defaultSize={50}
+ className="pl-3"
+ >
+ <div className="grid h-full grid-rows-[2rem_1fr] overflow-hidden">
+ <div className="flex items-center pr-2">
+ {parentRunFriendlyId ? (
+ <ShowParentLink runFriendlyId={parentRunFriendlyId} />
+ ) : (
+ <Paragraph variant="small" className="flex-1 text-charcoal-500">
+ This is the root task
+ </Paragraph>
+ )}
+ <LiveReloadingStatus
+ rootSpanCompleted={rootSpanStatus !== "executing"}
+ />
+ </div>
+ <TreeView
+ parentRef={parentRef}
+ scrollRef={treeScrollRef}
+ virtualizer={virtualizer}
+ autoFocus
+ tree={events}
+ nodes={nodes}
+ getNodeProps={getNodeProps}
+ getTreeProps={getTreeProps}
+ renderNode={({ node, state }) => (
+ <>
+ <div
+ className={cn(
+ "flex h-8 cursor-pointer items-center overflow-hidden rounded-l-sm pr-2",
+ state.selected
+ ? "bg-grid-dimmed hover:bg-grid-bright"
+ : "bg-transparent hover:bg-grid-dimmed"
+ )}
+ onClick={() => {
+ selectNode(node.id);
+ }}
+ >
+ <div className="flex h-8 items-center">
+ {Array.from({ length: node.level }).map((_, index) => (
+ <TaskLine
+ key={index}
+ isError={node.data.isError}
+ isSelected={state.selected}
+ />
+ ))}
+ <div
+ className={cn(
+ "flex h-8 w-4 items-center",
+ node.hasChildren && "hover:bg-charcoal-600"
+ )}
+ onClick={(e) => {
+ e.stopPropagation();
+ if (e.altKey) {
+ if (state.expanded) {
+ collapseAllBelowDepth(node.level);
+ } else {
+ expandAllBelowDepth(node.level);
+ }
+ } else {
+ toggleExpandNode(node.id);
+ }
+ scrollToNode(node.id);
+ }}
+ >
+ {node.hasChildren ? (
+ state.expanded ? (
+ <LuChevronDown className="h-4 w-4 text-charcoal-400" />
+ ) : (
+ <LuChevronUp className="h-4 w-4 text-charcoal-400" />
+ )
+ ) : (
+ <div className="h-8 w-4" />
+ )}
+ </div>
+ </div>
+
+ <div className="flex w-full items-center justify-between gap-2 pl-1">
+ <div className="flex items-center gap-2 overflow-x-hidden">
+ <RunIcon
+ name={node.data.style?.icon}
+ spanName={node.data.message}
+ className="h-4 min-h-4 w-4 min-w-4"
+ />
+ <NodeText node={node} />
+ {node.data.isRoot && (
+ <Badge variant="outline">Root</Badge>
+ )}
+ </div>
+ <div className="flex items-center gap-1">
+ <NodeStatusIcon node={node} />
+ </div>
+ </div>
+ </div>
+ </>
+ )}
+ onScroll={(scrollTop) => {
+ //sync the scroll to the tree
+ if (timelineScrollRef.current) {
+ timelineScrollRef.current.scrollTop = scrollTop;
+ }
+ }}
+ />
+ </div>
+ </ResizablePanel>
+ <ResizableHandle withHandle />
+ {/* Timeline */}
+ <ResizablePanel order={2} minSize={20} defaultSize={50}>
+ <TimelineView
+ totalDuration={totalDuration}
+ scale={scale}
+ events={events}
+ rootSpanStatus={rootSpanStatus}
+ rootStartedAt={rootStartedAt}
+ parentRef={parentRef}
+ timelineScrollRef={timelineScrollRef}
+ nodes={nodes}
+ getNodeProps={getNodeProps}
+ getTreeProps={getTreeProps}
+ showDurations={showDurations}
+ treeScrollRef={treeScrollRef}
+ virtualizer={virtualizer}
+ toggleNodeSelection={toggleNodeSelection}
+ />
+ </ResizablePanel>
+ </ResizablePanelGroup>
+ <div className="flex items-center justify-between gap-2 border-t border-grid-dimmed px-2">
+ <div className="grow @container">
+ <div className="hidden items-center gap-4 @[42rem]:flex">
+ <KeyboardShortcuts
+ expandAllBelowDepth={expandAllBelowDepth}
+ collapseAllBelowDepth={collapseAllBelowDepth}
+ toggleExpandLevel={toggleExpandLevel}
+ setShowDurations={setShowDurations}
+ />
+ </div>
+ <div className="@[42rem]:hidden">
+ <Popover>
+ <PopoverTrigger>Shortcuts</PopoverTrigger>
+ <PopoverContent
+ className="min-w-[20rem] overflow-y-auto p-2 scrollbar-thin scrollbar-track-transparent scrollbar-thumb-charcoal-600"
+ align="start"
+ >
+ <Heading size="h3">Keyboard shortcuts</Heading>
+ <div className="flex flex-col gap-2">
+ <KeyboardShortcuts
+ expandAllBelowDepth={expandAllBelowDepth}
+ collapseAllBelowDepth={collapseAllBelowDepth}
+ toggleExpandLevel={toggleExpandLevel}
+ setShowDurations={setShowDurations}
+ />
+ </div>
+ </PopoverContent>
+ </Popover>
+ </div>
+ </div>
+ <div className="flex items-center gap-4">
+ <Slider
+ variant={"tertiary"}
+ className="w-20"
+ LeadingIcon={LuZoomOut}
+ TrailingIcon={LuZoomIn}
+ value={[scale]}
+ onValueChange={(value) => setScale(value[0])}
+ min={0}
+ max={1}
+ step={0.05}
+ />
+ </div>
+ </div>
+ </div>
+ );
+}
+
+type TimelineViewProps = Pick<
+ TasksTreeViewProps,
+ "totalDuration" | "rootSpanStatus" | "events" | "rootStartedAt"
+> & {
+ scale: number;
+ parentRef: React.RefObject<HTMLDivElement>;
+ timelineScrollRef: React.RefObject<HTMLDivElement>;
+ virtualizer: Virtualizer<HTMLElement, Element>;
+ nodes: NodesState;
+ getNodeProps: UseTreeStateOutput["getNodeProps"];
+ getTreeProps: UseTreeStateOutput["getTreeProps"];
+ toggleNodeSelection: UseTreeStateOutput["toggleNodeSelection"];
+ showDurations: boolean;
+ treeScrollRef: React.RefObject<HTMLDivElement>;
+};
+
+const tickCount = 5;
+
+function TimelineView({
+ totalDuration,
+ scale,
+ rootSpanStatus,
+ rootStartedAt,
+ parentRef,
+ timelineScrollRef,
+ virtualizer,
+ events,
+ nodes,
+ getNodeProps,
+ getTreeProps,
+ toggleNodeSelection,
+ showDurations,
+ treeScrollRef,
+}: TimelineViewProps) {
+ const timelineContainerRef = useRef<HTMLDivElement>(null);
+ const initialTimelineDimensions = useInitialDimensions(timelineContainerRef);
+ const minTimelineWidth = initialTimelineDimensions?.width ?? 300;
+ const maxTimelineWidth = minTimelineWidth * 10;
+
+ //we want to live-update the duration if the root span is still executing
+ const [duration, setDuration] = useState(totalDuration);
+ useEffect(() => {
+ if (rootSpanStatus !== "executing" || !rootStartedAt) {
+ setDuration(totalDuration);
+ return;
+ }
+
+ const interval = setInterval(() => {
+ setDuration(
+ millisecondsToNanoseconds(Date.now() - rootStartedAt.getTime())
+ );
+ }, 500);
+
+ return () => clearInterval(interval);
+ }, [totalDuration, rootSpanStatus]);
+
+ return (
+ <div
+ className="h-full overflow-x-auto overflow-y-hidden scrollbar-thin scrollbar-track-transparent scrollbar-thumb-charcoal-600"
+ ref={timelineContainerRef}
+ >
+ <Timeline.Root
+ durationMs={nanosecondsToMilliseconds(duration * 1.05)}
+ scale={scale}
+ className="h-full overflow-hidden"
+ minWidth={minTimelineWidth}
+ maxWidth={maxTimelineWidth}
+ >
+ {/* Follows the cursor */}
+ <CurrentTimeIndicator totalDuration={duration} />
+
+ <Timeline.Row className="grid h-full grid-rows-[2rem_1fr]">
+ {/* The duration labels */}
+ <Timeline.Row>
+ <Timeline.Row className="h-6">
+ <Timeline.EquallyDistribute count={tickCount}>
+ {(ms: number, index: number) => {
+ if (index === tickCount - 1) return null;
+ return (
+ <Timeline.Point
+ ms={ms}
+ className={
+ "relative bottom-[2px] text-xxs text-text-dimmed"
+ }
+ >
+ {(ms) => (
+ <div
+ className={cn(
+ "whitespace-nowrap",
+ index === 0
+ ? "ml-1"
+ : index === tickCount - 1
+ ? "-ml-1 -translate-x-full"
+ : "-translate-x-1/2"
+ )}
+ >
+ {formatDurationMilliseconds(ms, {
+ style: "short",
+ maxDecimalPoints: ms < 1000 ? 0 : 1,
+ })}
+ </div>
+ )}
+ </Timeline.Point>
+ );
+ }}
+ </Timeline.EquallyDistribute>
+ {rootSpanStatus !== "executing" && (
+ <Timeline.Point
+ ms={nanosecondsToMilliseconds(duration)}
+ className={cn(
+ "relative bottom-[2px] text-xxs",
+ rootSpanStatus === "completed"
+ ? "text-success"
+ : "text-error"
+ )}
+ >
+ {(ms) => (
+ <div className={cn("-translate-x-1/2 whitespace-nowrap")}>
+ {formatDurationMilliseconds(ms, {
+ style: "short",
+ maxDecimalPoints: ms < 1000 ? 0 : 1,
+ })}
+ </div>
+ )}
+ </Timeline.Point>
+ )}
+ </Timeline.Row>
+ <Timeline.Row className="h-2">
+ <Timeline.EquallyDistribute count={tickCount}>
+ {(ms: number, index: number) => {
+ if (index === 0 || index === tickCount - 1) return null;
+ return (
+ <Timeline.Point
+ ms={ms}
+ className={"h-full border-r border-grid-dimmed"}
+ />
+ );
+ }}
+ </Timeline.EquallyDistribute>
+ <Timeline.Point
+ ms={nanosecondsToMilliseconds(duration)}
+ className={cn(
+ "h-full border-r",
+ rootSpanStatus === "completed"
+ ? "border-success/30"
+ : "border-error/30"
+ )}
+ />
+ </Timeline.Row>
+ </Timeline.Row>
+ {/* Main timeline body */}
+ <Timeline.Row className="overflow-hidden">
+ {/* The vertical tick lines */}
+ <Timeline.EquallyDistribute count={tickCount}>
+ {(ms: number, index: number) => {
+ if (index === 0) return null;
+ return (
+ <Timeline.Point
+ ms={ms}
+ className={"h-full border-r border-grid-dimmed"}
+ />
+ );
+ }}
+ </Timeline.EquallyDistribute>
+ {/* The completed line */}
+ {rootSpanStatus !== "executing" && (
+ <Timeline.Point
+ ms={nanosecondsToMilliseconds(duration)}
+ className={cn(
+ "h-full border-r",
+ rootSpanStatus === "completed"
+ ? "border-success/30"
+ : "border-error/30"
+ )}
+ />
+ )}
+ <TreeView
+ scrollRef={timelineScrollRef}
+ virtualizer={virtualizer}
+ tree={events}
+ nodes={nodes}
+ getNodeProps={getNodeProps}
+ getTreeProps={getTreeProps}
+ parentClassName="h-full scrollbar-hide"
+ renderNode={({
+ node,
+ state,
+ index,
+ virtualizer,
+ virtualItem,
+ }) => {
+ return (
+ <Timeline.Row
+ key={index}
+ className={cn(
+ "group flex h-8 items-center",
+ state.selected
+ ? "bg-grid-dimmed hover:bg-grid-bright"
+ : "bg-transparent hover:bg-grid-dimmed"
+ )}
+ // onMouseOver={() => console.log(`hover ${index}`)}
+ onClick={(e) => {
+ toggleNodeSelection(node.id);
+ }}
+ >
+ {node.data.level === "TRACE" ? (
+ <SpanWithDuration
+ showDuration={state.selected ? true : showDurations}
+ startMs={nanosecondsToMilliseconds(node.data.offset)}
+ durationMs={
+ node.data.duration
+ ? nanosecondsToMilliseconds(node.data.duration)
+ : nanosecondsToMilliseconds(
+ duration - node.data.offset
+ )
+ }
+ node={node}
+ />
+ ) : (
+ <Timeline.Point
+ ms={nanosecondsToMilliseconds(node.data.offset)}
+ >
+ {(ms) => (
+ <motion.div
+ className={cn(
+ "-ml-1 h-3 w-3 rounded-full border-2 border-background-bright",
+ eventBackgroundClassName(node.data)
+ )}
+ layoutId={node.id}
+ />
+ )}
+ </Timeline.Point>
+ )}
+ </Timeline.Row>
+ );
+ }}
+ onScroll={(scrollTop) => {
+ //sync the scroll to the tree
+ if (treeScrollRef.current) {
+ treeScrollRef.current.scrollTop = scrollTop;
+ }
+ }}
+ />
+ </Timeline.Row>
+ </Timeline.Row>
+ </Timeline.Root>
+ </div>
+ );
+}
+
+function NodeText({ node }: { node: RunEvent }) {
+ const className = "truncate";
+ return (
+ <Paragraph variant="small" className={cn(className)}>
+ <SpanTitle {...node.data} size="small" />
+ </Paragraph>
+ );
+}
+
+function NodeStatusIcon({ node }: { node: RunEvent }) {
+ if (node.data.level !== "TRACE") return null;
+ if (node.data.style.variant !== "primary") return null;
+
+ if (node.data.isCancelled) {
+ return (
+ <>
+ <Paragraph
+ variant="extra-small"
+ className={runStatusClassNameColor("CANCELED")}
+ >
+ Canceled
+ </Paragraph>
+ <TaskRunStatusIcon status="CANCELED" className={cn("size-4")} />
+ </>
+ );
+ }
+
+ if (node.data.isError) {
+ return (
+ <TaskRunStatusIcon
+ status="COMPLETED_WITH_ERRORS"
+ className={cn("size-4")}
+ />
+ );
+ }
+
+ if (node.data.isPartial) {
+ return <TaskRunStatusIcon status={"EXECUTING"} className={cn("size-4")} />;
+ }
+
+ return (
+ <TaskRunStatusIcon
+ status="COMPLETED_SUCCESSFULLY"
+ className={cn("size-4")}
+ />
+ );
+}
+
+function TaskLine({
+ isError,
+ isSelected,
+}: {
+ isError: boolean;
+ isSelected: boolean;
+}) {
+ return <div className={cn("h-8 w-2 border-r border-grid-bright")} />;
+}
+
+function ShowParentLink({ runFriendlyId }: { runFriendlyId: string }) {
+ const [mouseOver, setMouseOver] = useState(false);
+ const { spanParam } = useParams();
+
+ return (
+ <LinkButton
+ variant="minimal/medium"
+ to={
+ spanParam
+ ? v3RunSpanPath(
+ organization,
+ project,
+ {
+ friendlyId: runFriendlyId,
+ },
+ { spanId: spanParam }
+ )
+ : v3RunPath(organization, project, {
+ friendlyId: runFriendlyId,
+ })
+ }
+ onMouseEnter={() => setMouseOver(true)}
+ onMouseLeave={() => setMouseOver(false)}
+ fullWidth
+ textAlignLeft
+ shortcut={{ key: "p" }}
+ className="flex-1"
+ >
+ {mouseOver ? (
+ <ShowParentIconSelected className="h-4 w-4 text-indigo-500" />
+ ) : (
+ <ShowParentIcon className="text-charcoal-650 h-4 w-4" />
+ )}
+ <Paragraph
+ variant="small"
+ className={cn(mouseOver ? "text-indigo-500" : "text-charcoal-500")}
+ >
+ Show parent items
+ </Paragraph>
+ </LinkButton>
+ );
+}
+
+function LiveReloadingStatus({
+ rootSpanCompleted,
+}: {
+ rootSpanCompleted: boolean;
+}) {
+ if (rootSpanCompleted) return null;
+
+ return (
+ <div className="flex items-center gap-1">
+ <PulsingDot />
+ <Paragraph
+ variant="extra-small"
+ className="whitespace-nowrap text-blue-500"
+ >
+ Live reloading
+ </Paragraph>
+ </div>
+ );
+}
+
+function PulsingDot() {
+ return (
+ <span className="relative flex h-2 w-2">
+ <span
+ className={`absolute h-full w-full animate-ping rounded-full border border-blue-500 opacity-100 duration-1000`}
+ />
+ <span className={`h-2 w-2 rounded-full bg-blue-500`} />
+ </span>
+ );
+}
+
+function SpanWithDuration({
+ showDuration,
+ node,
+ ...props
+}: Timeline.SpanProps & { node: RunEvent; showDuration: boolean }) {
+ return (
+ <Timeline.Span {...props}>
+ <motion.div
+ className={cn(
+ "relative flex h-4 w-full min-w-[2px] items-center rounded-sm",
+ eventBackgroundClassName(node.data)
+ )}
+ layoutId={node.id}
+ >
+ {node.data.isPartial && (
+ <div
+ className="absolute left-0 top-0 h-full w-full animate-tile-scroll rounded-sm opacity-30"
+ style={{
+ backgroundImage: `url(${tileBgPath})`,
+ backgroundSize: "8px 8px",
+ }}
+ />
+ )}
+ <div
+ className={cn(
+ "sticky left-0 z-10 transition group-hover:opacity-100",
+ !showDuration && "opacity-0"
+ )}
+ >
+ <div className="rounded-sm px-1 py-0.5 text-xxs text-text-bright text-shadow-custom">
+ {formatDurationMilliseconds(props.durationMs, {
+ style: "short",
+ maxDecimalPoints: props.durationMs < 1000 ? 0 : 1,
+ })}
+ </div>
+ </div>
+ </motion.div>
+ </Timeline.Span>
+ );
+}
+
+const edgeBoundary = 0.05;
+
+function CurrentTimeIndicator({ totalDuration }: { totalDuration: number }) {
+ return (
+ <Timeline.FollowCursor>
+ {(ms) => {
+ const ratio = ms / nanosecondsToMilliseconds(totalDuration);
+ let offset = 0.5;
+ if (ratio < edgeBoundary) {
+ offset = lerp(0, 0.5, ratio / edgeBoundary);
+ } else if (ratio > 1 - edgeBoundary) {
+ offset = lerp(0.5, 1, (ratio - (1 - edgeBoundary)) / edgeBoundary);
+ }
+
+ return (
+ <div className="relative z-50 flex h-full flex-col">
+ <div className="relative flex h-6 items-end">
+ <div
+ className="absolute w-fit whitespace-nowrap rounded-sm border border-charcoal-600 bg-charcoal-750 px-1 py-0.5 text-xxs tabular-nums text-text-bright"
+ style={{
+ left: `${offset * 100}%`,
+ transform: `translateX(-${offset * 100}%)`,
+ }}
+ >
+ {formatDurationMilliseconds(ms, {
+ style: "short",
+ maxDecimalPoints: ms < 1000 ? 0 : 1,
+ })}
+ </div>
+ </div>
+ <div className="w-px grow border-r border-charcoal-600" />
+ </div>
+ );
+ }}
+ </Timeline.FollowCursor>
+ );
+}
+
+function KeyboardShortcuts({
+ expandAllBelowDepth,
+ collapseAllBelowDepth,
+ toggleExpandLevel,
+ setShowDurations,
+}: {
+ expandAllBelowDepth: (depth: number) => void;
+ collapseAllBelowDepth: (depth: number) => void;
+ toggleExpandLevel: (depth: number) => void;
+ setShowDurations: (show: (show: boolean) => boolean) => void;
+}) {
+ return (
+ <>
+ <ArrowKeyShortcuts />
+ <ShortcutWithAction
+ shortcut={{ key: "e" }}
+ action={() => expandAllBelowDepth(0)}
+ title="Expand all"
+ />
+ <ShortcutWithAction
+ shortcut={{ key: "c" }}
+ action={() => collapseAllBelowDepth(1)}
+ title="Collapse all"
+ />
+ <NumberShortcuts toggleLevel={(number) => toggleExpandLevel(number)} />
+ <ShortcutWithAction
+ shortcut={{ key: "d" }}
+ action={() => setShowDurations((d) => !d)}
+ title="Toggle durations"
+ />
+ </>
+ );
+}
+
+function ArrowKeyShortcuts() {
+ return (
+ <div className="flex items-center gap-0.5">
+ <ShortcutKey
+ shortcut={{ key: "arrowup" }}
+ variant="medium"
+ className="ml-0 mr-0"
+ />
+ <ShortcutKey
+ shortcut={{ key: "arrowdown" }}
+ variant="medium"
+ className="ml-0 mr-0"
+ />
+ <ShortcutKey
+ shortcut={{ key: "arrowleft" }}
+ variant="medium"
+ className="ml-0 mr-0"
+ />
+ <ShortcutKey
+ shortcut={{ key: "arrowright" }}
+ variant="medium"
+ className="ml-0 mr-0"
+ />
+ <Paragraph variant="extra-small" className="ml-1.5 whitespace-nowrap">
+ Navigate
+ </Paragraph>
+ </div>
+ );
+}
+
+function ShortcutWithAction({
+ shortcut,
+ title,
+ action,
+}: {
+ shortcut: Shortcut;
+ title: string;
+ action: () => void;
+}) {
+ useShortcutKeys({
+ shortcut,
+ action,
+ });
+
+ return (
+ <div className="flex items-center gap-0.5">
+ <ShortcutKey shortcut={shortcut} variant="medium" className="ml-0 mr-0" />
+ <Paragraph variant="extra-small" className="ml-1.5 whitespace-nowrap">
+ {title}
+ </Paragraph>
+ </div>
+ );
+}
+
+function NumberShortcuts({
+ toggleLevel,
+}: {
+ toggleLevel: (depth: number) => void;
+}) {
+ useKeyboardShortcuts({
+ "1": () => toggleLevel(1),
+ "2": () => toggleLevel(2),
+ "3": () => toggleLevel(3),
+ "4": () => toggleLevel(4),
+ "5": () => toggleLevel(5),
+ "6": () => toggleLevel(6),
+ "7": () => toggleLevel(7),
+ "8": () => toggleLevel(8),
+ "9": () => toggleLevel(9),
+ "0": () => toggleLevel(0),
+ });
+
+ return (
+ <div className="flex items-center gap-0.5">
+ <span className={cn(variants.medium, "ml-0 mr-0")}>0</span>
+ <span className="text-[0.75rem] text-text-dimmed">–</span>
+ <span className={cn(variants.medium, "ml-0 mr-0")}>9</span>
+ <Paragraph variant="extra-small" className="ml-1.5 whitespace-nowrap">
+ Toggle level
+ </Paragraph>
+ </div>
+ );
+}
+
+function SearchField({ onChange }: { onChange: (value: string) => void }) {
+ const [value, setValue] = useState("");
+
+ const updateFilterText = useDebounce((text: string) => {
+ onChange(text);
+ }, 250);
+
+ const updateValue = useCallback((value: string) => {
+ setValue(value);
+ updateFilterText(value);
+ }, []);
+
+ return (
+ <Input
+ placeholder="Search log"
+ variant="tertiary"
+ icon="search"
+ fullWidth={true}
+ value={value}
+ onChange={(e) => updateValue(e.target.value)}
+ />
+ );
+}
diff --git a/apps/carbon/package.json b/apps/carbon/package.json
index 59fb3c40dc..2438458eb9 100644
--- a/apps/carbon/package.json
+++ b/apps/carbon/package.json
@@ -24,6 +24,7 @@
"@tailwindcss/line-clamp": "^0.4.4",
"@tailwindcss/typography": "^0.5.10",
"@tanstack/react-table": "^8.9.3",
+ "@tanstack/react-virtual": "^3.5.0",
"@trigger.dev/cli": "^2.3.17",
"@trigger.dev/react": "^2.3.16",
"@trigger.dev/remix": "^2.3.16",
@@ -40,6 +41,7 @@
"@visx/responsive": "3.3.0",
"@visx/scale": "3.3.0",
"@visx/shape": "3.3.0",
+ "assert-never": "^1.2.1",
"axios": "^1.6.5",
"clsx": "^2.1.0",
"cookie": "^0.6.0",
diff --git a/package-lock.json b/package-lock.json
index 3c2235f01f..a035fb1817 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -49,6 +49,7 @@
"@tailwindcss/line-clamp": "^0.4.4",
"@tailwindcss/typography": "^0.5.10",
"@tanstack/react-table": "^8.9.3",
+ "@tanstack/react-virtual": "^3.5.0",
"@trigger.dev/cli": "^2.3.17",
"@trigger.dev/react": "^2.3.16",
"@trigger.dev/remix": "^2.3.16",
@@ -65,6 +66,7 @@
"@visx/responsive": "3.3.0",
"@visx/scale": "3.3.0",
"@visx/shape": "3.3.0",
+ "assert-never": "^1.2.1",
"axios": "^1.6.5",
"clsx": "^2.1.0",
"cookie": "^0.6.0",
@@ -9090,11 +9092,11 @@
}
},
"node_modules/@tanstack/react-virtual": {
- "version": "3.4.0",
- "resolved": "https://registry.npmjs.org/@tanstack/react-virtual/-/react-virtual-3.4.0.tgz",
- "integrity": "sha512-GZN4xn/Tg5w7gvYeVcMVCeL4pEyUhvg+Cp6KX2Z01C4FRNxIWMgIQ9ibgMarNQfo+gt0PVLcEER4A9sNv/jlow==",
+ "version": "3.5.0",
+ "resolved": "https://registry.npmjs.org/@tanstack/react-virtual/-/react-virtual-3.5.0.tgz",
+ "integrity": "sha512-rtvo7KwuIvqK9zb0VZ5IL7fiJAEnG+0EiFZz8FUOs+2mhGqdGmjKIaT1XU7Zq0eFqL0jonLlhbayJI/J2SA/Bw==",
"dependencies": {
- "@tanstack/virtual-core": "3.4.0"
+ "@tanstack/virtual-core": "3.5.0"
},
"funding": {
"type": "github",
@@ -9118,9 +9120,9 @@
}
},
"node_modules/@tanstack/virtual-core": {
- "version": "3.4.0",
- "resolved": "https://registry.npmjs.org/@tanstack/virtual-core/-/virtual-core-3.4.0.tgz",
- "integrity": "sha512-75jXqXxqq5M5Veb9KP1STi8kA5u408uOOAefk2ftHDGCpUk3RP6zX++QqfbmHJTBiU72NQ+ghgCZVts/Wocz8Q==",
+ "version": "3.5.0",
+ "resolved": "https://registry.npmjs.org/@tanstack/virtual-core/-/virtual-core-3.5.0.tgz",
+ "integrity": "sha512-KnPRCkQTyqhanNC0K63GBG3wA8I+D1fQuVnAvcBF8f13akOKeQp1gSbu6f77zCxhEk727iV5oQnbHLYzHrECLg==",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/tannerlinsley"
@@ -11530,6 +11532,11 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/assert-never": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/assert-never/-/assert-never-1.2.1.tgz",
+ "integrity": "sha512-TaTivMB6pYI1kXwrFlEhLeGfOqoDNdTxjCdwRfFFkEA30Eu+k48W34nlok2EYWJfFFzqaEmichdNM7th6M5HNw=="
+ },
"node_modules/assign-symbols": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/assign-symbols/-/assign-symbols-1.0.0.tgz",
diff --git a/packages/react/src/hooks/useDebounce.ts b/packages/react/src/hooks/useDebounce.ts
index 574713b775..cf3875afa8 100644
--- a/packages/react/src/hooks/useDebounce.ts
+++ b/packages/react/src/hooks/useDebounce.ts
@@ -1,29 +1,24 @@
-import { useEffect, useState } from "react";
+import { useRef } from "react";
-export default function useDebounce<T = any>(
- value: T,
+/**
+ * A function that you call with a debounce delay, the function will only be called after the delay has passed
+ *
+ * @param fn The function to debounce
+ * @param delay In ms
+ */
+export default function useDebounce<T extends (...args: any[]) => any>(
+ fn: T,
delay: number
-): [T, boolean] {
- // State and setters for debounced value
- const [debouncedValue, setDebouncedValue] = useState(value);
- let [isDebouncing, setDebouncing] = useState(false);
- useEffect(
- () => {
- // Update debounced value after delay
- setDebouncing(true);
- const handler = setTimeout(() => {
- setDebouncing(false);
+) {
+ const timeout = useRef<ReturnType<typeof setTimeout>>();
- setDebouncedValue(value);
- }, delay);
- // Cancel the timeout if value changes (also on delay change or unmount)
- // This is how we prevent debounced value from updating if value is changed ...
- // .. within the delay period. Timeout gets cleared and restarted.
- return () => {
- clearTimeout(handler);
- };
- },
- [value, delay] // Only re-call effect if value or delay changes
- );
- return [debouncedValue, isDebouncing];
+ return (...args: Parameters<T>) => {
+ if (timeout.current) {
+ clearTimeout(timeout.current);
+ }
+
+ timeout.current = setTimeout(() => {
+ fn(...args);
+ }, delay);
+ };
}
diff --git a/packages/utils/src/math.ts b/packages/utils/src/math.ts
index 9382b143fc..2f9a836312 100644
--- a/packages/utils/src/math.ts
+++ b/packages/utils/src/math.ts
@@ -1,4 +1,4 @@
-export const clip = (value: number, min: number, max: number) =>
+export const clamp = (value: number, min: number, max: number) =>
Math.min(Math.max(value, min), max);
export const twoDecimals = (n: number) => {
@@ -7,3 +7,11 @@ export const twoDecimals = (n: number) => {
return Math.round(n * div) / div;
};
+
+export const lerp = (min: number, max: number, t: number) => {
+ return min + (max - min) * clamp(t, 0, 1);
+};
+
+export const inverseLerp = (min: number, max: number, value: number) => {
+ return (value - min) / (max - min);
+};