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.

feat: prototype of gantt view

Brad Barbin7c83911ed353
diff --git a/apps/carbon/app/assets/icons/AttemptIcon.tsx b/apps/carbon/app/assets/icons/AttemptIcon.tsx
new file mode 100644
index 0000000000..9fd9d7f6eb
--- /dev/null
+++ b/apps/carbon/app/assets/icons/AttemptIcon.tsx
@@ -0,0 +1,29 @@
+export function AttemptIcon({ className }: { className?: string }) {
+ return (
+ <svg
+ className={className}
+ width="16"
+ height="16"
+ viewBox="0 0 16 16"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <g clipPath="url(#clip0_9964_113464)">
+ <path
+ fillRule="evenodd"
+ clipRule="evenodd"
+ d="M16 0H0V16H16V0ZM7.09906 4.4L4.53906 11.5H6.11906L6.63906 10H9.35906L9.87906 11.5H11.4591L8.89906 4.4H7.09906ZM7.99906 6L8.92906 8.73H7.06906L7.99906 6Z"
+ fill="currentColor"
+ />
+ </g>
+ <defs>
+ <clipPath id="clip0_9964_113464">
+ <path
+ d="M0 2C0 0.895431 0.895431 0 2 0H14C15.1046 0 16 0.895431 16 2V14C16 15.1046 15.1046 16 14 16H2C0.895431 16 0 15.1046 0 14V2Z"
+ fill="white"
+ />
+ </clipPath>
+ </defs>
+ </svg>
+ );
+}
diff --git a/apps/carbon/app/assets/icons/TaskIcon.tsx b/apps/carbon/app/assets/icons/TaskIcon.tsx
new file mode 100644
index 0000000000..48d9c4181d
--- /dev/null
+++ b/apps/carbon/app/assets/icons/TaskIcon.tsx
@@ -0,0 +1,29 @@
+export function TaskIcon({ className }: { className?: string }) {
+ return (
+ <svg
+ className={className}
+ width="16"
+ height="16"
+ viewBox="0 0 16 16"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <g clipPath="url(#clip0_9221_99732)">
+ <path
+ fillRule="evenodd"
+ clipRule="evenodd"
+ d="M16 0H0V16H16V0ZM10.8901 5.73995V4.44995H5.11011V5.73995H7.23011V11.55H8.77011V5.73995H10.8901Z"
+ fill="currentColor"
+ />
+ </g>
+ <defs>
+ <clipPath id="clip0_9221_99732">
+ <path
+ d="M0 2C0 0.895431 0.895431 0 2 0H14C15.1046 0 16 0.895431 16 2V14C16 15.1046 15.1046 16 14 16H2C0.895431 16 0 15.1046 0 14V2Z"
+ fill="white"
+ />
+ </clipPath>
+ </defs>
+ </svg>
+ );
+}
diff --git a/apps/carbon/app/components/Layout/Navigation/useModules.tsx b/apps/carbon/app/components/Layout/Navigation/useModules.tsx
index a27aa2eb08..6f9f51cab7 100644
--- a/apps/carbon/app/components/Layout/Navigation/useModules.tsx
+++ b/apps/carbon/app/components/Layout/Navigation/useModules.tsx
@@ -1,6 +1,15 @@
-import { BiListCheck } from "react-icons/bi";
-import { BsCalendar2Week } from "react-icons/bs";
-import { LuSettings, LuShield, LuUsers } from "react-icons/lu";
+import {
+ LuCalendarRange,
+ LuComponent,
+ LuCreditCard,
+ LuFiles,
+ LuLandmark,
+ LuReceipt,
+ LuSettings,
+ LuShield,
+ LuShoppingCart,
+ LuUsers,
+} from "react-icons/lu";
import { usePermissions } from "~/hooks";
import type { Authenticated, NavItem } from "~/types";
import { path } from "~/utils/path";
@@ -9,19 +18,19 @@ 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: "jobs",
+ // name: "Jobs",
+ // to: path.to.jobs,
+ // icon: LuCalendarClock,
+ // },
+ // {
// permission: "inventory",
// name: "Inventory",
// to: path.to.receipts,
@@ -31,7 +40,7 @@ export function useModules() {
permission: "scheduling",
name: "Scheduling",
to: path.to.scheduling,
- icon: BsCalendar2Week,
+ icon: LuCalendarRange,
},
// {
// permission: "timecards",
@@ -39,42 +48,42 @@ export function useModules() {
// 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/Temporary/Paragraph.tsx b/apps/carbon/app/components/Temporary/Paragraph.tsx
new file mode 100644
index 0000000000..9133b02f9f
--- /dev/null
+++ b/apps/carbon/app/components/Temporary/Paragraph.tsx
@@ -0,0 +1,95 @@
+import { cn } from "@carbon/react";
+
+const paragraphVariants = {
+ base: {
+ text: "font-sans text-base font-normal text-muted-foreground",
+ spacing: "mb-3",
+ },
+ "base/bright": {
+ text: "font-sans text-base font-normal text-foreground",
+ spacing: "mb-3",
+ },
+ small: {
+ text: "font-sans text-sm font-normal text-muted-foreground",
+ spacing: "mb-2",
+ },
+ "small/bright": {
+ text: "font-sans text-sm font-normal text-foreground",
+ spacing: "mb-2",
+ },
+ "extra-small": {
+ text: "font-sans text-xs font-normal text-muted-foreground",
+ spacing: "mb-1.5",
+ },
+ "extra-small/bright": {
+ text: "font-sans text-xs font-normal text-foreground",
+ spacing: "mb-1.5",
+ },
+ "extra-small/mono": {
+ text: "font-mono text-xs font-normal text-muted-foreground",
+ spacing: "mb-1.5",
+ },
+ "extra-small/bright/mono": {
+ text: "font-mono text-xs text-foreground",
+ spacing: "mb-1.5",
+ },
+ "extra-small/caps": {
+ text: "font-sans text-xs uppercase tracking-wider font-normal text-muted-foreground",
+ spacing: "mb-1.5",
+ },
+ "extra-small/bright/caps": {
+ text: "font-sans text-xs uppercase tracking-wider font-normal text-foreground",
+ spacing: "mb-1.5",
+ },
+ "extra-extra-small": {
+ text: "font-sans text-xxs font-normal text-muted-foreground",
+ spacing: "mb-1",
+ },
+ "extra-extra-small/bright": {
+ text: "font-sans text-xxs font-normal text-foreground",
+ spacing: "mb-1",
+ },
+
+ "extra-extra-small/caps": {
+ text: "font-sans text-xxs uppercase tracking-wider font-normal text-muted-foreground",
+ spacing: "mb-1",
+ },
+ "extra-extra-small/bright/caps": {
+ text: "font-sans text-xxs uppercase tracking-wider font-normal text-foreground",
+ spacing: "mb-1",
+ },
+ "extra-extra-small/dimmed/caps": {
+ text: "font-sans text-xxs uppercase tracking-wider font-normal text-muted-foreground",
+ spacing: "mb-1",
+ },
+};
+
+export type ParagraphVariant = keyof typeof paragraphVariants;
+
+type ParagraphProps = {
+ variant?: ParagraphVariant;
+ className?: string;
+ spacing?: boolean;
+ children: React.ReactNode;
+} & React.HTMLAttributes<HTMLParagraphElement>;
+
+export function Paragraph({
+ variant = "base",
+ className,
+ spacing = false,
+ children,
+ ...props
+}: ParagraphProps) {
+ return (
+ <p
+ className={cn(
+ paragraphVariants[variant].text,
+ spacing === true && paragraphVariants[variant].spacing,
+ className
+ )}
+ {...props}
+ >
+ {children}
+ </p>
+ );
+}
diff --git a/apps/carbon/app/components/Temporary/RunIcon.tsx b/apps/carbon/app/components/Temporary/RunIcon.tsx
new file mode 100644
index 0000000000..fa62e927a7
--- /dev/null
+++ b/apps/carbon/app/components/Temporary/RunIcon.tsx
@@ -0,0 +1,61 @@
+import { cn } from "@carbon/react";
+import { AiOutlinePartition } from "react-icons/ai";
+import {
+ HiClock,
+ HiHandRaised,
+ HiInformationCircle,
+ HiSquares2X2,
+} from "react-icons/hi2";
+import { LuCalendarClock, LuClock } from "react-icons/lu";
+import { AttemptIcon } from "~/assets/icons/AttemptIcon";
+import { TaskIcon } from "~/assets/icons/TaskIcon";
+
+type TaskIconProps = {
+ name: string | undefined;
+ className?: string;
+};
+
+export function RunIcon({ name, className }: TaskIconProps) {
+ if (!name)
+ return <HiSquares2X2 className={cn(className, "text-muted-foreground")} />;
+
+ switch (name) {
+ case "job":
+ return <LuCalendarClock className={cn(className, "text-primary")} />;
+ case "assembly":
+ return (
+ <AiOutlinePartition className={cn(className, "text-indigo-500")} />
+ );
+ case "operation":
+ return <LuClock className={cn(className, "text-blue-500")} />;
+ case "timecard":
+ return <TaskIcon className={cn(className, "text-yellow-500")} />;
+ case "attempt":
+ return <AttemptIcon className={cn(className, "text-muted-foreground")} />;
+ case "wait":
+ return <HiClock className={cn(className, "text-teal-500")} />;
+ case "trace":
+ return (
+ <HiSquares2X2 className={cn(className, "text-muted-foreground")} />
+ );
+ //log levels
+ case "debug":
+ case "log":
+ case "info":
+ return (
+ <HiInformationCircle
+ className={cn(className, "text-muted-foreground")}
+ />
+ );
+ case "warn":
+ return (
+ <HiInformationCircle className={cn(className, "text-amber-400")} />
+ );
+ case "error":
+ return <HiInformationCircle className={cn(className, "text-rose-500")} />;
+ case "fatal":
+ return <HiHandRaised className={cn(className, "text-rose-800")} />;
+ }
+
+ return <HiSquares2X2 className={cn(className, "text-muted-foreground")} />;
+}
diff --git a/apps/carbon/app/components/Temporary/SpanTitle.tsx b/apps/carbon/app/components/Temporary/SpanTitle.tsx
new file mode 100644
index 0000000000..4687338db4
--- /dev/null
+++ b/apps/carbon/app/components/Temporary/SpanTitle.tsx
@@ -0,0 +1,189 @@
+import { Badge, cn } from "@carbon/react";
+import { Fragment } from "react";
+import { LuChevronRight } from "react-icons/lu";
+import type { z } from "zod";
+import type { RunEvent, TaskEventLevel, TaskEventStyle } from "./types";
+
+type SpanTitleProps = {
+ message: string;
+ isError: boolean;
+ style: z.infer<typeof TaskEventStyle>;
+ level: TaskEventLevel;
+ isPartial: boolean;
+ size: "small" | "large";
+};
+
+export function SpanTitle(event: SpanTitleProps) {
+ return (
+ <span
+ className={cn(
+ "flex items-center gap-x-2 overflow-x-hidden",
+ eventTextClassName(event)
+ )}
+ >
+ <span className="truncate">{event.message}</span>{" "}
+ <SpanAccessory accessory={event.style.accessory} size={event.size} />
+ </span>
+ );
+}
+
+function SpanAccessory({
+ accessory,
+ size,
+}: {
+ accessory: z.infer<typeof TaskEventStyle>["accessory"];
+ size: SpanTitleProps["size"];
+}) {
+ if (!accessory) {
+ return null;
+ }
+
+ switch (accessory.style) {
+ case "person": {
+ return (
+ <SpanBadgeAccessory
+ accessory={accessory}
+ className={cn(
+ "overflow-x-hidden",
+ size === "large" ? "text-sm" : "text-xs"
+ )}
+ />
+ );
+ }
+ default: {
+ return (
+ <div className={cn("flex gap-1")}>
+ {accessory.items.map((item, index) => (
+ <span key={index} className={cn("inline-flex items-center gap-1")}>
+ {item.text}
+ </span>
+ ))}
+ </div>
+ );
+ }
+ }
+}
+
+export function SpanBadgeAccessory({
+ accessory,
+ className,
+}: {
+ accessory: NonNullable<z.infer<typeof TaskEventStyle>["accessory"]>;
+ className?: string;
+}) {
+ return (
+ <Badge
+ variant="outline"
+ className={cn("inline-flex items-center gap-0.5 truncate ", className)}
+ >
+ {accessory.items.map((item, index) => (
+ <Fragment key={index}>
+ <span className={cn("truncate")}>{item.text}</span>
+ {index < accessory.items.length - 1 && (
+ <span className="text-muted-foreground">
+ <LuChevronRight className="h-4 w-4" />
+ </span>
+ )}
+ </Fragment>
+ ))}
+ </Badge>
+ );
+}
+
+function eventTextClassName(
+ event: Pick<SpanTitleProps, "isError" | "style" | "level">
+) {
+ switch (event.level) {
+ case "TRACE": {
+ return textClassNameForVariant(event.style.variant);
+ }
+ case "LOG":
+ case "INFO":
+ case "DEBUG": {
+ return textClassNameForVariant(event.style.variant);
+ }
+ case "WARN": {
+ return "text-amber-400";
+ }
+ case "ERROR": {
+ return "text-error";
+ }
+ default: {
+ return textClassNameForVariant(event.style.variant);
+ }
+ }
+}
+
+export function eventBackgroundClassName(
+ event: Pick<
+ RunEvent["data"],
+ "isError" | "style" | "level" | "isPartial" | "isCancelled"
+ >
+) {
+ if (event.isError) {
+ return "bg-error";
+ }
+
+ if (event.isCancelled) {
+ return "bg-muted";
+ }
+
+ switch (event.level) {
+ case "TRACE": {
+ return backgroundClassNameForVariant(
+ event.style.variant,
+ event.isPartial
+ );
+ }
+ case "LOG":
+ case "INFO":
+ case "DEBUG": {
+ return backgroundClassNameForVariant(
+ event.style.variant,
+ event.isPartial
+ );
+ }
+ case "WARN": {
+ return "bg-orange-400";
+ }
+ case "ERROR": {
+ return "bg-destructive";
+ }
+ default: {
+ return backgroundClassNameForVariant(
+ event.style.variant,
+ event.isPartial
+ );
+ }
+ }
+}
+
+function textClassNameForVariant(
+ variant: z.infer<typeof TaskEventStyle>["variant"]
+) {
+ switch (variant) {
+ case "primary": {
+ return "text-foreground";
+ }
+ default: {
+ return "text-muted-foreground";
+ }
+ }
+}
+
+function backgroundClassNameForVariant(
+ variant: z.infer<typeof TaskEventStyle>["variant"],
+ isPartial: boolean
+) {
+ switch (variant) {
+ case "primary": {
+ if (isPartial) {
+ return "bg-blue-500";
+ }
+ return "bg-emerald-500";
+ }
+ default: {
+ return "bg-gray-500";
+ }
+ }
+}
diff --git a/apps/carbon/app/components/Temporary/TaskRunStatus.tsx b/apps/carbon/app/components/Temporary/TaskRunStatus.tsx
new file mode 100644
index 0000000000..8d1ce7d775
--- /dev/null
+++ b/apps/carbon/app/components/Temporary/TaskRunStatus.tsx
@@ -0,0 +1,253 @@
+import {
+ HiArrowPath,
+ HiBoltSlash,
+ HiBugAnt,
+ HiCheckCircle,
+ HiFire,
+ HiNoSymbol,
+ HiPauseCircle,
+ HiRectangleStack,
+} from "react-icons/hi2";
+
+import { Spinner, cn } from "@carbon/react";
+import assertNever from "assert-never";
+import { LuSnowflake, LuXCircle } from "react-icons/lu";
+
+export type TaskRunStatus =
+ | "PENDING"
+ | "WAITING_FOR_DEPLOY"
+ | "EXECUTING"
+ | "RETRYING_AFTER_FAILURE"
+ | "WAITING_TO_RESUME"
+ | "COMPLETED_SUCCESSFULLY"
+ | "CANCELED"
+ | "COMPLETED_WITH_ERRORS"
+ | "INTERRUPTED"
+ | "SYSTEM_FAILURE"
+ | "PAUSED"
+ | "CRASHED";
+
+export const allTaskRunStatuses = [
+ "WAITING_FOR_DEPLOY",
+ "PENDING",
+ "EXECUTING",
+ "RETRYING_AFTER_FAILURE",
+ "WAITING_TO_RESUME",
+ "COMPLETED_SUCCESSFULLY",
+ "CANCELED",
+ "COMPLETED_WITH_ERRORS",
+ "CRASHED",
+ "INTERRUPTED",
+ "SYSTEM_FAILURE",
+] as TaskRunStatus[];
+
+const taskRunStatusDescriptions: Record<TaskRunStatus, string> = {
+ PENDING: "Task is waiting to be executed",
+ WAITING_FOR_DEPLOY: "Task needs to be deployed first to start executing",
+ EXECUTING: "Task is currently being executed",
+ RETRYING_AFTER_FAILURE: "Task is being reattempted after a failure",
+ WAITING_TO_RESUME: "Task has been frozen and is waiting to be resumed",
+ COMPLETED_SUCCESSFULLY: "Task has been successfully completed",
+ CANCELED: "Task has been canceled",
+ COMPLETED_WITH_ERRORS: "Task has failed with errors",
+ INTERRUPTED: "Task has failed because it was interrupted",
+ SYSTEM_FAILURE: "Task has failed due to a system failure",
+ PAUSED: "Task has been paused by the user",
+ CRASHED: "Task has crashed and won't be retried",
+};
+
+export const QUEUED_STATUSES: TaskRunStatus[] = [
+ "PENDING",
+ "WAITING_FOR_DEPLOY",
+];
+
+export const RUNNING_STATUSES: TaskRunStatus[] = [
+ "EXECUTING",
+ "RETRYING_AFTER_FAILURE",
+ "WAITING_TO_RESUME",
+];
+
+export const FINISHED_STATUSES: TaskRunStatus[] = [
+ "COMPLETED_SUCCESSFULLY",
+ "CANCELED",
+ "COMPLETED_WITH_ERRORS",
+ "INTERRUPTED",
+ "SYSTEM_FAILURE",
+ "CRASHED",
+];
+
+export function descriptionForTaskRunStatus(status: TaskRunStatus): string {
+ return taskRunStatusDescriptions[status];
+}
+
+export function TaskRunStatusCombo({
+ status,
+ className,
+ iconClassName,
+}: {
+ status: TaskRunStatus;
+ className?: string;
+ iconClassName?: string;
+}) {
+ return (
+ <span className={cn("flex items-center gap-1", className)}>
+ <TaskRunStatusIcon
+ status={status}
+ className={cn("h-4 w-4", iconClassName)}
+ />
+ <TaskRunStatusLabel status={status} />
+ </span>
+ );
+}
+
+export function TaskRunStatusLabel({ status }: { status: TaskRunStatus }) {
+ return (
+ <span className={runStatusClassNameColor(status)}>
+ {runStatusTitle(status)}
+ </span>
+ );
+}
+
+export function TaskRunStatusIcon({
+ status,
+ className,
+}: {
+ status: TaskRunStatus;
+ className: string;
+}) {
+ switch (status) {
+ case "PENDING":
+ return (
+ <HiRectangleStack
+ className={cn(runStatusClassNameColor(status), className)}
+ />
+ );
+ case "WAITING_FOR_DEPLOY":
+ return (
+ <HiRectangleStack
+ className={cn(runStatusClassNameColor(status), className)}
+ />
+ );
+ case "EXECUTING":
+ return (
+ <Spinner
+ className={cn(runStatusClassNameColor(status), "w-2 h-2", className)}
+ />
+ );
+ case "WAITING_TO_RESUME":
+ return (
+ <LuSnowflake
+ className={cn(runStatusClassNameColor(status), className)}
+ />
+ );
+ case "RETRYING_AFTER_FAILURE":
+ return (
+ <HiArrowPath
+ className={cn(runStatusClassNameColor(status), className)}
+ />
+ );
+ case "PAUSED":
+ return (
+ <HiPauseCircle
+ className={cn(runStatusClassNameColor(status), className)}
+ />
+ );
+ case "CANCELED":
+ return (
+ <HiNoSymbol
+ className={cn(runStatusClassNameColor(status), className)}
+ />
+ );
+ case "INTERRUPTED":
+ return (
+ <HiBoltSlash
+ className={cn(runStatusClassNameColor(status), className)}
+ />
+ );
+ case "COMPLETED_SUCCESSFULLY":
+ return (
+ <HiCheckCircle
+ className={cn(runStatusClassNameColor(status), className)}
+ />
+ );
+ case "COMPLETED_WITH_ERRORS":
+ return (
+ <LuXCircle className={cn(runStatusClassNameColor(status), className)} />
+ );
+ case "SYSTEM_FAILURE":
+ return (
+ <HiBugAnt className={cn(runStatusClassNameColor(status), className)} />
+ );
+ case "CRASHED":
+ return (
+ <HiFire className={cn(runStatusClassNameColor(status), className)} />
+ );
+
+ default: {
+ assertNever(status);
+ }
+ }
+}
+
+export function runStatusClassNameColor(status: TaskRunStatus): string {
+ switch (status) {
+ case "PENDING":
+ return "text-gray-500";
+ case "WAITING_FOR_DEPLOY":
+ return "text-orange-500";
+ case "EXECUTING":
+ case "RETRYING_AFTER_FAILURE":
+ return "text-pending";
+ case "WAITING_TO_RESUME":
+ return "text-blue-300";
+ case "PAUSED":
+ return "text-orange-300";
+ case "CANCELED":
+ return "text-gray-500";
+ case "INTERRUPTED":
+ return "text-error";
+ case "COMPLETED_SUCCESSFULLY":
+ return "text-success";
+ case "COMPLETED_WITH_ERRORS":
+ return "text-error";
+ case "SYSTEM_FAILURE":
+ return "text-error";
+ case "CRASHED":
+ return "text-error";
+ default: {
+ assertNever(status);
+ }
+ }
+}
+
+export function runStatusTitle(status: TaskRunStatus): string {
+ switch (status) {
+ case "PENDING":
+ return "Queued";
+ case "WAITING_FOR_DEPLOY":
+ return "Waiting for deploy";
+ case "EXECUTING":
+ return "Executing";
+ case "WAITING_TO_RESUME":
+ return "Frozen";
+ case "RETRYING_AFTER_FAILURE":
+ return "Reattempting";
+ case "PAUSED":
+ return "Paused";
+ case "CANCELED":
+ return "Canceled";
+ case "INTERRUPTED":
+ return "Interrupted";
+ case "COMPLETED_SUCCESSFULLY":
+ return "Completed";
+ case "COMPLETED_WITH_ERRORS":
+ return "Failed";
+ case "SYSTEM_FAILURE":
+ return "System failure";
+ case "CRASHED":
+ return "Crashed";
+ default: {
+ assertNever(status);
+ }
+ }
+}
diff --git a/apps/carbon/app/components/Temporary/index.ts b/apps/carbon/app/components/Temporary/index.ts
new file mode 100644
index 0000000000..54002c83a9
--- /dev/null
+++ b/apps/carbon/app/components/Temporary/index.ts
@@ -0,0 +1,2 @@
+export * from "./Paragraph";
+export * from "./SpanTitle";
diff --git a/apps/carbon/app/components/Temporary/types.ts b/apps/carbon/app/components/Temporary/types.ts
new file mode 100644
index 0000000000..c481d4db80
--- /dev/null
+++ b/apps/carbon/app/components/Temporary/types.ts
@@ -0,0 +1,53 @@
+import { z } from "zod";
+
+export enum TaskEventLevel {
+ TRACE = "TRACE",
+ DEBUG = "DEBUG",
+ INFO = "INFO",
+ LOG = "LOG",
+ WARN = "WARN",
+ ERROR = "ERROR",
+}
+
+export type RunEvent = {
+ id: string;
+ parentId: string | undefined;
+ children: string[];
+ hasChildren: boolean;
+ level: number;
+ data: {
+ duration: number;
+ offset: number;
+ message: string;
+ isRoot: boolean;
+ isError: boolean;
+ style: z.infer<typeof TaskEventStyle>;
+ level: TaskEventLevel;
+ isPartial: boolean;
+ isCancelled: boolean;
+ };
+};
+
+const Variant = z.enum(["primary"]);
+
+const AccessoryItem = z.object({
+ text: z.string(),
+ variant: z.string().optional(),
+ url: z.string().optional(),
+});
+
+const Accessory = z.object({
+ items: z.array(AccessoryItem),
+ style: z.enum(["person"]).optional(),
+});
+
+export const TaskEventStyle = z
+ .object({
+ icon: z.string().optional(),
+ variant: Variant.optional(),
+ accessory: Accessory.optional(),
+ })
+ .default({
+ icon: undefined,
+ variant: undefined,
+ });
diff --git a/apps/carbon/app/modules/settings/ui/useSettingsSubmodules.tsx b/apps/carbon/app/modules/settings/ui/useSettingsSubmodules.tsx
index 8394ab0e3e..dfb72fb675 100644
--- a/apps/carbon/app/modules/settings/ui/useSettingsSubmodules.tsx
+++ b/apps/carbon/app/modules/settings/ui/useSettingsSubmodules.tsx
@@ -1,4 +1,5 @@
-import { LuFactory } from "react-icons/lu";
+import { LuFactory, LuSheet, LuWorkflow } from "react-icons/lu";
+import { MdOutlineDashboardCustomize } from "react-icons/md";
import { usePermissions } from "~/hooks";
import type { AuthenticatedRouteGroup } from "~/types";
import { path } from "~/utils/path";
@@ -15,29 +16,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/routes/x+/scheduling+/index.tsx b/apps/carbon/app/routes/x+/scheduling+/index.tsx
index aa010e5481..2fcc862666 100644
--- a/apps/carbon/app/routes/x+/scheduling+/index.tsx
+++ b/apps/carbon/app/routes/x+/scheduling+/index.tsx
@@ -1,99 +1,206 @@
import {
Badge,
- Heading,
+ Button,
+ ClientOnly,
Input,
- Popover,
- PopoverContent,
- PopoverTrigger,
+ InputGroup,
+ InputLeftElement,
ResizableHandle,
ResizablePanel,
ResizablePanelGroup,
+ Slider,
+ Switch,
cn,
useDebounce,
- useKeyboardShortcuts,
+ useInitialDimensions,
} from "@carbon/react";
+import { formatDurationMilliseconds, lerp } from "@carbon/utils";
import type { Location } from "@remix-run/react";
-import { useLoaderData, useParams } from "@remix-run/react";
+import { Link, 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 { useEffect, useRef, useState } from "react";
import {
LuChevronDown,
LuChevronUp,
+ LuSearch,
LuZoomIn,
LuZoomOut,
} from "react-icons/lu";
-
+import { typedjson, useTypedLoaderData } from "remix-typedjson";
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 {
+ Paragraph,
SpanTitle,
eventBackgroundClassName,
-} from "~/components/runs/v3/SpanTitle";
+} from "~/components/Temporary";
+import { RunIcon } from "~/components/Temporary/RunIcon";
+
import {
TaskRunStatusIcon,
runStatusClassNameColor,
-} from "~/components/runs/v3/TaskRunStatus";
-import { useInitialDimensions } from "~/hooks/useInitialDimensions";
+} from "~/components/Temporary/TaskRunStatus";
+import type { RunEvent } from "~/components/Temporary/types";
+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 { 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";
+import {
+ getResizableRunSettings,
+ setResizableRunSettings,
+} from "~/utils/resizablePanel";
-export const loader = async ({ request, params }: LoaderFunctionArgs) => {
- const { companyId, userId } = await requirePermissions(request, {
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ await requirePermissions(request, {
view: "scheduling",
});
- console.log({ companyId, userId });
+ const resizeSettings = await getResizableRunSettings(request);
- return {
- data: [],
- };
-};
+ return typedjson({
+ trace: {
+ events: [
+ {
+ id: "1",
+ parentId: undefined,
+ hasChildren: true,
+ children: ["2", "3"],
+ level: 0,
+ data: {
+ duration: 21000,
+ offset: 0,
+ level: "TRACE",
+ message: "F01234",
+ isPartial: true,
+ isRoot: true,
+ isError: false,
+ style: {
+ icon: "job",
+ },
+ },
+ },
+ {
+ id: "2",
+ parentId: "1",
+ hasChildren: true,
+ children: ["4"],
+ level: 1,
+ data: {
+ duration: 10000,
+ offset: 0,
+ level: "TRACE",
+ message: "Plasma",
+ isPartial: false,
+ isRoot: false,
+ isError: false,
+ style: {
+ variant: "primary",
+ icon: "operation",
+ },
+ },
+ },
+ {
+ id: "4",
+ parentId: "2",
+ hasChildren: false,
+ children: [],
+ level: 2,
+ data: {
+ duration: 10000,
+ offset: 0,
+ level: "TRACE",
+ message: "Timecard",
+ isPartial: false,
+ isRoot: false,
+ isError: false,
+ style: {
+ variant: "primary",
+ icon: "timecard",
+ accessory: {
+ style: "person",
+ items: [
+ {
+ text: "Anne Barbin",
+ },
+ ],
+ },
+ },
+ },
+ },
+ {
+ id: "3",
+ parentId: "1",
+ hasChildren: true,
+ children: ["5"],
+ level: 1,
+ data: {
+ duration: 8000,
+ offset: 13000,
+ level: "TRACE",
+ message: "Bend",
+ isPartial: true,
+ isRoot: false,
+ isError: false,
+ style: {
+ variant: "primary",
+ icon: "operation",
+ },
+ },
+ },
+ {
+ id: "5",
+ parentId: "3",
+ hasChildren: false,
+ children: [],
+ level: 2,
+ data: {
+ duration: 8000,
+ offset: 13000,
+ level: "TRACE",
+ message: "Timecard",
+ isPartial: true,
+ isRoot: false,
+ isError: false,
+ style: {
+ variant: "primary",
+ icon: "timecard",
+ accessory: {
+ style: "person",
+ items: [
+ {
+ text: "Brad Barbin",
+ },
+ ],
+ },
+ },
+ },
+ },
+ ] as RunEvent[],
+ parentRunFriendlyId: "",
+ duration: 21000,
+ rootSpanStatus: "completed" as const,
+ rootStartedAt: new Date(),
+ },
+ resizeSettings,
+ });
+}
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>();
+export default function LiveView() {
+ const { trace, resizeSettings } = useTypedLoaderData<typeof loader>();
const user = useUser();
const { location, replaceSearchParam } = useReplaceLocation();
const selectedSpanId = getSpanId(location);
@@ -111,36 +218,13 @@ export default function Page() {
}, 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")}
- >
+ <div
+ className={cn(
+ "grid h-full max-h-full grid-cols-1 overflow-hidden bg-background"
+ )}
+ >
+ <ClientOnly fallback={null}>
+ {() => (
<ResizablePanelGroup
direction="horizontal"
className="h-full max-h-full"
@@ -181,17 +265,17 @@ export default function Page() {
minSize={30}
defaultSize={resizeSettings.layout?.[1]}
>
- <SpanView
- runParam={run.friendlyId}
- spanId={selectedSpanId}
- closePanel={() => replaceSearchParam("span")}
- />
+ {/* <SpanView
+ runParam={run.friendlyId}
+ spanId={selectedSpanId}
+ closePanel={() => replaceSearchParam("span")}
+ /> */}
</ResizablePanel>
)}
</ResizablePanelGroup>
- </div>
- </PageBody>
- </>
+ )}
+ </ClientOnly>
+ </div>
);
}
@@ -201,7 +285,7 @@ type TasksTreeViewProps = {
parentRunFriendlyId?: string;
onSelectedIdChanged: (selectedId: string | undefined) => void;
totalDuration: number;
- rootSpanStatus: "executing" | "completed" | "failed";
+ rootSpanStatus: "inprogress" | "completed" | "todo" | "cancelled";
rootStartedAt: Date | undefined;
};
@@ -215,7 +299,7 @@ function TasksTreeView({
rootStartedAt,
}: TasksTreeViewProps) {
const [filterText, setFilterText] = useState("");
- const [errorsOnly, setErrorsOnly] = useState(false);
+ const [wipOnly, setWipOnly] = useState(false);
const [showDurations, setShowDurations] = useState(false);
const [scale, setScale] = useState(0);
const parentRef = useRef<HTMLDivElement>(null);
@@ -242,11 +326,11 @@ function TasksTreeView({
estimatedRowHeight: () => 32,
parentRef,
filter: {
- value: { text: filterText, errorsOnly },
+ value: { text: filterText, wipOnly },
fn: (value, node) => {
- const nodePassesErrorTest =
- (value.errorsOnly && node.data.isError) || !value.errorsOnly;
- if (!nodePassesErrorTest) return false;
+ const isWIP = (value.wipOnly && node.data.isPartial) || !value.wipOnly;
+
+ if (!isWIP) return false;
if (value.text === "") return true;
if (
@@ -261,14 +345,20 @@ function TasksTreeView({
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">
+ <div className="flex items-center justify-between gap-2 border-b border-border">
<SearchField onChange={setFilterText} />
<div className="flex items-center gap-2">
<Switch
variant="small"
- label="Errors only"
- checked={errorsOnly}
- onCheckedChange={(e) => setErrorsOnly(e.valueOf())}
+ label="In Process Only"
+ checked={wipOnly}
+ onCheckedChange={(e) => setWipOnly(e.valueOf())}
+ />
+ <Switch
+ variant="small"
+ label="Show Durations"
+ checked={showDurations}
+ onCheckedChange={(e) => setShowDurations(e.valueOf())}
/>
</div>
</div>
@@ -288,15 +378,11 @@ function TasksTreeView({
>
<div className="grid h-full grid-rows-[2rem_1fr] overflow-hidden">
<div className="flex items-center pr-2">
- {parentRunFriendlyId ? (
+ {parentRunFriendlyId && (
<ShowParentLink runFriendlyId={parentRunFriendlyId} />
- ) : (
- <Paragraph variant="small" className="flex-1 text-charcoal-500">
- This is the root task
- </Paragraph>
)}
<LiveReloadingStatus
- rootSpanCompleted={rootSpanStatus !== "executing"}
+ rootSpanCompleted={rootSpanStatus !== "inprogress"}
/>
</div>
<TreeView
@@ -314,8 +400,8 @@ function TasksTreeView({
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"
+ ? "bg-muted hover:bg-muted/90"
+ : "bg-transparent hover:bg-muted/90"
)}
onClick={() => {
selectNode(node.id);
@@ -332,7 +418,7 @@ function TasksTreeView({
<div
className={cn(
"flex h-8 w-4 items-center",
- node.hasChildren && "hover:bg-charcoal-600"
+ node.hasChildren && "hover:bg-accent"
)}
onClick={(e) => {
e.stopPropagation();
@@ -350,9 +436,9 @@ function TasksTreeView({
>
{node.hasChildren ? (
state.expanded ? (
- <LuChevronDown className="h-4 w-4 text-charcoal-400" />
+ <LuChevronDown className="h-4 w-4 text-gray-400" />
) : (
- <LuChevronUp className="h-4 w-4 text-charcoal-400" />
+ <LuChevronUp className="h-4 w-4 text-gray-400" />
)
) : (
<div className="h-8 w-4" />
@@ -364,12 +450,13 @@ function TasksTreeView({
<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>
+ <Badge variant="outline" className="text-xs">
+ Job
+ </Badge>
)}
</div>
<div className="flex items-center gap-1">
@@ -409,8 +496,9 @@ function TasksTreeView({
/>
</ResizablePanel>
</ResizablePanelGroup>
- <div className="flex items-center justify-between gap-2 border-t border-grid-dimmed px-2">
+ <div className="flex items-center justify-between gap-2 border-t border-border px-2">
<div className="grow @container">
+ {/*
<div className="hidden items-center gap-4 @[42rem]:flex">
<KeyboardShortcuts
expandAllBelowDepth={expandAllBelowDepth}
@@ -419,11 +507,11 @@ function TasksTreeView({
setShowDurations={setShowDurations}
/>
</div>
- <div className="@[42rem]:hidden">
+ <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"
+ className="min-w-[20rem] overflow-y-auto p-2 scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent"
align="start"
>
<Heading size="h3">Keyboard shortcuts</Heading>
@@ -437,14 +525,14 @@ function TasksTreeView({
</div>
</PopoverContent>
</Popover>
- </div>
+ </div> */}
</div>
<div className="flex items-center gap-4">
<Slider
- variant={"tertiary"}
+ variant="primary"
className="w-20"
- LeadingIcon={LuZoomOut}
- TrailingIcon={LuZoomIn}
+ leftIcon={<LuZoomOut />}
+ rightIcon={<LuZoomIn />}
value={[scale]}
onValueChange={(value) => setScale(value[0])}
min={0}
@@ -496,30 +584,28 @@ function TimelineView({
const minTimelineWidth = initialTimelineDimensions?.width ?? 300;
const maxTimelineWidth = minTimelineWidth * 10;
- //we want to live-update the duration if the root span is still executing
+ //we want to live-update the duration if the root span is still in progress
const [duration, setDuration] = useState(totalDuration);
useEffect(() => {
- if (rootSpanStatus !== "executing" || !rootStartedAt) {
+ if (rootSpanStatus !== "inprogress" || !rootStartedAt) {
setDuration(totalDuration);
return;
}
const interval = setInterval(() => {
- setDuration(
- millisecondsToNanoseconds(Date.now() - rootStartedAt.getTime())
- );
- }, 500);
+ setDuration(Date.now() - rootStartedAt.getTime());
+ }, 5000);
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"
+ className="h-full overflow-x-auto overflow-y-hidden scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent"
ref={timelineContainerRef}
>
<Timeline.Root
- durationMs={nanosecondsToMilliseconds(duration * 1.05)}
+ durationMs={duration * 1.05}
scale={scale}
className="h-full overflow-hidden"
minWidth={minTimelineWidth}
@@ -563,14 +649,14 @@ function TimelineView({
);
}}
</Timeline.EquallyDistribute>
- {rootSpanStatus !== "executing" && (
+ {rootSpanStatus !== "inprogress" && (
<Timeline.Point
- ms={nanosecondsToMilliseconds(duration)}
+ ms={duration}
className={cn(
"relative bottom-[2px] text-xxs",
rootSpanStatus === "completed"
- ? "text-success"
- : "text-error"
+ ? "text-emerald-500"
+ : "text-destructive"
)}
>
{(ms) => (
@@ -591,13 +677,13 @@ function TimelineView({
return (
<Timeline.Point
ms={ms}
- className={"h-full border-r border-grid-dimmed"}
+ className={"h-full border-r border-muted"}
/>
);
}}
</Timeline.EquallyDistribute>
<Timeline.Point
- ms={nanosecondsToMilliseconds(duration)}
+ ms={duration}
className={cn(
"h-full border-r",
rootSpanStatus === "completed"
@@ -616,20 +702,20 @@ function TimelineView({
return (
<Timeline.Point
ms={ms}
- className={"h-full border-r border-grid-dimmed"}
+ className={"h-full border-r border-muted"}
/>
);
}}
</Timeline.EquallyDistribute>
{/* The completed line */}
- {rootSpanStatus !== "executing" && (
+ {rootSpanStatus !== "inprogress" && (
<Timeline.Point
- ms={nanosecondsToMilliseconds(duration)}
+ ms={duration}
className={cn(
"h-full border-r",
rootSpanStatus === "completed"
- ? "border-success/30"
- : "border-error/30"
+ ? "border-emerald-500/90"
+ : "border-destructive/30"
)}
/>
)}
@@ -654,8 +740,8 @@ function TimelineView({
className={cn(
"group flex h-8 items-center",
state.selected
- ? "bg-grid-dimmed hover:bg-grid-bright"
- : "bg-transparent hover:bg-grid-dimmed"
+ ? "bg-muted hover:bg-muted/90"
+ : "bg-transparent hover:bg-muted"
)}
// onMouseOver={() => console.log(`hover ${index}`)}
onClick={(e) => {
@@ -665,24 +751,20 @@ function TimelineView({
{node.data.level === "TRACE" ? (
<SpanWithDuration
showDuration={state.selected ? true : showDurations}
- startMs={nanosecondsToMilliseconds(node.data.offset)}
+ startMs={node.data.offset}
durationMs={
node.data.duration
- ? nanosecondsToMilliseconds(node.data.duration)
- : nanosecondsToMilliseconds(
- duration - node.data.offset
- )
+ ? node.data.duration
+ : duration - node.data.offset
}
node={node}
/>
) : (
- <Timeline.Point
- ms={nanosecondsToMilliseconds(node.data.offset)}
- >
+ <Timeline.Point ms={node.data.offset}>
{(ms) => (
<motion.div
className={cn(
- "-ml-1 h-3 w-3 rounded-full border-2 border-background-bright",
+ "-ml-1 h-3 w-3 rounded-full border-2 border-border",
eventBackgroundClassName(node.data)
)}
layoutId={node.id}
@@ -729,7 +811,7 @@ function NodeStatusIcon({ node }: { node: RunEvent }) {
>
Canceled
</Paragraph>
- <TaskRunStatusIcon status="CANCELED" className={cn("size-4")} />
+ <TaskRunStatusIcon status="CANCELED" className={cn("w-4 h-4")} />
</>
);
}
@@ -738,19 +820,19 @@ function NodeStatusIcon({ node }: { node: RunEvent }) {
return (
<TaskRunStatusIcon
status="COMPLETED_WITH_ERRORS"
- className={cn("size-4")}
+ className={cn("w-4 h-4")}
/>
);
}
if (node.data.isPartial) {
- return <TaskRunStatusIcon status={"EXECUTING"} className={cn("size-4")} />;
+ return <TaskRunStatusIcon status={"EXECUTING"} className={cn("w-4 h-4")} />;
}
return (
<TaskRunStatusIcon
status="COMPLETED_SUCCESSFULLY"
- className={cn("size-4")}
+ className={cn("w-4 h-4")}
/>
);
}
@@ -762,7 +844,7 @@ function TaskLine({
isError: boolean;
isSelected: boolean;
}) {
- return <div className={cn("h-8 w-2 border-r border-grid-bright")} />;
+ return <div className={cn("h-8 w-2 border-r border-border")} />;
}
function ShowParentLink({ runFriendlyId }: { runFriendlyId: string }) {
@@ -770,41 +852,32 @@ function ShowParentLink({ runFriendlyId }: { runFriendlyId: string }) {
const { spanParam } = useParams();
return (
- <LinkButton
- variant="minimal/medium"
- to={
- spanParam
- ? v3RunSpanPath(
- organization,
- project,
- {
- friendlyId: runFriendlyId,
- },
- { spanId: spanParam }
- )
- : v3RunPath(organization, project, {
- friendlyId: runFriendlyId,
- })
- }
+ <Button
onMouseEnter={() => setMouseOver(true)}
onMouseLeave={() => setMouseOver(false)}
- fullWidth
- textAlignLeft
- shortcut={{ key: "p" }}
- className="flex-1"
+ asChild
+ className="w-full text-left 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")}
+ <Link
+ to={
+ spanParam
+ ? "/x/scheduling/runs?span=" + spanParam
+ : "x/scheduling/runs"
+ }
>
- Show parent items
- </Paragraph>
- </LinkButton>
+ {mouseOver ? (
+ <ShowParentIconSelected className="h-4 w-4 text-indigo-500" />
+ ) : (
+ <ShowParentIcon className="text-gray-600 h-4 w-4" />
+ )}
+ <Paragraph
+ variant="small"
+ className={cn(mouseOver ? "text-indigo-500" : "text-gray-500")}
+ >
+ Show parent items
+ </Paragraph>
+ </Link>
+ </Button>
);
}
@@ -820,7 +893,7 @@ function LiveReloadingStatus({
<PulsingDot />
<Paragraph
variant="extra-small"
- className="whitespace-nowrap text-blue-500"
+ className="whitespace-nowrap text-primary"
>
Live reloading
</Paragraph>
@@ -832,9 +905,9 @@ 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`}
+ className={`absolute h-full w-full animate-ping rounded-full border border-primary opacity-100 duration-1000`}
/>
- <span className={`h-2 w-2 rounded-full bg-blue-500`} />
+ <span className={`h-2 w-2 rounded-full bg-primary`} />
</span>
);
}
@@ -868,7 +941,7 @@ function SpanWithDuration({
!showDuration && "opacity-0"
)}
>
- <div className="rounded-sm px-1 py-0.5 text-xxs text-text-bright text-shadow-custom">
+ <div className="rounded-sm px-1 py-0.5 text-xxs text-foreground">
{formatDurationMilliseconds(props.durationMs, {
style: "short",
maxDecimalPoints: props.durationMs < 1000 ? 0 : 1,
@@ -886,7 +959,7 @@ function CurrentTimeIndicator({ totalDuration }: { totalDuration: number }) {
return (
<Timeline.FollowCursor>
{(ms) => {
- const ratio = ms / nanosecondsToMilliseconds(totalDuration);
+ const ratio = ms / totalDuration;
let offset = 0.5;
if (ratio < edgeBoundary) {
offset = lerp(0, 0.5, ratio / edgeBoundary);
@@ -898,7 +971,7 @@ function CurrentTimeIndicator({ totalDuration }: { totalDuration: number }) {
<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"
+ className="absolute w-fit whitespace-nowrap rounded-sm border border-border bg-gray-700 px-1 py-0.5 text-xxs tabular-nums text-text-bright"
style={{
left: `${offset * 100}%`,
transform: `translateX(-${offset * 100}%)`,
@@ -910,7 +983,7 @@ function CurrentTimeIndicator({ totalDuration }: { totalDuration: number }) {
})}
</div>
</div>
- <div className="w-px grow border-r border-charcoal-600" />
+ <div className="w-px grow border-r border-border" />
</div>
);
}}
@@ -918,6 +991,7 @@ function CurrentTimeIndicator({ totalDuration }: { totalDuration: number }) {
);
}
+/*
function KeyboardShortcuts({
expandAllBelowDepth,
collapseAllBelowDepth,
@@ -991,7 +1065,7 @@ function ShortcutWithAction({
title: string;
action: () => void;
}) {
- useShortcutKeys({
+ useKeyboardShortcuts({
shortcut,
action,
});
@@ -1035,6 +1109,7 @@ function NumberShortcuts({
</div>
);
}
+*/
function SearchField({ onChange }: { onChange: (value: string) => void }) {
const [value, setValue] = useState("");
@@ -1043,19 +1118,21 @@ function SearchField({ onChange }: { onChange: (value: string) => void }) {
onChange(text);
}, 250);
- const updateValue = useCallback((value: string) => {
+ const updateValue = (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)}
- />
+ <InputGroup insetRing className="border-transparent rounded-none ring-0">
+ <InputLeftElement>
+ <LuSearch className="h-4 w-4 text-muted-foreground" />
+ </InputLeftElement>
+ <Input
+ placeholder="Search Job"
+ value={value}
+ onChange={(e) => updateValue(e.target.value)}
+ />
+ </InputGroup>
);
}
diff --git a/apps/carbon/app/utils/resizablePanel.ts b/apps/carbon/app/utils/resizablePanel.ts
new file mode 100644
index 0000000000..47f30a814d
--- /dev/null
+++ b/apps/carbon/app/utils/resizablePanel.ts
@@ -0,0 +1,39 @@
+import { z } from "zod";
+
+const resizableConfig = z
+ .object({ layout: z.array(z.number()).optional() })
+ .default({ layout: undefined });
+type ResizableConfig = z.infer<typeof resizableConfig>;
+
+function getCookieValue(
+ cookieHeader: string | null,
+ cookieName: string
+): ResizableConfig {
+ const cookieValue = cookieHeader?.split(`${cookieName}=`)[1]?.split(";")[0];
+ if (!cookieValue) {
+ return { layout: undefined };
+ }
+ try {
+ const json = JSON.parse(cookieValue);
+ return resizableConfig.parse(json);
+ } catch (e) {
+ return { layout: undefined };
+ }
+}
+
+//run page
+const runResizableName = "resizable-panels:run";
+
+export async function getResizableRunSettings(
+ request: Request
+): Promise<ResizableConfig> {
+ const cookieHeader = request.headers.get("Cookie");
+ return getCookieValue(cookieHeader, runResizableName);
+}
+
+export async function setResizableRunSettings(
+ document: Document,
+ layout: number[]
+) {
+ document.cookie = `${runResizableName}=${JSON.stringify({ layout })}`;
+}
diff --git a/apps/carbon/package.json b/apps/carbon/package.json
index 2438458eb9..2997fdea72 100644
--- a/apps/carbon/package.json
+++ b/apps/carbon/package.json
@@ -62,6 +62,7 @@
"react-pdf": "^7.7.1",
"react-phone-number-input": "^3.3.9",
"remix-flat-routes": "^0.6.4",
+ "remix-typedjson": "^0.4.1",
"resend": "^3.1.0",
"tailwind-merge": "^2.2.1",
"tailwind-scrollbar": "^3.0.5",
diff --git a/package-lock.json b/package-lock.json
index a035fb1817..a11fbc2f47 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -87,6 +87,7 @@
"react-pdf": "^7.7.1",
"react-phone-number-input": "^3.3.9",
"remix-flat-routes": "^0.6.4",
+ "remix-typedjson": "^0.4.1",
"resend": "^3.1.0",
"tailwind-merge": "^2.2.1",
"tailwind-scrollbar": "^3.0.5",
@@ -4472,6 +4473,39 @@
}
}
},
+ "node_modules/@radix-ui/react-slider": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-slider/-/react-slider-1.1.2.tgz",
+ "integrity": "sha512-NKs15MJylfzVsCagVSWKhGGLNR1W9qWs+HtgbmjjVUB3B9+lb3PYoXxVju3kOrpf0VKyVCtZp+iTwVoqpa1Chw==",
+ "dependencies": {
+ "@babel/runtime": "^7.13.10",
+ "@radix-ui/number": "1.0.1",
+ "@radix-ui/primitive": "1.0.1",
+ "@radix-ui/react-collection": "1.0.3",
+ "@radix-ui/react-compose-refs": "1.0.1",
+ "@radix-ui/react-context": "1.0.1",
+ "@radix-ui/react-direction": "1.0.1",
+ "@radix-ui/react-primitive": "1.0.3",
+ "@radix-ui/react-use-controllable-state": "1.0.1",
+ "@radix-ui/react-use-layout-effect": "1.0.1",
+ "@radix-ui/react-use-previous": "1.0.1",
+ "@radix-ui/react-use-size": "1.0.1"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0",
+ "react-dom": "^16.8 || ^17.0 || ^18.0"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
"node_modules/@radix-ui/react-slot": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.0.2.tgz",
@@ -17876,6 +17910,12 @@
"node": ">=14.18.0"
}
},
+ "node_modules/humanize-duration": {
+ "version": "3.32.0",
+ "resolved": "https://registry.npmjs.org/humanize-duration/-/humanize-duration-3.32.0.tgz",
+ "integrity": "sha512-6WsXYTHJr7hXKqoqf5zoWza/lANRAqGlbnZnm0cjDykbXuez1JVXOQGmq0EPB45pXYAJyueRA3S3hfhmMbrMEQ==",
+ "dev": true
+ },
"node_modules/humanize-ms": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/humanize-ms/-/humanize-ms-1.2.1.tgz",
@@ -33308,6 +33348,16 @@
"resolved": "https://registry.npmjs.org/remeda/-/remeda-1.61.0.tgz",
"integrity": "sha512-caKfSz9rDeSKBQQnlJnVW3mbVdFgxgGWQKq1XlFokqjf+hQD5gxutLGTTY2A/x24UxVyJe9gH5fAkFI63ULw4A=="
},
+ "node_modules/remix-typedjson": {
+ "version": "0.4.1",
+ "resolved": "https://registry.npmjs.org/remix-typedjson/-/remix-typedjson-0.4.1.tgz",
+ "integrity": "sha512-AL6LdNajqce1Exy6aB1bD6GYMk90S6H31e8kDCi6jLgBi4K82Ph604lqGGzalswaPPYckYK+NZzgvhWEY7JCDw==",
+ "peerDependencies": {
+ "@remix-run/react": "^1.16.0 || ^2.0",
+ "@remix-run/server-runtime": "^1.16.0 || ^2.0",
+ "react": "^17.0.2 || ^18.0.0"
+ }
+ },
"node_modules/remote-git-tags": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/remote-git-tags/-/remote-git-tags-3.0.0.tgz",
@@ -39326,6 +39376,7 @@
"@radix-ui/react-scroll-area": "^1.0.5",
"@radix-ui/react-select": "^2.0.0",
"@radix-ui/react-separator": "^1.0.3",
+ "@radix-ui/react-slider": "^1.1.2",
"@radix-ui/react-slot": "^1.0.2",
"@radix-ui/react-switch": "^1.0.3",
"@radix-ui/react-tabs": "^1.0.4",
@@ -39358,7 +39409,7 @@
"is-hotkey": "^0.2.0",
"react-aria-components": "1.0.1",
"react-colorful": "^5.6.1",
- "react-resizable-panels": "^2.0.19",
+ "react-resizable-panels": "^2.0.9",
"sonner": "1.4.41",
"tailwind-merge": "^2.2.1",
"tailwindcss-animate": "^1.0.7"
@@ -39471,6 +39522,7 @@
"@types/react-dom": "^18.2.24",
"eslint": "^8.23.1",
"eslint-config-carbon": "*",
+ "humanize-duration": "^3.32.0",
"jest": "^26.6.3",
"react": "^18.2.0",
"tsup": "^6.5.0",
diff --git a/packages/react/package.json b/packages/react/package.json
index 6f994fa781..af3ac4e692 100644
--- a/packages/react/package.json
+++ b/packages/react/package.json
@@ -14,6 +14,7 @@
"@radix-ui/react-scroll-area": "^1.0.5",
"@radix-ui/react-select": "^2.0.0",
"@radix-ui/react-separator": "^1.0.3",
+ "@radix-ui/react-slider": "^1.1.2",
"@radix-ui/react-slot": "^1.0.2",
"@radix-ui/react-switch": "^1.0.3",
"@radix-ui/react-tabs": "^1.0.4",
@@ -46,7 +47,7 @@
"is-hotkey": "^0.2.0",
"react-aria-components": "1.0.1",
"react-colorful": "^5.6.1",
- "react-resizable-panels": "^2.0.19",
+ "react-resizable-panels": "^2.0.9",
"sonner": "1.4.41",
"tailwind-merge": "^2.2.1",
"tailwindcss-animate": "^1.0.7"
diff --git a/packages/react/src/Input.tsx b/packages/react/src/Input.tsx
index 012aa861f0..2c804d44cc 100644
--- a/packages/react/src/Input.tsx
+++ b/packages/react/src/Input.tsx
@@ -10,7 +10,7 @@ import { getValidChildren } from "./utils/react";
const InputGroupContext = createContext<boolean>(false);
const inputGroupVariants = cva(
- "flex relative w-full bg-transparent text-foreground shadow-sm focus-within:outline-none border border-input ring-offset-background focus-within:outline-none focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2",
+ "flex relative w-full bg-transparent text-foreground shadow-sm focus-within:outline-none border border-input",
{
variants: {
size: {
@@ -27,18 +27,24 @@ const inputGroupVariants = cva(
true: "border-destructive focus-within:ring-destructive",
false: "",
},
+ insetRing: {
+ false:
+ "ring-offset-background focus-within:outline-none focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2",
+ true: "focus-within:outline-none focus-within:box-shadow-[inset 0 0 0 2px var(--ring-color)]",
+ },
},
defaultVariants: {
size: "md",
isDisabled: false,
isInvalid: false,
+ insetRing: false,
},
}
);
export interface InputGroupProps
extends Omit<InputHTMLAttributes<HTMLInputElement>, "size">,
- VariantProps<typeof inputVariants> {
+ VariantProps<typeof inputGroupVariants> {
isDisabled?: boolean;
isInvalid?: boolean;
}
@@ -49,6 +55,7 @@ const InputGroup = forwardRef<HTMLDivElement, InputGroupProps>(
className,
isInvalid = false,
isDisabled = false,
+ insetRing,
size,
children,
...props
@@ -78,6 +85,7 @@ const InputGroup = forwardRef<HTMLDivElement, InputGroupProps>(
size,
isDisabled,
isInvalid,
+ insetRing,
className,
})
)}
diff --git a/packages/react/src/Resizable.tsx b/packages/react/src/Resizable.tsx
index ee07ec0d7e..660fbebfdf 100644
--- a/packages/react/src/Resizable.tsx
+++ b/packages/react/src/Resizable.tsx
@@ -1,3 +1,5 @@
+"use client";
+
import { LuGripVertical } from "react-icons/lu";
import * as ResizablePrimitive from "react-resizable-panels";
@@ -40,4 +42,4 @@ const ResizableHandle = ({
</ResizablePrimitive.PanelResizeHandle>
);
-export { ResizablePanelGroup, ResizablePanel, ResizableHandle };
+export { ResizableHandle, ResizablePanel, ResizablePanelGroup };
diff --git a/packages/react/src/Slider.tsx b/packages/react/src/Slider.tsx
new file mode 100644
index 0000000000..20b50cd2ba
--- /dev/null
+++ b/packages/react/src/Slider.tsx
@@ -0,0 +1,70 @@
+import * as RadixSlider from "@radix-ui/react-slider";
+import { cloneElement, type ComponentProps, type ReactElement } from "react";
+import { cn } from "./utils/cn";
+
+const variants = {
+ primary: {
+ container: "h-6 gap-1 rounded-sm hover:bg-muted px-1",
+ icons: "h-4 w-4 text-foreground",
+ root: "h-4",
+ track: "h-1 bg-accent group-hover:bg-secondary",
+ range: "bg-transparent group-hover:bg-primary",
+ thumb: "h-3 w-3 border-2 border-primary bg-background shadow-md",
+ },
+};
+
+type VariantName = keyof typeof variants;
+
+export type SliderProps = ComponentProps<typeof RadixSlider.Root> & {
+ leftIcon?: ReactElement;
+ rightIcon?: ReactElement;
+ variant: VariantName;
+};
+
+export function Slider({
+ variant,
+ className,
+ leftIcon,
+ rightIcon,
+ ...props
+}: SliderProps) {
+ const variation = variants[variant];
+ return (
+ <div className={cn("group flex items-center", variation.container)}>
+ {leftIcon &&
+ cloneElement(leftIcon, {
+ className: !leftIcon.props?.size
+ ? cn("mr-2 h-4 w-4", leftIcon.props.className)
+ : cn("mr-2", leftIcon.props.className),
+ })}
+ <RadixSlider.Root
+ className={cn(
+ "relative flex touch-none select-none items-center",
+ variation.root,
+ className
+ )}
+ {...props}
+ >
+ <RadixSlider.Track
+ className={cn("relative grow rounded-full", variation.track)}
+ >
+ <RadixSlider.Range
+ className={cn("absolute h-full rounded-full", variation.range)}
+ />
+ </RadixSlider.Track>
+ <RadixSlider.Thumb
+ className={cn(
+ "block cursor-pointer rounded-full transition focus:outline-none",
+ variation.thumb
+ )}
+ />
+ </RadixSlider.Root>
+ {rightIcon &&
+ cloneElement(rightIcon, {
+ className: !rightIcon.props?.size
+ ? cn("ml-2 h-4 w-4", rightIcon.props.className)
+ : cn("ml-2", rightIcon.props.className),
+ })}
+ </div>
+ );
+}
diff --git a/packages/react/src/Switch.tsx b/packages/react/src/Switch.tsx
index 54bdcc5259..4c58807dad 100644
--- a/packages/react/src/Switch.tsx
+++ b/packages/react/src/Switch.tsx
@@ -6,25 +6,64 @@ import { forwardRef } from "react";
import { cn } from "./utils/cn";
+const variations = {
+ large: {
+ container:
+ "flex items-center gap-x-2 rounded-md hover:bg-muted p-2 transition",
+ root: "h-6 w-11",
+ thumb:
+ "h-5 w-5 data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0",
+ text: "text-sm",
+ },
+ small: {
+ container:
+ "flex items-center gap-x-1.5 rounded hover:bg-muted pr-1 py-[0.1rem] pl-1.5 transition",
+ root: "h-3 w-6",
+ thumb:
+ "h-2.5 w-2.5 data-[state=checked]:translate-x-2.5 data-[state=unchecked]:translate-x-0",
+ text: "text-xs",
+ },
+};
+
+type SwitchProps = ComponentPropsWithoutRef<typeof SwitchPrimitives.Root> & {
+ variant?: keyof typeof variations;
+ label?: string | React.ReactNode;
+};
+
const Switch = forwardRef<
ElementRef<typeof SwitchPrimitives.Root>,
- ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>
->(({ className, ...props }, ref) => (
- <SwitchPrimitives.Root
- className={cn(
- "peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",
- className
- )}
- {...props}
- ref={ref}
- >
- <SwitchPrimitives.Thumb
- className={cn(
- "pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0"
- )}
- />
- </SwitchPrimitives.Root>
-));
+ SwitchProps
+>(({ className, label, variant, ...props }, ref) => {
+ const { container, root, thumb, text } = variations[variant ?? "large"];
+
+ return (
+ <SwitchPrimitives.Root
+ className={cn("group", container, className)}
+ {...props}
+ ref={ref}
+ >
+ {label ? (
+ <label className={cn("whitespace-nowrap", text)}>
+ {typeof label === "string" ? <span>{label}</span> : label}
+ </label>
+ ) : null}
+ <div
+ className={cn(
+ "group-focus-visible:ring-ring group-focus-visible:ring-offset-background peer inline-flex shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors group-focus-visible:ring-2 group-focus-visible:ring-offset-2 group-disabled:cursor-not-allowed group-disabled:opacity-50 group-data-[state=checked]:bg-primary group-data-[state=unchecked]:bg-input focus-visible:outline-none",
+ root,
+ className
+ )}
+ >
+ <SwitchPrimitives.Thumb
+ className={cn(
+ "pointer-events-none block rounded-full bg-background shadow-lg ring-0 transition-transform",
+ thumb
+ )}
+ />
+ </div>
+ </SwitchPrimitives.Root>
+ );
+});
Switch.displayName = SwitchPrimitives.Root.displayName;
export { Switch };
diff --git a/packages/react/src/hooks/index.ts b/packages/react/src/hooks/index.ts
index 2707f63683..6e213757e8 100644
--- a/packages/react/src/hooks/index.ts
+++ b/packages/react/src/hooks/index.ts
@@ -2,6 +2,7 @@ import useDebounce from "./useDebounce";
import useDisclosure from "./useDisclosure";
import useEscape from "./useEscape";
import useHydrated from "./useHydrated";
+import useInitialDimensions from "./useInitialDimenions";
import useInterval from "./useInterval";
import useKeyboardShortcuts from "./useKeyboardShortcuts";
import useLocalStorage from "./useLocalStorage";
@@ -14,6 +15,7 @@ export {
useDisclosure,
useEscape,
useHydrated,
+ useInitialDimensions,
useInterval,
useKeyboardShortcuts,
useLocalStorage,
diff --git a/packages/react/src/hooks/useInitialDimenions.ts b/packages/react/src/hooks/useInitialDimenions.ts
new file mode 100644
index 0000000000..0f7e0a8ead
--- /dev/null
+++ b/packages/react/src/hooks/useInitialDimenions.ts
@@ -0,0 +1,15 @@
+import { useEffect, useState } from "react";
+
+export default function useInitialDimensions(
+ ref: React.RefObject<HTMLElement>
+) {
+ const [dimensions, setDimensions] = useState<DOMRectReadOnly | null>(null);
+
+ useEffect(() => {
+ if (ref.current) {
+ setDimensions(ref.current.getBoundingClientRect());
+ }
+ }, [ref]);
+
+ return dimensions;
+}
diff --git a/packages/react/src/index.tsx b/packages/react/src/index.tsx
index e5c7a822dc..2b7726957d 100644
--- a/packages/react/src/index.tsx
+++ b/packages/react/src/index.tsx
@@ -209,6 +209,7 @@ import {
SelectValue,
} from "./Select";
import { Skeleton } from "./Skeleton";
+import { Slider } from "./Slider";
import { Spinner } from "./Spinner";
import { Status } from "./Status";
import { Switch } from "./Switch";
@@ -229,6 +230,7 @@ import {
useDisclosure,
useEscape,
useHydrated,
+ useInitialDimensions,
useInterval,
useKeyboardShortcuts,
useMount,
@@ -415,6 +417,7 @@ export {
SelectTrigger,
SelectValue,
Skeleton,
+ Slider,
Spinner,
Status,
Switch,
@@ -449,6 +452,7 @@ export {
useEditor,
useEscape,
useHydrated,
+ useInitialDimensions,
useInterval,
useKeyboardShortcuts,
useModalCardType,
diff --git a/packages/utils/package.json b/packages/utils/package.json
index 7d4751ea62..f1e86ebe94 100644
--- a/packages/utils/package.json
+++ b/packages/utils/package.json
@@ -12,6 +12,7 @@
"@types/react-dom": "^18.2.24",
"eslint": "^8.23.1",
"eslint-config-carbon": "*",
+ "humanize-duration": "^3.32.0",
"jest": "^26.6.3",
"react": "^18.2.0",
"tsup": "^6.5.0",
diff --git a/packages/utils/src/duration.ts b/packages/utils/src/duration.ts
new file mode 100644
index 0000000000..9290c72611
--- /dev/null
+++ b/packages/utils/src/duration.ts
@@ -0,0 +1,96 @@
+import type { Unit } from "humanize-duration";
+import humanizeDuration from "humanize-duration";
+
+function dateDifference(date1: Date, date2: Date) {
+ return Math.abs(date1.getTime() - date2.getTime());
+}
+
+type DurationOptions = {
+ style?: "long" | "short";
+ maxDecimalPoints?: number;
+ units?: Unit[];
+};
+
+export function formatDuration(
+ start?: Date | null,
+ end?: Date | null,
+ options?: DurationOptions
+): string {
+ if (!start || !end) {
+ return "–";
+ }
+
+ return formatDurationMilliseconds(dateDifference(start, end), options);
+}
+
+export function nanosecondsToMilliseconds(nanoseconds: number): number {
+ return nanoseconds / 1_000_000;
+}
+
+export function millisecondsToNanoseconds(milliseconds: number): number {
+ return milliseconds * 1_000_000;
+}
+
+export function formatDurationNanoseconds(
+ nanoseconds: number,
+ options?: DurationOptions
+): string {
+ return formatDurationMilliseconds(
+ nanosecondsToMilliseconds(nanoseconds),
+ options
+ );
+}
+
+const aboveOneSecondUnits = ["d", "h", "m", "s"] as Unit[];
+const belowOneSecondUnits = ["ms"] as Unit[];
+
+export function formatDurationMilliseconds(
+ milliseconds: number,
+ options?: DurationOptions
+): string {
+ let duration = humanizeDuration(milliseconds, {
+ units: options?.units
+ ? options.units
+ : milliseconds < 1000
+ ? belowOneSecondUnits
+ : aboveOneSecondUnits,
+ maxDecimalPoints: options?.maxDecimalPoints ?? 1,
+ largest: 2,
+ });
+
+ if (!options) {
+ return duration;
+ }
+
+ switch (options.style) {
+ case "short":
+ duration = duration.replace(" milliseconds", "ms");
+ duration = duration.replace(" millisecond", "ms");
+ duration = duration.replace(" seconds", "s");
+ duration = duration.replace(" second", "s");
+ duration = duration.replace(" minutes", "m");
+ duration = duration.replace(" minute", "m");
+ duration = duration.replace(" hours", "h");
+ duration = duration.replace(" hour", "h");
+ duration = duration.replace(" days", "d");
+ duration = duration.replace(" day", "d");
+ duration = duration.replace(" weeks", "w");
+ duration = duration.replace(" week", "w");
+ duration = duration.replace(" months", "mo");
+ duration = duration.replace(" month", "mo");
+ duration = duration.replace(" years", "y");
+ duration = duration.replace(" year", "y");
+ }
+
+ return duration;
+}
+
+export function formatDurationInDays(milliseconds: number): string {
+ let duration = humanizeDuration(milliseconds, {
+ maxDecimalPoints: 0,
+ largest: 2,
+ units: ["d"],
+ });
+
+ return duration;
+}
diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.ts
index 06e19c966b..d88cba6fc7 100644
--- a/packages/utils/src/index.ts
+++ b/packages/utils/src/index.ts
@@ -2,6 +2,7 @@ export * from "./accounting";
export * from "./arrays";
export * from "./color";
export * from "./date";
+export * from "./duration";
export * from "./file";
export * from "./geo";
export * from "./keyboard";