@tryghost/shade 0.1.0-alpha.1 → 0.1.0-alpha.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +30 -64
- package/es/components/page-templates/list-page.js +2 -1
- package/es/components/page-templates/list-page.js.map +1 -1
- package/es/components/patterns/gh-chart.js +2 -1
- package/es/components/patterns/gh-chart.js.map +1 -1
- package/es/components/patterns/page-header.js +5 -2
- package/es/components/patterns/page-header.js.map +1 -1
- package/es/components/ui/chart.js +2 -29
- package/es/components/ui/chart.js.map +1 -1
- package/es/components/ui/combobox.js +2 -2
- package/es/components/ui/combobox.js.map +1 -1
- package/es/components/ui/dialog.js +32 -8
- package/es/components/ui/dialog.js.map +1 -1
- package/es/components/ui/pagemenu.js +33 -9
- package/es/components/ui/pagemenu.js.map +1 -1
- package/es/components/ui/token-field.js +2 -2
- package/es/components/ui/token-field.js.map +1 -1
- package/es/components.js +2 -2
- package/es/index.js +2 -2
- package/es/lib/date-utils.js +151 -0
- package/es/lib/date-utils.js.map +1 -0
- package/es/lib/ds-utils.js +1 -71
- package/es/lib/ds-utils.js.map +1 -1
- package/es/lib/utils.js +2 -1
- package/es/utils.js +2 -1
- package/package.json +4 -3
- package/styles.css +6 -0
- package/types/components/page-templates/list-page.d.ts +2 -1
- package/types/components/page-templates/list-page.d.ts.map +1 -1
- package/types/components/patterns/page-header.d.ts +5 -2
- package/types/components/patterns/page-header.d.ts.map +1 -1
- package/types/components/patterns/share-modal.d.ts +1 -1
- package/types/components/ui/chart.d.ts +1 -17
- package/types/components/ui/chart.d.ts.map +1 -1
- package/types/components/ui/combobox.d.ts.map +1 -1
- package/types/components/ui/dialog.d.ts +11 -2
- package/types/components/ui/dialog.d.ts.map +1 -1
- package/types/components/ui/pagemenu.d.ts +3 -0
- package/types/components/ui/pagemenu.d.ts.map +1 -1
- package/types/components/ui/token-field.d.ts +2 -2
- package/types/components/ui/token-field.d.ts.map +1 -1
- package/types/lib/date-utils.d.ts +17 -0
- package/types/lib/date-utils.d.ts.map +1 -0
- package/types/lib/ds-utils.d.ts +0 -16
- package/types/lib/ds-utils.d.ts.map +1 -1
- package/types/lib/utils.d.ts +1 -0
- package/types/lib/utils.d.ts.map +1 -1
- package/types/utils.d.ts +2 -1
- package/types/utils.d.ts.map +1 -1
|
@@ -1,25 +1,49 @@
|
|
|
1
1
|
import { cn } from "../../lib/ds-utils.js";
|
|
2
2
|
import { ShadeScope } from "../../shade-scope.js";
|
|
3
3
|
import * as React$1 from "react";
|
|
4
|
-
import { jsx, jsxs } from "react/jsx-runtime";
|
|
4
|
+
import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
|
|
5
5
|
import * as DialogPrimitive from "@radix-ui/react-dialog";
|
|
6
6
|
//#region src/components/ui/dialog.tsx
|
|
7
|
-
var
|
|
7
|
+
var DialogModalContext = React$1.createContext(true);
|
|
8
|
+
var Dialog = ({ modal = true, ...props }) => /* @__PURE__ */ jsx(DialogModalContext.Provider, {
|
|
9
|
+
value: modal,
|
|
10
|
+
children: /* @__PURE__ */ jsx(DialogPrimitive.Root, {
|
|
11
|
+
modal,
|
|
12
|
+
...props
|
|
13
|
+
})
|
|
14
|
+
});
|
|
8
15
|
var DialogTrigger = DialogPrimitive.Trigger;
|
|
9
16
|
var DialogPortal = DialogPrimitive.Portal;
|
|
10
17
|
var DialogClose = DialogPrimitive.Close;
|
|
11
18
|
var DialogOverlay = React$1.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(DialogPrimitive.Overlay, {
|
|
12
19
|
ref,
|
|
13
20
|
className: cn("fixed inset-0 z-50 transform-gpu bg-black/30 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0 dark:bg-black/60", className),
|
|
21
|
+
"data-slot": "dialog-overlay",
|
|
14
22
|
...props
|
|
15
23
|
}));
|
|
16
24
|
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;
|
|
17
|
-
var
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
25
|
+
var dialogPanelClassName = "z-50 grid w-full max-w-lg transform-gpu gap-6 bg-surface-elevated-2 p-6 shadow-lg outline-hidden duration-200 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95";
|
|
26
|
+
var DialogContent = React$1.forwardRef(({ className, children, scroll = "fixed", ...props }, ref) => {
|
|
27
|
+
const modal = React$1.useContext(DialogModalContext);
|
|
28
|
+
const panel = /* @__PURE__ */ jsx(DialogPrimitive.Content, {
|
|
29
|
+
ref,
|
|
30
|
+
className: cn(scroll === "overlay" ? "pointer-events-auto relative rounded-lg" : "fixed top-[8vmin] left-[50%] translate-x-[-50%] sm:rounded-lg", dialogPanelClassName, className),
|
|
31
|
+
...props,
|
|
32
|
+
children
|
|
33
|
+
});
|
|
34
|
+
const scrollingPanel = /* @__PURE__ */ jsx("div", {
|
|
35
|
+
className: "flex min-h-full items-start justify-center px-4 py-[8vmin]",
|
|
36
|
+
children: panel
|
|
37
|
+
});
|
|
38
|
+
return /* @__PURE__ */ jsx(DialogPortal, { children: /* @__PURE__ */ jsx(ShadeScope, { children: scroll === "overlay" ? modal ? /* @__PURE__ */ jsx(DialogOverlay, {
|
|
39
|
+
className: "overflow-y-auto duration-200",
|
|
40
|
+
children: scrollingPanel
|
|
41
|
+
}) : /* @__PURE__ */ jsx("div", {
|
|
42
|
+
className: "pointer-events-none fixed inset-0 z-50 overflow-y-auto",
|
|
43
|
+
"data-slot": "dialog-scroller",
|
|
44
|
+
children: scrollingPanel
|
|
45
|
+
}) : /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx(DialogOverlay, {}), panel] }) }) });
|
|
46
|
+
});
|
|
23
47
|
DialogContent.displayName = DialogPrimitive.Content.displayName;
|
|
24
48
|
var DialogHeader = ({ className, ...props }) => /* @__PURE__ */ jsx("div", {
|
|
25
49
|
className: cn("flex flex-col gap-y-1.5 text-center sm:text-left", className),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dialog.js","names":[],"sources":["../../../src/components/ui/dialog.tsx"],"sourcesContent":["import * as React from 'react';\nimport * as DialogPrimitive from '@radix-ui/react-dialog';\n\nimport { cn } from '@/lib/utils';\nimport { ShadeScope } from '@/shade-scope';\n\nconst Dialog = DialogPrimitive.Root;\n\nconst DialogTrigger = DialogPrimitive.Trigger;\n\nconst DialogPortal = DialogPrimitive.Portal;\n\nconst DialogClose = DialogPrimitive.Close;\n\nconst DialogOverlay = React.forwardRef<\n React.ElementRef<typeof DialogPrimitive.Overlay>,\n React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>\n>(({ className, ...props }, ref) => (\n <DialogPrimitive.Overlay\n ref={ref}\n className={cn(\n 'fixed inset-0 z-50 transform-gpu bg-black/30 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0 dark:bg-black/60',\n className,\n )}\n {...props}\n />\n));\nDialogOverlay.displayName = DialogPrimitive.Overlay.displayName;\n\
|
|
1
|
+
{"version":3,"file":"dialog.js","names":[],"sources":["../../../src/components/ui/dialog.tsx"],"sourcesContent":["import * as React from 'react';\nimport * as DialogPrimitive from '@radix-ui/react-dialog';\n\nimport { cn } from '@/lib/utils';\nimport { ShadeScope } from '@/shade-scope';\n\n// Radix keeps whether a dialog is modal to itself, and the overlay scroll layout needs to know.\nconst DialogModalContext = React.createContext(true);\n\nconst Dialog = ({ modal = true, ...props }: React.ComponentProps<typeof DialogPrimitive.Root>) => (\n <DialogModalContext.Provider value={modal}>\n <DialogPrimitive.Root modal={modal} {...props} />\n </DialogModalContext.Provider>\n);\n\nconst DialogTrigger = DialogPrimitive.Trigger;\n\nconst DialogPortal = DialogPrimitive.Portal;\n\nconst DialogClose = DialogPrimitive.Close;\n\nconst DialogOverlay = React.forwardRef<\n React.ElementRef<typeof DialogPrimitive.Overlay>,\n React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>\n>(({ className, ...props }, ref) => (\n <DialogPrimitive.Overlay\n ref={ref}\n className={cn(\n 'fixed inset-0 z-50 transform-gpu bg-black/30 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0 dark:bg-black/60',\n className,\n )}\n data-slot=\"dialog-overlay\"\n {...props}\n />\n));\nDialogOverlay.displayName = DialogPrimitive.Overlay.displayName;\n\n// The panel itself, shared by both ways a dialog can sit on the page.\nconst dialogPanelClassName =\n 'z-50 grid w-full max-w-lg transform-gpu gap-6 bg-surface-elevated-2 p-6 shadow-lg outline-hidden duration-200 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95';\n\nexport interface DialogContentProps extends React.ComponentPropsWithoutRef<\n typeof DialogPrimitive.Content\n> {\n /**\n * How a dialog taller than the window scrolls. `fixed` (the default) pins the dialog near\n * the top of the window, so it needs its own height limit and inner scroll. `overlay` makes\n * the backdrop the scroll container instead: the whole dialog scrolls as one piece, the way\n * a page does.\n */\n scroll?: 'fixed' | 'overlay';\n}\n\nconst DialogContent = React.forwardRef<\n React.ElementRef<typeof DialogPrimitive.Content>,\n DialogContentProps\n>(({ className, children, scroll = 'fixed', ...props }, ref) => {\n const modal = React.useContext(DialogModalContext);\n\n const panel = (\n <DialogPrimitive.Content\n ref={ref}\n className={cn(\n scroll === 'overlay'\n ? 'pointer-events-auto relative rounded-lg'\n : 'fixed top-[8vmin] left-[50%] translate-x-[-50%] sm:rounded-lg',\n dialogPanelClassName,\n className,\n )}\n {...props}\n >\n {children}\n </DialogPrimitive.Content>\n );\n\n // The space around the dialog is padding on this wrapper, not on the scroll container:\n // browsers leave a scroll container's own bottom padding out of what it scrolls, which\n // would leave the dialog flush with the bottom of the window.\n const scrollingPanel = (\n <div className=\"flex min-h-full items-start justify-center px-4 py-[8vmin]\">{panel}</div>\n );\n\n return (\n <DialogPortal>\n <ShadeScope>\n {scroll === 'overlay' ? (\n modal ? (\n // The dialog sits inside the backdrop here, so the backdrop animates as long as the\n // dialog does; otherwise closing unmounts the dialog part-way through its animation.\n <DialogOverlay className=\"overflow-y-auto duration-200\">{scrollingPanel}</DialogOverlay>\n ) : (\n // Radix renders no backdrop for a non-modal dialog, and the page behind stays\n // usable, so this scroll container lets presses beside the dialog through.\n <div\n className=\"pointer-events-none fixed inset-0 z-50 overflow-y-auto\"\n data-slot=\"dialog-scroller\"\n >\n {scrollingPanel}\n </div>\n )\n ) : (\n <>\n <DialogOverlay />\n {panel}\n </>\n )}\n </ShadeScope>\n </DialogPortal>\n );\n});\nDialogContent.displayName = DialogPrimitive.Content.displayName;\n\nconst DialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (\n <div className={cn('flex flex-col gap-y-1.5 text-center sm:text-left', className)} {...props} />\n);\nDialogHeader.displayName = 'DialogHeader';\n\nconst DialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (\n <div\n className={cn(\n 'flex flex-col-reverse sm:flex-row sm:items-end sm:justify-end sm:gap-2 [&_button]:min-w-20',\n className,\n )}\n {...props}\n />\n);\nDialogFooter.displayName = 'DialogFooter';\n\nconst DialogTitle = React.forwardRef<\n React.ElementRef<typeof DialogPrimitive.Title>,\n React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>\n>(({ className, ...props }, ref) => (\n <DialogPrimitive.Title\n ref={ref}\n className={cn('text-xl leading-none font-semibold tracking-tight', className)}\n {...props}\n />\n));\nDialogTitle.displayName = DialogPrimitive.Title.displayName;\n\nconst DialogDescription = React.forwardRef<\n React.ElementRef<typeof DialogPrimitive.Description>,\n React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>\n>(({ className, ...props }, ref) => (\n <DialogPrimitive.Description\n ref={ref}\n className={cn('text-muted-foreground', className)}\n {...props}\n />\n));\nDialogDescription.displayName = DialogPrimitive.Description.displayName;\n\nexport {\n Dialog,\n DialogPortal,\n DialogOverlay,\n DialogTrigger,\n DialogClose,\n DialogContent,\n DialogHeader,\n DialogFooter,\n DialogTitle,\n DialogDescription,\n};\n"],"mappings":";;;;;;AAOA,IAAM,qBAAqB,QAAM,cAAc,IAAI;AAEnD,IAAM,UAAU,EAAE,QAAQ,MAAM,GAAG,YACjC,oBAAC,mBAAmB,UAApB;CAA6B,OAAO;WAClC,oBAAC,gBAAgB,MAAjB;EAA6B;EAAO,GAAI;CAAQ,CAAA;AACrB,CAAA;AAG/B,IAAM,gBAAgB,gBAAgB;AAEtC,IAAM,eAAe,gBAAgB;AAErC,IAAM,cAAc,gBAAgB;AAEpC,IAAM,gBAAgB,QAAM,YAGzB,EAAE,WAAW,GAAG,SAAS,QAC1B,oBAAC,gBAAgB,SAAjB;CACO;CACL,WAAW,GACT,yLACA,SACF;CACA,aAAU;CACV,GAAI;AACL,CAAA,CACF;AACD,cAAc,cAAc,gBAAgB,QAAQ;AAGpD,IAAM,uBACJ;AAcF,IAAM,gBAAgB,QAAM,YAGzB,EAAE,WAAW,UAAU,SAAS,SAAS,GAAG,SAAS,QAAQ;CAC9D,MAAM,QAAQ,QAAM,WAAW,kBAAkB;CAEjD,MAAM,QACJ,oBAAC,gBAAgB,SAAjB;EACO;EACL,WAAW,GACT,WAAW,YACP,4CACA,iEACJ,sBACA,SACF;EACA,GAAI;EAEH;CACsB,CAAA;CAM3B,MAAM,iBACJ,oBAAC,OAAD;EAAK,WAAU;YAA8D;CAAW,CAAA;CAG1F,OACE,oBAAC,cAAD,EAAA,UACE,oBAAC,YAAD,EAAA,UACG,WAAW,YACV,QAGE,oBAAC,eAAD;EAAe,WAAU;YAAgC;CAA8B,CAAA,IAIvF,oBAAC,OAAD;EACE,WAAU;EACV,aAAU;YAET;CACE,CAAA,IAGP,qBAAA,YAAA,EAAA,UAAA,CACE,oBAAC,eAAD,CAAgB,CAAA,GACf,KACD,EAAA,CAAA,EAEM,CAAA,EACA,CAAA;AAElB,CAAC;AACD,cAAc,cAAc,gBAAgB,QAAQ;AAEpD,IAAM,gBAAgB,EAAE,WAAW,GAAG,YACpC,oBAAC,OAAD;CAAK,WAAW,GAAG,oDAAoD,SAAS;CAAG,GAAI;AAAQ,CAAA;AAEjG,aAAa,cAAc;AAE3B,IAAM,gBAAgB,EAAE,WAAW,GAAG,YACpC,oBAAC,OAAD;CACE,WAAW,GACT,8FACA,SACF;CACA,GAAI;AACL,CAAA;AAEH,aAAa,cAAc;AAE3B,IAAM,cAAc,QAAM,YAGvB,EAAE,WAAW,GAAG,SAAS,QAC1B,oBAAC,gBAAgB,OAAjB;CACO;CACL,WAAW,GAAG,qDAAqD,SAAS;CAC5E,GAAI;AACL,CAAA,CACF;AACD,YAAY,cAAc,gBAAgB,MAAM;AAEhD,IAAM,oBAAoB,QAAM,YAG7B,EAAE,WAAW,GAAG,SAAS,QAC1B,oBAAC,gBAAgB,aAAjB;CACO;CACL,WAAW,GAAG,yBAAyB,SAAS;CAChD,GAAI;AACL,CAAA,CACF;AACD,kBAAkB,cAAc,gBAAgB,YAAY"}
|
|
@@ -11,6 +11,22 @@ var PageMenu = React$1.forwardRef(({ children, responsive = false, value, defaul
|
|
|
11
11
|
const [resizeKey, setResizeKey] = React$1.useState(0);
|
|
12
12
|
const containerRef = React$1.useRef(null);
|
|
13
13
|
const measureRef = React$1.useRef(null);
|
|
14
|
+
const [uncontrolledValue, setUncontrolledValue] = React$1.useState(defaultValue);
|
|
15
|
+
const isControlled = value !== void 0;
|
|
16
|
+
const activeValue = isControlled ? value : uncontrolledValue;
|
|
17
|
+
const handleSelect = React$1.useCallback((nextValue) => {
|
|
18
|
+
if (nextValue === activeValue) return;
|
|
19
|
+
if (!isControlled) setUncontrolledValue(nextValue);
|
|
20
|
+
onValueChange?.(nextValue);
|
|
21
|
+
}, [
|
|
22
|
+
activeValue,
|
|
23
|
+
isControlled,
|
|
24
|
+
onValueChange
|
|
25
|
+
]);
|
|
26
|
+
const contextValue = React$1.useMemo(() => ({
|
|
27
|
+
value: activeValue,
|
|
28
|
+
onSelect: handleSelect
|
|
29
|
+
}), [activeValue, handleSelect]);
|
|
14
30
|
React$1.useLayoutEffect(() => {
|
|
15
31
|
if (!responsive || !containerRef.current || !measureRef.current) {
|
|
16
32
|
setVisibleCount(React$1.Children.count(children));
|
|
@@ -63,9 +79,9 @@ var PageMenu = React$1.forwardRef(({ children, responsive = false, value, defaul
|
|
|
63
79
|
const visibleItems = childrenArray.slice(0, visibleCount);
|
|
64
80
|
const hiddenItems = childrenArray.slice(visibleCount);
|
|
65
81
|
const hasOverflow = hiddenItems.length > 0;
|
|
66
|
-
const selectedHiddenItem = hiddenItems.find((child) => React$1.isValidElement(child) && child.props?.value ===
|
|
82
|
+
const selectedHiddenItem = hiddenItems.find((child) => React$1.isValidElement(child) && child.props?.value === activeValue);
|
|
67
83
|
if (!responsive) return /* @__PURE__ */ jsx(PageMenuContext.Provider, {
|
|
68
|
-
value:
|
|
84
|
+
value: contextValue,
|
|
69
85
|
children: /* @__PURE__ */ jsx("div", {
|
|
70
86
|
ref,
|
|
71
87
|
className: cn("flex items-center gap-2", className),
|
|
@@ -74,7 +90,7 @@ var PageMenu = React$1.forwardRef(({ children, responsive = false, value, defaul
|
|
|
74
90
|
})
|
|
75
91
|
});
|
|
76
92
|
return /* @__PURE__ */ jsxs(PageMenuContext.Provider, {
|
|
77
|
-
value:
|
|
93
|
+
value: contextValue,
|
|
78
94
|
children: [/* @__PURE__ */ jsx("div", {
|
|
79
95
|
ref: measureRef,
|
|
80
96
|
"aria-hidden": "true",
|
|
@@ -107,10 +123,12 @@ var PageMenu = React$1.forwardRef(({ children, responsive = false, value, defaul
|
|
|
107
123
|
children: hiddenItems.map((item, index) => {
|
|
108
124
|
if (!React$1.isValidElement(item) || !item.props?.value) return null;
|
|
109
125
|
return /* @__PURE__ */ jsx(DropdownMenuItem, {
|
|
110
|
-
className: cn(item.props.value ===
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
item.props.
|
|
126
|
+
className: cn(item.props.value === activeValue && "bg-accent text-accent-foreground"),
|
|
127
|
+
disabled: item.props.disabled,
|
|
128
|
+
onClick: (event) => {
|
|
129
|
+
if (item.props.disabled) return;
|
|
130
|
+
item.props.onClick?.(event);
|
|
131
|
+
if (!event.defaultPrevented) handleSelect(item.props.value);
|
|
114
132
|
},
|
|
115
133
|
children: item.props.children
|
|
116
134
|
}, item.props.value || index);
|
|
@@ -120,13 +138,19 @@ var PageMenu = React$1.forwardRef(({ children, responsive = false, value, defaul
|
|
|
120
138
|
});
|
|
121
139
|
});
|
|
122
140
|
PageMenu.displayName = "PageMenu";
|
|
123
|
-
var PageMenuItem = React$1.forwardRef(({ children, value, className, ...props }, ref) => {
|
|
124
|
-
const
|
|
141
|
+
var PageMenuItem = React$1.forwardRef(({ children, value, className, onClick, ...props }, ref) => {
|
|
142
|
+
const pageMenu = React$1.useContext(PageMenuContext);
|
|
143
|
+
const isActive = pageMenu?.value === value;
|
|
125
144
|
return /* @__PURE__ */ jsx(Button, {
|
|
126
145
|
ref,
|
|
146
|
+
"aria-current": isActive ? "page" : void 0,
|
|
127
147
|
className: cn("relative gap-1.5 px-3 text-control font-medium text-text-secondary hover:text-foreground focus-visible:ring-0", "data-[state=active]:bg-muted-foreground/10 data-[state=active]:text-foreground", "dark:hover:bg-tab-hover dark:data-[state=active]:bg-tab-active dark:data-[state=active]:hover:bg-tab-active", className),
|
|
128
148
|
"data-state": isActive ? "active" : void 0,
|
|
129
149
|
variant: "ghost",
|
|
150
|
+
onClick: (event) => {
|
|
151
|
+
onClick?.(event);
|
|
152
|
+
if (!event.defaultPrevented) pageMenu?.onSelect(value);
|
|
153
|
+
},
|
|
130
154
|
...props,
|
|
131
155
|
children
|
|
132
156
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pagemenu.js","names":[],"sources":["../../../src/components/ui/pagemenu.tsx"],"sourcesContent":["import * as React from 'react';\nimport { cn } from '@/lib/utils';\nimport { MoreHorizontal } from 'lucide-react';\nimport { Button, type ButtonProps } from './button';\nimport {\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuTrigger,\n} from './dropdown-menu';\n\nconst PageMenuContext = React.createContext<{ defaultValue?: string } | null>(null);\n\nexport interface PageMenuProps {\n children: React.ReactNode;\n responsive?: boolean;\n value?: string;\n defaultValue?: string;\n onValueChange?: (value: string) => void;\n className?: string;\n}\n\nexport interface PageMenuItemProps extends Omit<ButtonProps, 'children'> {\n value: string;\n children: React.ReactNode;\n}\n\nconst PageMenu = React.forwardRef<HTMLDivElement, PageMenuProps>(\n (\n { children, responsive = false, value, defaultValue, onValueChange, className, ...props },\n ref,\n ) => {\n const [visibleCount, setVisibleCount] = React.useState(React.Children.count(children));\n const [resizeKey, setResizeKey] = React.useState(0);\n const containerRef = React.useRef<HTMLDivElement>(null);\n const measureRef = React.useRef<HTMLDivElement>(null);\n\n React.useLayoutEffect(() => {\n if (!responsive || !containerRef.current || !measureRef.current) {\n setVisibleCount(React.Children.count(children));\n return;\n }\n\n // Use requestAnimationFrame to ensure DOM is fully rendered\n const calculateSizes = () => {\n if (!containerRef.current || !measureRef.current) {\n return;\n }\n\n const container = containerRef.current;\n const measureContainer = measureRef.current;\n const containerWidth = container.clientWidth;\n const dropdownWidth = 60; // Space needed for dropdown button\n const gap = 6; // Gap between items (gap-1.5)\n\n // Get all child elements from the measure container\n const items = Array.from(measureContainer.children) as HTMLElement[];\n\n // First, check if ALL items fit without any dropdown\n let totalWidth = 0;\n for (let i = 0; i < items.length; i++) {\n const itemWidth = items[i].getBoundingClientRect().width;\n const gapWidth = i > 0 ? gap : 0;\n totalWidth += gapWidth + itemWidth;\n }\n\n // If all items fit with some buffer space, show them all\n const safetyBuffer = 8; // Add 8px buffer for safe rendering\n if (totalWidth <= containerWidth - safetyBuffer) {\n setVisibleCount(items.length);\n return;\n }\n\n // Otherwise, calculate how many fit with dropdown space reserved\n let currentWidth = 0;\n let count = 0;\n\n for (let i = 0; i < items.length; i++) {\n const itemWidth = items[i].getBoundingClientRect().width;\n const gapWidth = i > 0 ? gap : 0;\n const newWidth = currentWidth + gapWidth + itemWidth;\n\n // Reserve space for dropdown (since we know not all items fit)\n const totalNeededWidth = newWidth + dropdownWidth;\n\n if (totalNeededWidth <= containerWidth) {\n currentWidth = newWidth;\n count += 1;\n } else {\n break;\n }\n }\n\n setVisibleCount(count);\n };\n\n requestAnimationFrame(calculateSizes);\n }, [responsive, children, resizeKey]);\n\n React.useLayoutEffect(() => {\n if (!responsive || !containerRef.current) {\n return;\n }\n\n const resizeObserver = new ResizeObserver(() => {\n // Trigger re-calculation by updating the resize key\n setResizeKey((prev) => prev + 1);\n });\n\n resizeObserver.observe(containerRef.current);\n return () => resizeObserver.disconnect();\n }, [responsive]);\n\n const childrenArray = React.Children.toArray(children);\n const visibleItems = childrenArray.slice(0, visibleCount);\n const hiddenItems = childrenArray.slice(visibleCount);\n const hasOverflow = hiddenItems.length > 0;\n\n // Find selected hidden item\n const selectedHiddenItem = hiddenItems.find(\n (child) => React.isValidElement(child) && child.props?.value === value,\n ) as React.ReactElement | undefined;\n\n if (!responsive) {\n return (\n <PageMenuContext.Provider value={{ defaultValue }}>\n <div ref={ref} className={cn('flex items-center gap-2', className)} {...props}>\n {children}\n </div>\n </PageMenuContext.Provider>\n );\n }\n\n return (\n <PageMenuContext.Provider value={{ defaultValue }}>\n {/* Hidden container to measure all items */}\n <div\n ref={measureRef}\n aria-hidden=\"true\"\n className=\"pointer-events-none absolute flex items-center gap-2 opacity-0\"\n style={{ top: -9999, left: -9999 }}\n >\n {children}\n </div>\n\n {/* Visible container */}\n <div ref={containerRef} className=\"flex w-full min-w-0 flex-1 items-center gap-2\">\n <div ref={ref} className={cn('flex min-w-0 items-center gap-2', className)} {...props}>\n {visibleItems}\n </div>\n\n {hasOverflow && (\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n className={cn(\n 'h-[30px] flex-shrink-0 px-3 py-2',\n selectedHiddenItem && 'bg-accent text-accent-foreground',\n )}\n variant=\"ghost\"\n >\n {selectedHiddenItem ? (\n <span className=\"max-w-[100px] truncate\">\n {selectedHiddenItem.props.children}\n </span>\n ) : (\n <MoreHorizontal className=\"size-6\" />\n )}\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align=\"end\">\n {hiddenItems.map((item, index) => {\n if (!React.isValidElement(item) || !item.props?.value) {\n return null;\n }\n\n return (\n <DropdownMenuItem\n key={item.props.value || index}\n className={cn(\n item.props.value === value && 'bg-accent text-accent-foreground',\n )}\n onClick={() => {\n onValueChange?.(item.props.value);\n item.props.onClick?.();\n }}\n >\n {item.props.children}\n </DropdownMenuItem>\n );\n })}\n </DropdownMenuContent>\n </DropdownMenu>\n )}\n </div>\n </PageMenuContext.Provider>\n );\n },\n);\n\nPageMenu.displayName = 'PageMenu';\n\nconst PageMenuItem = React.forwardRef<HTMLButtonElement, PageMenuItemProps>(\n ({ children, value, className, ...props }, ref) => {\n const pageMenuProps = React.useContext(PageMenuContext);\n const isActive = pageMenuProps?.defaultValue === value;\n\n return (\n <Button\n ref={ref}\n className={cn(\n 'relative gap-1.5 px-3 text-control font-medium text-text-secondary hover:text-foreground focus-visible:ring-0',\n 'data-[state=active]:bg-muted-foreground/10 data-[state=active]:text-foreground',\n 'dark:hover:bg-tab-hover dark:data-[state=active]:bg-tab-active dark:data-[state=active]:hover:bg-tab-active',\n className,\n )}\n data-state={isActive ? 'active' : undefined}\n variant=\"ghost\"\n {...props}\n >\n {children}\n </Button>\n );\n },\n);\n\nPageMenuItem.displayName = 'PageMenuItem';\n\nexport { PageMenu, PageMenuItem };\n"],"mappings":";;;;;;;AAWA,IAAM,kBAAkB,QAAM,cAAgD,IAAI;AAgBlF,IAAM,WAAW,QAAM,YAEnB,EAAE,UAAU,aAAa,OAAO,OAAO,cAAc,eAAe,WAAW,GAAG,SAClF,QACG;CACH,MA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AAY,KAAK,MAAM,UAAU;KAChC,IAAI,CAAC,QAAM,eAAe,IAAI,KAAK,CAAC,KAAK,OAAO,OAC9C,OAAO;KAGT,OACE,oBAAC,kBAAD;MAEE,WAAW,GACT,KAAK,MAAM,UAAU,SAAS,kCAChC;MACA,eAAe;OACb,gBAAgB,KAAK,MAAM,KAAK;OAChC,KAAK,MAAM,UAAU;MACvB;gBAEC,KAAK,MAAM;KACI,GAVX,KAAK,MAAM,SAAS,KAUT;IAEtB,CAAC;GACkB,CAAA,CACT,EAAA,CAAA,CAEb;IACmB;;AAE9B,CACF;AAEA,SAAS,cAAc;AAEvB,IAAM,eAAe,QAAM,YACxB,EAAE,UAAU,OAAO,WAAW,GAAG,SAAS,QAAQ;CAEjD,MAAM,WADgB,QAAM,WAAW,eACtB,CAAA,EAAe,iBAAiB;CAEjD,OACE,oBAAC,QAAD;EACO;EACL,WAAW,GACT,iHACA,kFACA,+GACA,SACF;EACA,cAAY,WAAW,WAAW,KAAA;EAClC,SAAQ;EACR,GAAI;EAEH;CACK,CAAA;AAEZ,CACF;AAEA,aAAa,cAAc"}
|
|
1
|
+
{"version":3,"file":"pagemenu.js","names":[],"sources":["../../../src/components/ui/pagemenu.tsx"],"sourcesContent":["import * as React from 'react';\nimport { cn } from '@/lib/utils';\nimport { MoreHorizontal } from 'lucide-react';\nimport { Button, type ButtonProps } from './button';\nimport {\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuTrigger,\n} from './dropdown-menu';\n\ninterface PageMenuContextValue {\n value?: string;\n onSelect: (value: string) => void;\n}\n\nconst PageMenuContext = React.createContext<PageMenuContextValue | null>(null);\n\nexport interface PageMenuProps {\n children: React.ReactNode;\n responsive?: boolean;\n /** The active item's value. Pass with `onValueChange` to control the menu, e.g. from the current route. */\n value?: string;\n /** The item active on first render when the menu manages its own selection. */\n defaultValue?: string;\n /** Called with the item's value when the user picks a different item. */\n onValueChange?: (value: string) => void;\n className?: string;\n}\n\nexport interface PageMenuItemProps extends Omit<ButtonProps, 'children'> {\n value: string;\n children: React.ReactNode;\n}\n\nconst PageMenu = React.forwardRef<HTMLDivElement, PageMenuProps>(\n (\n { children, responsive = false, value, defaultValue, onValueChange, className, ...props },\n ref,\n ) => {\n const [visibleCount, setVisibleCount] = React.useState(React.Children.count(children));\n const [resizeKey, setResizeKey] = React.useState(0);\n const containerRef = React.useRef<HTMLDivElement>(null);\n const measureRef = React.useRef<HTMLDivElement>(null);\n\n // Controlled when `value` is passed, otherwise tracks its own selection\n // starting from `defaultValue` (same contract as Radix Tabs).\n const [uncontrolledValue, setUncontrolledValue] = React.useState(defaultValue);\n const isControlled = value !== undefined;\n const activeValue = isControlled ? value : uncontrolledValue;\n\n const handleSelect = React.useCallback(\n (nextValue: string) => {\n if (nextValue === activeValue) {\n return;\n }\n if (!isControlled) {\n setUncontrolledValue(nextValue);\n }\n onValueChange?.(nextValue);\n },\n [activeValue, isControlled, onValueChange],\n );\n\n const contextValue = React.useMemo(\n () => ({ value: activeValue, onSelect: handleSelect }),\n [activeValue, handleSelect],\n );\n\n React.useLayoutEffect(() => {\n if (!responsive || !containerRef.current || !measureRef.current) {\n setVisibleCount(React.Children.count(children));\n return;\n }\n\n // Use requestAnimationFrame to ensure DOM is fully rendered\n const calculateSizes = () => {\n if (!containerRef.current || !measureRef.current) {\n return;\n }\n\n const container = containerRef.current;\n const measureContainer = measureRef.current;\n const containerWidth = container.clientWidth;\n const dropdownWidth = 60; // Space needed for dropdown button\n const gap = 6; // Gap between items (gap-1.5)\n\n // Get all child elements from the measure container\n const items = Array.from(measureContainer.children) as HTMLElement[];\n\n // First, check if ALL items fit without any dropdown\n let totalWidth = 0;\n for (let i = 0; i < items.length; i++) {\n const itemWidth = items[i].getBoundingClientRect().width;\n const gapWidth = i > 0 ? gap : 0;\n totalWidth += gapWidth + itemWidth;\n }\n\n // If all items fit with some buffer space, show them all\n const safetyBuffer = 8; // Add 8px buffer for safe rendering\n if (totalWidth <= containerWidth - safetyBuffer) {\n setVisibleCount(items.length);\n return;\n }\n\n // Otherwise, calculate how many fit with dropdown space reserved\n let currentWidth = 0;\n let count = 0;\n\n for (let i = 0; i < items.length; i++) {\n const itemWidth = items[i].getBoundingClientRect().width;\n const gapWidth = i > 0 ? gap : 0;\n const newWidth = currentWidth + gapWidth + itemWidth;\n\n // Reserve space for dropdown (since we know not all items fit)\n const totalNeededWidth = newWidth + dropdownWidth;\n\n if (totalNeededWidth <= containerWidth) {\n currentWidth = newWidth;\n count += 1;\n } else {\n break;\n }\n }\n\n setVisibleCount(count);\n };\n\n requestAnimationFrame(calculateSizes);\n }, [responsive, children, resizeKey]);\n\n React.useLayoutEffect(() => {\n if (!responsive || !containerRef.current) {\n return;\n }\n\n const resizeObserver = new ResizeObserver(() => {\n // Trigger re-calculation by updating the resize key\n setResizeKey((prev) => prev + 1);\n });\n\n resizeObserver.observe(containerRef.current);\n return () => resizeObserver.disconnect();\n }, [responsive]);\n\n const childrenArray = React.Children.toArray(children);\n const visibleItems = childrenArray.slice(0, visibleCount);\n const hiddenItems = childrenArray.slice(visibleCount);\n const hasOverflow = hiddenItems.length > 0;\n\n // Find selected hidden item\n const selectedHiddenItem = hiddenItems.find(\n (child) => React.isValidElement(child) && child.props?.value === activeValue,\n ) as React.ReactElement | undefined;\n\n if (!responsive) {\n return (\n <PageMenuContext.Provider value={contextValue}>\n <div ref={ref} className={cn('flex items-center gap-2', className)} {...props}>\n {children}\n </div>\n </PageMenuContext.Provider>\n );\n }\n\n return (\n <PageMenuContext.Provider value={contextValue}>\n {/* Hidden container to measure all items */}\n <div\n ref={measureRef}\n aria-hidden=\"true\"\n className=\"pointer-events-none absolute flex items-center gap-2 opacity-0\"\n style={{ top: -9999, left: -9999 }}\n >\n {children}\n </div>\n\n {/* Visible container */}\n <div ref={containerRef} className=\"flex w-full min-w-0 flex-1 items-center gap-2\">\n <div ref={ref} className={cn('flex min-w-0 items-center gap-2', className)} {...props}>\n {visibleItems}\n </div>\n\n {hasOverflow && (\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n className={cn(\n 'h-[30px] flex-shrink-0 px-3 py-2',\n selectedHiddenItem && 'bg-accent text-accent-foreground',\n )}\n variant=\"ghost\"\n >\n {selectedHiddenItem ? (\n <span className=\"max-w-[100px] truncate\">\n {selectedHiddenItem.props.children}\n </span>\n ) : (\n <MoreHorizontal className=\"size-6\" />\n )}\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align=\"end\">\n {hiddenItems.map((item, index) => {\n if (!React.isValidElement(item) || !item.props?.value) {\n return null;\n }\n\n return (\n <DropdownMenuItem\n key={item.props.value || index}\n className={cn(\n item.props.value === activeValue && 'bg-accent text-accent-foreground',\n )}\n disabled={item.props.disabled}\n onClick={(event) => {\n // Radix still fires onClick on disabled items and relies on CSS to block pointer clicks\n if (item.props.disabled) {\n return;\n }\n item.props.onClick?.(event);\n if (!event.defaultPrevented) {\n handleSelect(item.props.value);\n }\n }}\n >\n {item.props.children}\n </DropdownMenuItem>\n );\n })}\n </DropdownMenuContent>\n </DropdownMenu>\n )}\n </div>\n </PageMenuContext.Provider>\n );\n },\n);\n\nPageMenu.displayName = 'PageMenu';\n\nconst PageMenuItem = React.forwardRef<HTMLButtonElement, PageMenuItemProps>(\n ({ children, value, className, onClick, ...props }, ref) => {\n const pageMenu = React.useContext(PageMenuContext);\n const isActive = pageMenu?.value === value;\n\n return (\n <Button\n ref={ref}\n aria-current={isActive ? 'page' : undefined}\n className={cn(\n 'relative gap-1.5 px-3 text-control font-medium text-text-secondary hover:text-foreground focus-visible:ring-0',\n 'data-[state=active]:bg-muted-foreground/10 data-[state=active]:text-foreground',\n 'dark:hover:bg-tab-hover dark:data-[state=active]:bg-tab-active dark:data-[state=active]:hover:bg-tab-active',\n className,\n )}\n data-state={isActive ? 'active' : undefined}\n variant=\"ghost\"\n onClick={(event) => {\n onClick?.(event);\n if (!event.defaultPrevented) {\n pageMenu?.onSelect(value);\n }\n }}\n {...props}\n >\n {children}\n </Button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O;EACL,gBAAc,WAAW,SAAS,KAAA;EAClC,WAAW,GACT,iHACA,kFACA,+GACA,SACF;EACA,cAAY,WAAW,WAAW,KAAA;EAClC,SAAQ;EACR,UAAU,UAAU;GAClB,UAAU,KAAK;GACf,IAAI,CAAC,MAAM,kBACT,UAAU,SAAS,KAAK;EAE5B;EACA,GAAI;EAEH;CACK,CAAA;AAEZ,CACF;AAEA,aAAa,cAAc"}
|
|
@@ -5,8 +5,8 @@ import { inputSurface } from "./input-surface.js";
|
|
|
5
5
|
var tokenFieldClasses = {
|
|
6
6
|
field: cn(inputSurface("within"), "relative flex min-h-(--control-height) w-full cursor-text flex-wrap items-center gap-1 p-0.75 text-control"),
|
|
7
7
|
input: "min-w-20 flex-1 bg-transparent px-2 text-control outline-hidden placeholder:text-muted-foreground",
|
|
8
|
-
chip: "h-6 max-w-full cursor-pointer gap-1 rounded-
|
|
9
|
-
chevron: "pointer-events-none absolute top-[calc((var(--control-height)-var(--spacing)*4)/2)] right-
|
|
8
|
+
chip: "h-auto min-h-6 max-w-full cursor-pointer gap-1 rounded-xl border-transparent px-2 py-0.75 pr-1.5 text-left text-sm leading-4 whitespace-normal",
|
|
9
|
+
chevron: "pointer-events-none absolute top-[calc((var(--control-height)-var(--spacing)*4)/2-1px)] right-1.5 size-4 text-muted-foreground"
|
|
10
10
|
};
|
|
11
11
|
//#endregion
|
|
12
12
|
export { tokenFieldClasses };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"token-field.js","names":[],"sources":["../../../src/components/ui/token-field.ts"],"sourcesContent":["import { inputSurface } from '@/components/ui/input-surface';\nimport { cn } from '@/lib/utils';\n\n/** Shared chip density for token inputs such as labels, tags and authors. */\nexport const tokenFieldClasses = {\n field: cn(\n inputSurface('within'),\n 'relative flex min-h-(--control-height) w-full cursor-text flex-wrap items-center gap-1 p-0.75 text-control',\n ),\n input:\n 'min-w-20 flex-1 bg-transparent px-2 text-control outline-hidden placeholder:text-muted-foreground',\n chip: 'h-6 max-w-full cursor-pointer gap-1 rounded-
|
|
1
|
+
{"version":3,"file":"token-field.js","names":[],"sources":["../../../src/components/ui/token-field.ts"],"sourcesContent":["import { inputSurface } from '@/components/ui/input-surface';\nimport { cn } from '@/lib/utils';\n\n/** Shared chip density for token inputs such as labels, tags and authors. */\nexport const tokenFieldClasses = {\n field: cn(\n inputSurface('within'),\n 'relative flex min-h-(--control-height) w-full cursor-text flex-wrap items-center gap-1 p-0.75 text-control',\n ),\n input:\n 'min-w-20 flex-1 bg-transparent px-2 text-control outline-hidden placeholder:text-muted-foreground',\n // 24px on one line; long names wrap.\n chip: 'h-auto min-h-6 max-w-full cursor-pointer gap-1 rounded-xl border-transparent px-2 py-0.75 pr-1.5 text-left text-sm leading-4 whitespace-normal',\n // Matches Select's chevron; offsets start inside the 1px border.\n chevron:\n 'pointer-events-none absolute top-[calc((var(--control-height)-var(--spacing)*4)/2-1px)] right-1.5 size-4 text-muted-foreground',\n} as const;\n"],"mappings":";;;;AAIA,IAAa,oBAAoB;CAC/B,OAAO,GACL,aAAa,QAAQ,GACrB,4GACF;CACA,OACE;CAEF,MAAM;CAEN,SACE;AACJ"}
|
package/es/components.js
CHANGED
|
@@ -8,7 +8,7 @@ import { selectTriggerVariants } from "./components/ui/select-variants.js";
|
|
|
8
8
|
import { inputSurface, inputSurfaceClasses } from "./components/ui/input-surface.js";
|
|
9
9
|
import { Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectScrollDownButton, SelectScrollUpButton, SelectSeparator, SelectTrigger, SelectValue } from "./components/ui/select.js";
|
|
10
10
|
import { Kbd, KbdGroup } from "./components/ui/kbd.js";
|
|
11
|
-
import { AlignedAxisTick, ChartContainer, ChartLegend, ChartLegendContent, ChartStyle, ChartTooltip, ChartTooltipContent
|
|
11
|
+
import { AlignedAxisTick, ChartContainer, ChartLegend, ChartLegendContent, ChartStyle, ChartTooltip, ChartTooltipContent } from "./components/ui/chart.js";
|
|
12
12
|
import { Tabs, TabsContent, TabsDropdownTrigger, TabsList, TabsTrigger, TabsTriggerCount } from "./components/ui/tabs.js";
|
|
13
13
|
import { Calendar, CalendarDayButton } from "./components/ui/calendar.js";
|
|
14
14
|
import { Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogOverlay, DialogPortal, DialogTitle, DialogTrigger } from "./components/ui/dialog.js";
|
|
@@ -76,4 +76,4 @@ import { a as TwitterLogo, i as GoogleLogo, n as GhostLogo, o as XLogo, r as Gho
|
|
|
76
76
|
import { TimePicker } from "./components/ui/time-picker.js";
|
|
77
77
|
import { tokenFieldClasses } from "./components/ui/token-field.js";
|
|
78
78
|
import { defaultFilter as commandDefaultFilter } from "cmdk";
|
|
79
|
-
export { Accordion, AccordionContent, AccordionItem, AccordionTrigger, ActionList, ActionListItem, ActionListItemActions, ActionListItemContent, AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogOverlay, AlertDialogPortal, AlertDialogTitle, AlertDialogTrigger, AlignedAxisTick, AnimatedNumber, Avatar, AvatarFallback, AvatarImage, Badge, Banner, BarChartLoadingIndicator, Breadcrumb, BreadcrumbEllipsis, BreadcrumbItem, BreadcrumbLink, BreadcrumbList, BreadcrumbPage, BreadcrumbSeparator, Button, Calendar, CalendarDayButton, Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle, ChartContainer, ChartLegend, ChartLegendContent, ChartStyle, ChartTooltip, ChartTooltipContent, Checkbox, CodeEditor, Combobox, ComboboxContent, ComboboxTrigger, ComboboxValue, Command, CommandCheck, CommandDialog, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandSeparator, CommandShortcut, ContextMenu, ContextMenuCheckboxItem, ContextMenuContent, ContextMenuGroup, ContextMenuItem, ContextMenuLabel, ContextMenuPortal, ContextMenuRadioGroup, ContextMenuRadioItem, ContextMenuSeparator, ContextMenuShortcut, ContextMenuSub, ContextMenuSubContent, ContextMenuSubTrigger, ContextMenuTrigger, CopyField, CopyFieldActions, CopyFieldContent, CopyFieldCopyButton, CopyFieldLabel, CopyFieldValue, DataList, DataListBar, DataListBody, DataListHead, DataListHeader, DataListItemContent, DataListItemValue, DataListItemValueAbs, DataListItemValuePerc, DataListRow,
|
|
79
|
+
export { Accordion, AccordionContent, AccordionItem, AccordionTrigger, ActionList, ActionListItem, ActionListItemActions, ActionListItemContent, AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogOverlay, AlertDialogPortal, AlertDialogTitle, AlertDialogTrigger, AlignedAxisTick, AnimatedNumber, Avatar, AvatarFallback, AvatarImage, Badge, Banner, BarChartLoadingIndicator, Breadcrumb, BreadcrumbEllipsis, BreadcrumbItem, BreadcrumbLink, BreadcrumbList, BreadcrumbPage, BreadcrumbSeparator, Button, Calendar, CalendarDayButton, Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle, ChartContainer, ChartLegend, ChartLegendContent, ChartStyle, ChartTooltip, ChartTooltipContent, Checkbox, CodeEditor, Combobox, ComboboxContent, ComboboxTrigger, ComboboxValue, Command, CommandCheck, CommandDialog, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandSeparator, CommandShortcut, ContextMenu, ContextMenuCheckboxItem, ContextMenuContent, ContextMenuGroup, ContextMenuItem, ContextMenuLabel, ContextMenuPortal, ContextMenuRadioGroup, ContextMenuRadioItem, ContextMenuSeparator, ContextMenuShortcut, ContextMenuSub, ContextMenuSubContent, ContextMenuSubTrigger, ContextMenuTrigger, CopyField, CopyFieldActions, CopyFieldContent, CopyFieldCopyButton, CopyFieldLabel, CopyFieldValue, DataList, DataListBar, DataListBody, DataListHead, DataListHeader, DataListItemContent, DataListItemValue, DataListItemValueAbs, DataListItemValuePerc, DataListRow, Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogOverlay, DialogPortal, DialogTitle, DialogTrigger, DragIndicator, DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuPortal, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuSeparator, DropdownMenuShortcut, DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuTrigger, Dropzone, EmptyBadge, EmptyCard, EmptyIndicator, FLOATING_SIDEBAR_BUMP, FLOATING_SIDEBAR_CLOSED_FOOTPRINT, FLOATING_SIDEBAR_CLOSED_SIZE, FLOATING_SIDEBAR_DURATION, FLOATING_SIDEBAR_EASE, FLOATING_SIDEBAR_EASE_DURATION, FLOATING_SIDEBAR_INSET, FLOATING_SIDEBAR_OPEN_WIDTH, FLOATING_SIDEBAR_SPRING, FacebookLogo, Field, FieldContent, FieldDescription, FieldError, FieldGroup, FieldLabel, FieldLegend, FieldSeparator, FieldSet, FieldTitle, Flag, FloatingSidebar, Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage, GhostLogo, GhostOrb, GoogleLogo, HoverCard, HoverCardContent, HoverCardTrigger, IconComponents as Icon, Indicator, Input, InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput, InputGroupText, InputGroupTextarea, Kbd, KbdGroup, Label, Link, LoadingIndicator, MultiSelectCombobox, Navbar, NavbarActions, NavbarNavigation, NoValueLabel, NoValueLabelIcon, PageMenu, PageMenuItem, Popover, PopoverAnchor, PopoverClose, PopoverContent, PopoverTrigger, PreviewChrome, RadioGroup, RadioGroupItem, Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectScrollDownButton, SelectScrollUpButton, SelectSeparator, SelectTrigger, SelectValue, Separator, Sheet, SheetClose, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetOverlay, SheetPortal, SheetTitle, SheetTrigger, Sidebar, SidebarContent, SidebarFooter, SidebarGroup, SidebarGroupAction, SidebarGroupContent, SidebarGroupLabel, SidebarHeader, SidebarInput, SidebarInset, SidebarMenu, SidebarMenuAction, SidebarMenuBadge, SidebarMenuButton, SidebarMenuItem, SidebarMenuSkeleton, SidebarMenuSub, SidebarMenuSubButton, SidebarMenuSubItem, SidebarProvider, SidebarRail, SidebarSeparator, SidebarTrigger, SimplePagination, SimplePaginationNavigation, SimplePaginationNextButton, SimplePaginationPages, SimplePaginationPreviousButton, Skeleton, SkeletonTable, SortableList, StickyFooter, Switch, Table, TableBody, TableCaption, TableCell, TableFooter, TableHead, TableHeadButton, TableHeader, TableRow, Tabs, TabsContent, TabsDropdownTrigger, TabsList, TabsTrigger, TabsTriggerCount, Textarea, TimePicker, Toaster, ToggleGroup, ToggleGroupItem, Tooltip, TooltipContent, TooltipProvider, TooltipTrigger, TwitterLogo, XLogo, badgeVariants, bannerVariants, buttonVariants, cardVariants, commandDefaultFilter, dropzoneVariants, getFloatingSidebarGapWidth, getFloatingSidebarTiming, imageOverlayButton, imageOverlayButtonClasses, indicatorVariants, inputGroupVariants, inputSurface, inputSurfaceClasses, previewChromeVariants, radioGroupItemVariants, selectTriggerVariants, tabsVariants, tokenFieldClasses, useFormField, useSidebar };
|
package/es/index.js
CHANGED
|
@@ -21,7 +21,7 @@ import { Kbd, KbdGroup } from "./components/ui/kbd.js";
|
|
|
21
21
|
import { PageHeader, PageHeaderActionGroup, PageHeaderActionGroupMobileMenu, PageHeaderActionGroupMobileMenuContent, PageHeaderActionGroupMobileMenuTrigger, PageHeaderActionGroupPrimary, PageHeaderActions, PageHeaderBreadcrumb, PageHeaderCount, PageHeaderDescription, PageHeaderLeft, PageHeaderMeta, PageHeaderTitle } from "./components/patterns/page-header.js";
|
|
22
22
|
import { ViewBar, ViewBarActions, ViewBarNav } from "./components/patterns/view-bar.js";
|
|
23
23
|
import { FilterBar } from "./components/patterns/filter-bar.js";
|
|
24
|
-
import { AlignedAxisTick, ChartContainer, ChartLegend, ChartLegendContent, ChartStyle, ChartTooltip, ChartTooltipContent
|
|
24
|
+
import { AlignedAxisTick, ChartContainer, ChartLegend, ChartLegendContent, ChartStyle, ChartTooltip, ChartTooltipContent } from "./components/ui/chart.js";
|
|
25
25
|
import { GhAreaChart, GhCustomTooltipContent } from "./components/patterns/gh-chart.js";
|
|
26
26
|
import { KpiCardHeader, KpiCardHeaderLabel, KpiCardHeaderValue } from "./components/patterns/kpi-card.js";
|
|
27
27
|
import { Tabs, TabsContent, TabsDropdownTrigger, TabsList, TabsTrigger, TabsTriggerCount } from "./components/ui/tabs.js";
|
|
@@ -110,4 +110,4 @@ import { a as TwitterLogo, i as GoogleLogo, n as GhostLogo, o as XLogo, r as Gho
|
|
|
110
110
|
import { TimePicker } from "./components/ui/time-picker.js";
|
|
111
111
|
import { tokenFieldClasses } from "./components/ui/token-field.js";
|
|
112
112
|
import { commandDefaultFilter } from "./components.js";
|
|
113
|
-
export { Accordion, AccordionContent, AccordionItem, AccordionTrigger, ActionList, ActionListItem, ActionListItemActions, ActionListItemContent, AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogOverlay, AlertDialogPortal, AlertDialogTitle, AlertDialogTrigger, AlignedAxisTick, AnimatedNumber, Avatar, AvatarFallback, AvatarImage, Badge, Banner, BarChartLoadingIndicator, Box, Breadcrumb, BreadcrumbEllipsis, BreadcrumbItem, BreadcrumbLink, BreadcrumbList, BreadcrumbPage, BreadcrumbSeparator, Button, Calendar, CalendarDayButton, Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle, ChartContainer, ChartLegend, ChartLegendContent, ChartStyle, ChartTooltip, ChartTooltipContent, Checkbox, CodeEditor, ColorPicker, ColorPickerTrigger, ColorSwatch, ColorSwatchRow, Combobox, ComboboxContent, ComboboxTrigger, ComboboxValue, Command, CommandCheck, CommandDialog, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandSeparator, CommandShortcut, Container, ContextMenu, ContextMenuCheckboxItem, ContextMenuContent, ContextMenuGroup, ContextMenuItem, ContextMenuLabel, ContextMenuPortal, ContextMenuRadioGroup, ContextMenuRadioItem, ContextMenuSeparator, ContextMenuShortcut, ContextMenuSub, ContextMenuSubContent, ContextMenuSubTrigger, ContextMenuTrigger, CopyField, CopyFieldActions, CopyFieldContent, CopyFieldCopyButton, CopyFieldLabel, CopyFieldValue, DEFAULT_I18N, DEFAULT_OPERATORS, DataList, DataListBar, DataListBody, DataListHead, DataListHeader, DataListItemContent, DataListItemValue, DataListItemValueAbs, DataListItemValuePerc, DataListRow,
|
|
113
|
+
export { Accordion, AccordionContent, AccordionItem, AccordionTrigger, ActionList, ActionListItem, ActionListItemActions, ActionListItemContent, AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogOverlay, AlertDialogPortal, AlertDialogTitle, AlertDialogTrigger, AlignedAxisTick, AnimatedNumber, Avatar, AvatarFallback, AvatarImage, Badge, Banner, BarChartLoadingIndicator, Box, Breadcrumb, BreadcrumbEllipsis, BreadcrumbItem, BreadcrumbLink, BreadcrumbList, BreadcrumbPage, BreadcrumbSeparator, Button, Calendar, CalendarDayButton, Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle, ChartContainer, ChartLegend, ChartLegendContent, ChartStyle, ChartTooltip, ChartTooltipContent, Checkbox, CodeEditor, ColorPicker, ColorPickerTrigger, ColorSwatch, ColorSwatchRow, Combobox, ComboboxContent, ComboboxTrigger, ComboboxValue, Command, CommandCheck, CommandDialog, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandSeparator, CommandShortcut, Container, ContextMenu, ContextMenuCheckboxItem, ContextMenuContent, ContextMenuGroup, ContextMenuItem, ContextMenuLabel, ContextMenuPortal, ContextMenuRadioGroup, ContextMenuRadioItem, ContextMenuSeparator, ContextMenuShortcut, ContextMenuSub, ContextMenuSubContent, ContextMenuSubTrigger, ContextMenuTrigger, CopyField, CopyFieldActions, CopyFieldContent, CopyFieldCopyButton, CopyFieldLabel, CopyFieldValue, DEFAULT_I18N, DEFAULT_OPERATORS, DataList, DataListBar, DataListBody, DataListHead, DataListHeader, DataListItemContent, DataListItemValue, DataListItemValueAbs, DataListItemValuePerc, DataListRow, DetailPage, Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogOverlay, DialogPortal, DialogTitle, DialogTrigger, DirtyConfirmDialog, DragIndicator, DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuPortal, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuSeparator, DropdownMenuShortcut, DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuTrigger, Dropzone, EmptyBadge, EmptyCard, EmptyIndicator, ErrorPage, FLOATING_SIDEBAR_BUMP, FLOATING_SIDEBAR_CLOSED_FOOTPRINT, FLOATING_SIDEBAR_CLOSED_SIZE, FLOATING_SIDEBAR_DURATION, FLOATING_SIDEBAR_EASE, FLOATING_SIDEBAR_EASE_DURATION, FLOATING_SIDEBAR_INSET, FLOATING_SIDEBAR_OPEN_WIDTH, FLOATING_SIDEBAR_SPRING, FacebookLogo, Field, FieldContent, FieldDescription, FieldError, FieldGroup, FieldLabel, FieldLegend, FieldSeparator, FieldSet, FieldTitle, FilterBar, FilterDatePicker, FilterSegmentInput, FilterSegmentMultiSelect, FilterSegmentSelect, Filters, FiltersContent, Flag, FloatingSidebar, Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage, GhAreaChart, GhCustomTooltipContent, GhostLogo, GhostOrb, GoogleLogo, Grid, H1, H2, H3, H4, HTable, HoverCard, HoverCardContent, HoverCardTrigger, IconComponents as Icon, ImageUpload, ImageUploadAction, ImageUploadActions, ImageUploadDropzone, ImageUploadImage, ImageUploadPreview, Indicator, Inline, Input, InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput, InputGroupText, InputGroupTextarea, Kbd, KbdGroup, KpiCardHeader, KpiCardHeaderLabel, KpiCardHeaderValue, KpiDropdownButton, KpiTabTrigger, KpiTabValue, Label, Link, ListPage, ListPageBody, ListPageHeader, LoadingIndicator, ModalPage, ModalPageTitle, MultiSelectCombobox, Navbar, NavbarActions, NavbarNavigation, NoValueLabel, NoValueLabelIcon, PageChromeProvider, PageHeader, PageHeaderActionGroup, PageHeaderActionGroupMobileMenu, PageHeaderActionGroupMobileMenuContent, PageHeaderActionGroupMobileMenuTrigger, PageHeaderActionGroupPrimary, PageHeaderActions, PageHeaderBreadcrumb, PageHeaderCount, PageHeaderDescription, PageHeaderLeft, PageHeaderMeta, PageHeaderTitle, PageMenu, PageMenuItem, Popover, PopoverAnchor, PopoverClose, PopoverContent, PopoverTrigger, PreviewChrome, RadioGroup, RadioGroupItem, SHADE_TOKEN_NAMES, Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectScrollDownButton, SelectScrollUpButton, SelectSeparator, SelectTrigger, SelectValue, Separator, SettingGroup, SettingGroupActions, SettingGroupContent, SettingGroupDescription, SettingGroupDetails, SettingGroupHeader, SettingGroupTitle, SettingGroupValue, SettingGroupValueContent, SettingGroupValueTitle, SettingsModal, ShareModal, Sheet, SheetClose, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetOverlay, SheetPortal, SheetTitle, SheetTrigger, Sidebar, SidebarContent, SidebarFooter, SidebarGroup, SidebarGroupAction, SidebarGroupContent, SidebarGroupLabel, SidebarHeader, SidebarInput, SidebarInset, SidebarMenu, SidebarMenuAction, SidebarMenuBadge, SidebarMenuButton, SidebarMenuItem, SidebarMenuSkeleton, SidebarMenuSub, SidebarMenuSubButton, SidebarMenuSubItem, SidebarProvider, SidebarRail, SidebarSeparator, SidebarTrigger, SimplePagination, SimplePaginationNavigation, SimplePaginationNextButton, SimplePaginationPages, SimplePaginationPreviousButton, Skeleton, SkeletonTable, SortableList, Stack, StickyFooter, Switch, Table, TableBody, TableCaption, TableCell, TableFooter, TableHead, TableHeadButton, TableHeader, TableRow, Tabs, TabsContent, TabsDropdownTrigger, TabsList, TabsTrigger, TabsTriggerCount, Text, Textarea, TimePicker, Toaster, ToggleGroup, ToggleGroupItem, Tooltip, TooltipContent, TooltipProvider, TooltipTrigger, TwitterLogo, ViewBar, ViewBarActions, ViewBarNav, XLogo, badgeVariants, bannerVariants, buttonVariants, cardVariants, commandDefaultFilter, createFilter, createFilterGroup, dropzoneVariants, getFloatingSidebarGapWidth, getFloatingSidebarTiming, imageOverlayButton, imageOverlayButtonClasses, imageUploadPreviewVariants, indicatorVariants, inputGroupVariants, inputSurface, inputSurfaceClasses, previewChromeVariants, radioGroupItemVariants, selectTriggerVariants, settingGroupVariants, settingsModalVariants, shadeToken, tabsVariants, tokenFieldClasses, useDirtyConfirmation, useFormField, usePageChrome, useSidebar };
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
//#region src/lib/date-utils.ts
|
|
2
|
+
var MONTHS = [
|
|
3
|
+
"Jan",
|
|
4
|
+
"Feb",
|
|
5
|
+
"Mar",
|
|
6
|
+
"Apr",
|
|
7
|
+
"May",
|
|
8
|
+
"Jun",
|
|
9
|
+
"Jul",
|
|
10
|
+
"Aug",
|
|
11
|
+
"Sep",
|
|
12
|
+
"Oct",
|
|
13
|
+
"Nov",
|
|
14
|
+
"Dec"
|
|
15
|
+
];
|
|
16
|
+
var DAY_MS = 1440 * 60 * 1e3;
|
|
17
|
+
var INVALID_DATE = "Invalid date";
|
|
18
|
+
var zonedFormatters = /* @__PURE__ */ new Map();
|
|
19
|
+
var getZonedFormatter = (timeZone) => {
|
|
20
|
+
let formatter = zonedFormatters.get(timeZone);
|
|
21
|
+
if (!formatter) {
|
|
22
|
+
try {
|
|
23
|
+
formatter = new Intl.DateTimeFormat("en-US", {
|
|
24
|
+
timeZone,
|
|
25
|
+
hourCycle: "h23",
|
|
26
|
+
year: "numeric",
|
|
27
|
+
month: "numeric",
|
|
28
|
+
day: "numeric",
|
|
29
|
+
hour: "numeric",
|
|
30
|
+
minute: "numeric",
|
|
31
|
+
second: "numeric"
|
|
32
|
+
});
|
|
33
|
+
} catch (error) {
|
|
34
|
+
if (!(error instanceof RangeError)) throw error;
|
|
35
|
+
formatter = getZonedFormatter("UTC");
|
|
36
|
+
}
|
|
37
|
+
zonedFormatters.set(timeZone, formatter);
|
|
38
|
+
}
|
|
39
|
+
return formatter;
|
|
40
|
+
};
|
|
41
|
+
var getDateTimeParts = (date, timeZone) => {
|
|
42
|
+
if (!timeZone) return {
|
|
43
|
+
year: date.getFullYear(),
|
|
44
|
+
month: date.getMonth(),
|
|
45
|
+
day: date.getDate(),
|
|
46
|
+
hour: date.getHours(),
|
|
47
|
+
minute: date.getMinutes(),
|
|
48
|
+
second: date.getSeconds()
|
|
49
|
+
};
|
|
50
|
+
const parts = getZonedFormatter(timeZone).formatToParts(date);
|
|
51
|
+
const get = (type) => Number(parts.find((part) => part.type === type)?.value);
|
|
52
|
+
return {
|
|
53
|
+
year: get("year"),
|
|
54
|
+
month: get("month") - 1,
|
|
55
|
+
day: get("day"),
|
|
56
|
+
hour: get("hour"),
|
|
57
|
+
minute: get("minute"),
|
|
58
|
+
second: get("second")
|
|
59
|
+
};
|
|
60
|
+
};
|
|
61
|
+
var toUTCTime = ({ year, month, day, hour, minute, second }) => {
|
|
62
|
+
const date = /* @__PURE__ */ new Date(0);
|
|
63
|
+
date.setUTCFullYear(year, month, day);
|
|
64
|
+
date.setUTCHours(hour, minute, second);
|
|
65
|
+
return date.getTime();
|
|
66
|
+
};
|
|
67
|
+
var fromWallClockTime = (parts, timeZone) => {
|
|
68
|
+
if (!timeZone) {
|
|
69
|
+
const date = /* @__PURE__ */ new Date(0);
|
|
70
|
+
date.setFullYear(parts.year, parts.month, parts.day);
|
|
71
|
+
date.setHours(parts.hour, parts.minute, parts.second, 0);
|
|
72
|
+
return date;
|
|
73
|
+
}
|
|
74
|
+
const wallClockTime = toUTCTime(parts);
|
|
75
|
+
const readWallClockTime = (time) => toUTCTime(getDateTimeParts(new Date(time), timeZone));
|
|
76
|
+
const getOffset = (time) => readWallClockTime(time) - time;
|
|
77
|
+
const withOffsetBefore = wallClockTime - getOffset(wallClockTime - DAY_MS);
|
|
78
|
+
const withOffsetAfter = wallClockTime - getOffset(wallClockTime + DAY_MS);
|
|
79
|
+
if (withOffsetBefore === withOffsetAfter) return new Date(withOffsetBefore);
|
|
80
|
+
const occurrences = [withOffsetBefore, withOffsetAfter].filter((time) => readWallClockTime(time) === wallClockTime).sort((a, b) => a - b);
|
|
81
|
+
return new Date(occurrences[0] ?? withOffsetBefore);
|
|
82
|
+
};
|
|
83
|
+
var ISO_EXTENDED_DATE_TIME = /^(?<year>\d{4})-(?<month>\d{2})(?:-(?<day>\d{2})(?:[T ](?<hour>\d{2})(?::(?<minute>\d{2})(?::(?<second>\d{2})(?:[.,]\d+)?)?)?(?<offset>Z|(?<offsetSign>[+-])(?<offsetHours>\d{2}):?(?<offsetMinutes>\d{2})?)?)?)?$/;
|
|
84
|
+
var ISO_BASIC_DATE_TIME = /^(?<year>\d{4})(?<month>\d{2})(?<day>\d{2})(?:[T ](?<hour>\d{2})(?:(?<minute>\d{2})(?:(?<second>\d{2})(?:[.,]\d+)?)?)?(?<offset>Z|(?<offsetSign>[+-])(?<offsetHours>\d{2}):?(?<offsetMinutes>\d{2})?)?)?$/;
|
|
85
|
+
var parseDate = (value, timeZone) => {
|
|
86
|
+
const match = ISO_EXTENDED_DATE_TIME.exec(value) ?? ISO_BASIC_DATE_TIME.exec(value);
|
|
87
|
+
if (!match?.groups) {
|
|
88
|
+
const date = new Date(value);
|
|
89
|
+
return isNaN(date.getTime()) ? null : date;
|
|
90
|
+
}
|
|
91
|
+
const { year, month, day = "1", hour = "0", minute = "0", second = "0", offset, offsetSign, offsetHours = "0", offsetMinutes = "0" } = match.groups;
|
|
92
|
+
const parts = {
|
|
93
|
+
year: Number(year),
|
|
94
|
+
month: Number(month) - 1,
|
|
95
|
+
day: Number(day),
|
|
96
|
+
hour: Number(hour),
|
|
97
|
+
minute: Number(minute),
|
|
98
|
+
second: Number(second)
|
|
99
|
+
};
|
|
100
|
+
const utc = new Date(toUTCTime(parts));
|
|
101
|
+
if (!(utc.getUTCMonth() === parts.month && utc.getUTCDate() === parts.day && utc.getUTCHours() === parts.hour && utc.getUTCMinutes() === parts.minute && utc.getUTCSeconds() === parts.second && Number(offsetHours) < 24 && Number(offsetMinutes) < 60)) return null;
|
|
102
|
+
if (!offset) return fromWallClockTime(parts, timeZone);
|
|
103
|
+
const offsetMs = (Number(offsetHours) * 60 + Number(offsetMinutes)) * 60 * 1e3;
|
|
104
|
+
return new Date(utc.getTime() - (offsetSign === "-" ? -offsetMs : offsetMs));
|
|
105
|
+
};
|
|
106
|
+
var formatTime = ({ hour, minute }) => `${hour % 12 || 12}:${String(minute).padStart(2, "0")}${hour < 12 ? "am" : "pm"}`;
|
|
107
|
+
var formatDate = ({ year, month, day }, timeZone) => {
|
|
108
|
+
const date = `${day} ${MONTHS[month]}`;
|
|
109
|
+
return year === getDateTimeParts(/* @__PURE__ */ new Date(), timeZone).year ? date : `${date} ${year}`;
|
|
110
|
+
};
|
|
111
|
+
var formatDisplayDate = (dateString, timezone) => {
|
|
112
|
+
if (dateString instanceof Date) dateString = dateString.toISOString();
|
|
113
|
+
if (!dateString || dateString.length === 0 || typeof dateString !== "string") return "";
|
|
114
|
+
const timeZone = timezone || "UTC";
|
|
115
|
+
const date = parseDate(dateString, timeZone);
|
|
116
|
+
return date ? formatDate(getDateTimeParts(date, timeZone), timeZone) : INVALID_DATE;
|
|
117
|
+
};
|
|
118
|
+
/**
|
|
119
|
+
* Format a plain time in a given time zone.
|
|
120
|
+
*
|
|
121
|
+
* @example
|
|
122
|
+
* formatDisplayTime('2020-04-20T18:09:12.345Z', 'Africa/Lagos')
|
|
123
|
+
* // 7:09pm
|
|
124
|
+
*/
|
|
125
|
+
var formatDisplayTime = (dateString, timezone) => {
|
|
126
|
+
if (!dateString) return "";
|
|
127
|
+
const timeZone = timezone || "UTC";
|
|
128
|
+
const date = parseDate(dateString, timeZone);
|
|
129
|
+
return date ? formatTime(getDateTimeParts(date, timeZone)) : INVALID_DATE;
|
|
130
|
+
};
|
|
131
|
+
/**
|
|
132
|
+
* Formats a date based on the range, in the browser's time zone
|
|
133
|
+
* - For ranges above 365 days: shows month and year (e.g. "Apr 2025")
|
|
134
|
+
* - For ranges of 91 days or more: shows "Week of [date]"
|
|
135
|
+
* - For other ranges: shows the date in the same format as formatDisplayDate
|
|
136
|
+
*/
|
|
137
|
+
var formatDisplayDateWithRange = (date, range, showHours = false, hoursOnly = false) => {
|
|
138
|
+
if (!date) return "";
|
|
139
|
+
const parsed = parseDate(date);
|
|
140
|
+
if (!parsed) return INVALID_DATE;
|
|
141
|
+
const parts = getDateTimeParts(parsed);
|
|
142
|
+
if (range === 1 && hoursOnly) return formatTime(parts);
|
|
143
|
+
else if (range === 1 && showHours) return `${MONTHS[parts.month]} ${parts.day}, ${formatTime(parts)}`;
|
|
144
|
+
else if (range > 365) return `${MONTHS[parts.month]} ${parts.year}`;
|
|
145
|
+
else if (range >= 91) return `Week of ${formatDate(parts)}`;
|
|
146
|
+
return formatDate(parts);
|
|
147
|
+
};
|
|
148
|
+
//#endregion
|
|
149
|
+
export { formatDisplayDate, formatDisplayDateWithRange, formatDisplayTime };
|
|
150
|
+
|
|
151
|
+
//# sourceMappingURL=date-utils.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"date-utils.js","names":[],"sources":["../../src/lib/date-utils.ts"],"sourcesContent":["const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];\n\nconst DAY_MS = 24 * 60 * 60 * 1000;\n\n// Shown for a date that can't be parsed, so it can't be mistaken for a missing date\nconst INVALID_DATE = 'Invalid date';\n\ninterface DateTimeParts {\n year: number;\n month: number;\n day: number;\n hour: number;\n minute: number;\n second: number;\n}\n\nconst zonedFormatters = new Map<string, Intl.DateTimeFormat>();\n\n// A time zone the browser doesn't know falls back to UTC, as it did with moment-timezone\nconst getZonedFormatter = (timeZone: string): Intl.DateTimeFormat => {\n let formatter = zonedFormatters.get(timeZone);\n if (!formatter) {\n try {\n formatter = new Intl.DateTimeFormat('en-US', {\n timeZone,\n hourCycle: 'h23',\n year: 'numeric',\n month: 'numeric',\n day: 'numeric',\n hour: 'numeric',\n minute: 'numeric',\n second: 'numeric',\n });\n } catch (error) {\n if (!(error instanceof RangeError)) {\n throw error;\n }\n formatter = getZonedFormatter('UTC');\n }\n zonedFormatters.set(timeZone, formatter);\n }\n return formatter;\n};\n\n// Without a time zone, the parts are in the browser's local time\nconst getDateTimeParts = (date: Date, timeZone?: string): DateTimeParts => {\n if (!timeZone) {\n return {\n year: date.getFullYear(),\n month: date.getMonth(),\n day: date.getDate(),\n hour: date.getHours(),\n minute: date.getMinutes(),\n second: date.getSeconds(),\n };\n }\n\n const parts = getZonedFormatter(timeZone).formatToParts(date);\n const get = (type: Intl.DateTimeFormatPartTypes) =>\n Number(parts.find((part) => part.type === type)?.value);\n\n return {\n year: get('year'),\n month: get('month') - 1,\n day: get('day'),\n hour: get('hour'),\n minute: get('minute'),\n second: get('second'),\n };\n};\n\n// Unlike Date.UTC(), this doesn't read years 0-99 as 1900-1999\nconst toUTCTime = ({ year, month, day, hour, minute, second }: DateTimeParts): number => {\n const date = new Date(0);\n date.setUTCFullYear(year, month, day);\n date.setUTCHours(hour, minute, second);\n return date.getTime();\n};\n\n// Wall-clock time that a time zone skips, such as 2:30am when clocks go forward, moves forward by\n// the gap. Wall-clock time that it repeats reads as the first occurrence. Both match moment-timezone.\nconst fromWallClockTime = (parts: DateTimeParts, timeZone?: string): Date => {\n if (!timeZone) {\n // Local Date setters resolve skipped and repeated times the same way\n const date = new Date(0);\n date.setFullYear(parts.year, parts.month, parts.day);\n date.setHours(parts.hour, parts.minute, parts.second, 0);\n return date;\n }\n\n const wallClockTime = toUTCTime(parts);\n const readWallClockTime = (time: number) => toUTCTime(getDateTimeParts(new Date(time), timeZone));\n const getOffset = (time: number) => readWallClockTime(time) - time;\n\n // The offsets a day either side are the ones in use on each side of any change at this time\n const withOffsetBefore = wallClockTime - getOffset(wallClockTime - DAY_MS);\n const withOffsetAfter = wallClockTime - getOffset(wallClockTime + DAY_MS);\n if (withOffsetBefore === withOffsetAfter) {\n return new Date(withOffsetBefore);\n }\n\n const occurrences = [withOffsetBefore, withOffsetAfter]\n .filter((time) => readWallClockTime(time) === wallClockTime)\n .sort((a, b) => a - b);\n return new Date(occurrences[0] ?? withOffsetBefore);\n};\n\n// ISO 8601 dates and date-times in the forms moment reads, in the extended\n// (`2025-04-15T13:05:00+01:00`) and basic (`20250415T130500+0100`) formats\nconst ISO_EXTENDED_DATE_TIME =\n /^(?<year>\\d{4})-(?<month>\\d{2})(?:-(?<day>\\d{2})(?:[T ](?<hour>\\d{2})(?::(?<minute>\\d{2})(?::(?<second>\\d{2})(?:[.,]\\d+)?)?)?(?<offset>Z|(?<offsetSign>[+-])(?<offsetHours>\\d{2}):?(?<offsetMinutes>\\d{2})?)?)?)?$/;\nconst ISO_BASIC_DATE_TIME =\n /^(?<year>\\d{4})(?<month>\\d{2})(?<day>\\d{2})(?:[T ](?<hour>\\d{2})(?:(?<minute>\\d{2})(?:(?<second>\\d{2})(?:[.,]\\d+)?)?)?(?<offset>Z|(?<offsetSign>[+-])(?<offsetHours>\\d{2}):?(?<offsetMinutes>\\d{2})?)?)?$/;\n\n// An ISO 8601 date or date-time without an offset is wall-clock time in the time zone, as moment\n// reads it. `new Date()` alone would read a date-only string as UTC midnight.\nconst parseDate = (value: string, timeZone?: string): Date | null => {\n const match = ISO_EXTENDED_DATE_TIME.exec(value) ?? ISO_BASIC_DATE_TIME.exec(value);\n if (!match?.groups) {\n const date = new Date(value);\n return isNaN(date.getTime()) ? null : date;\n }\n\n const {\n year,\n month,\n day = '1',\n hour = '0',\n minute = '0',\n second = '0',\n offset,\n offsetSign,\n offsetHours = '0',\n offsetMinutes = '0',\n } = match.groups;\n const parts = {\n year: Number(year),\n month: Number(month) - 1,\n day: Number(day),\n hour: Number(hour),\n minute: Number(minute),\n second: Number(second),\n };\n\n // The formats only check the shape, so reject fields that would roll over, such as 30 February or 24:00\n const utc = new Date(toUTCTime(parts));\n const isValid =\n utc.getUTCMonth() === parts.month &&\n utc.getUTCDate() === parts.day &&\n utc.getUTCHours() === parts.hour &&\n utc.getUTCMinutes() === parts.minute &&\n utc.getUTCSeconds() === parts.second &&\n Number(offsetHours) < 24 &&\n Number(offsetMinutes) < 60;\n if (!isValid) {\n return null;\n }\n\n if (!offset) {\n return fromWallClockTime(parts, timeZone);\n }\n const offsetMs = (Number(offsetHours) * 60 + Number(offsetMinutes)) * 60 * 1000;\n return new Date(utc.getTime() - (offsetSign === '-' ? -offsetMs : offsetMs));\n};\n\n// Result is in the format of `7:09pm`\nconst formatTime = ({ hour, minute }: DateTimeParts): string =>\n `${hour % 12 || 12}:${String(minute).padStart(2, '0')}${hour < 12 ? 'am' : 'pm'}`;\n\n// Result is in the format of `12 Jun 2025`, without the year when it's the current year\nconst formatDate = ({ year, month, day }: DateTimeParts, timeZone?: string): string => {\n const date = `${day} ${MONTHS[month]}`;\n return year === getDateTimeParts(new Date(), timeZone).year ? date : `${date} ${year}`;\n};\n\n// Format date for UI, result is in the format of `12 Jun 2025`\n// Timestamps with an offset are shown in the given time zone, or in UTC without one\nexport const formatDisplayDate = (dateString: string, timezone?: string): string => {\n // If the date is a Date object, convert it to a string\n // @ts-expect-error This should error if dateString is not a string, but for some reason Typescript isn't catching this\n if (dateString instanceof Date) {\n dateString = dateString.toISOString();\n }\n // Fallback to empty string if dateString is an unexpected type. Better to fallback to empty string than to crash the app\n if (!dateString || dateString.length === 0 || typeof dateString !== 'string') {\n return '';\n }\n\n const timeZone = timezone || 'UTC';\n const date = parseDate(dateString, timeZone);\n return date ? formatDate(getDateTimeParts(date, timeZone), timeZone) : INVALID_DATE;\n};\n\n/**\n * Format a plain time in a given time zone.\n *\n * @example\n * formatDisplayTime('2020-04-20T18:09:12.345Z', 'Africa/Lagos')\n * // 7:09pm\n */\nexport const formatDisplayTime = (dateString: string, timezone: string): string => {\n if (!dateString) {\n return '';\n }\n\n const timeZone = timezone || 'UTC';\n const date = parseDate(dateString, timeZone);\n return date ? formatTime(getDateTimeParts(date, timeZone)) : INVALID_DATE;\n};\n\n/**\n * Formats a date based on the range, in the browser's time zone\n * - For ranges above 365 days: shows month and year (e.g. \"Apr 2025\")\n * - For ranges of 91 days or more: shows \"Week of [date]\"\n * - For other ranges: shows the date in the same format as formatDisplayDate\n */\nexport const formatDisplayDateWithRange = (\n date: string,\n range: number,\n showHours: boolean = false,\n hoursOnly: boolean = false,\n): string => {\n if (!date) {\n return '';\n }\n\n const parsed = parseDate(date);\n if (!parsed) {\n return INVALID_DATE;\n }\n const parts = getDateTimeParts(parsed);\n\n if (range === 1 && hoursOnly) {\n return formatTime(parts);\n } else if (range === 1 && showHours) {\n return `${MONTHS[parts.month]} ${parts.day}, ${formatTime(parts)}`;\n } else if (range > 365) {\n return `${MONTHS[parts.month]} ${parts.year}`;\n } else if (range >= 91) {\n return `Week of ${formatDate(parts)}`;\n }\n return formatDate(parts);\n};\n"],"mappings":";AAAA,IAAM,SAAS;CAAC;CAAO;CAAO;CAAO;CAAO;CAAO;CAAO;CAAO;CAAO;CAAO;CAAO;CAAO;AAAK;AAElG,IAAM,SAAS,OAAU,KAAK;AAG9B,IAAM,eAAe;AAWrB,IAAM,kCAAkB,IAAI,IAAiC;AAG7D,IAAM,qBAAqB,aAA0C;CACnE,IAAI,YAAY,gBAAgB,IAAI,QAAQ;CAC5C,IAAI,CAAC,WAAW;EACd,IAAI;GACF,YAAY,IAAI,KAAK,eAAe,SAAS;IAC3C;IACA,WAAW;IACX,MAAM;IACN,OAAO;IACP,KAAK;IACL,MAAM;IACN,QAAQ;IACR,QAAQ;GACV,CAAC;EACH,SAAS,OAAO;GACd,IAAI,EAAE,iBAAiB,aACrB,MAAM;GAER,YAAY,kBAAkB,KAAK;EACrC;EACA,gBAAgB,IAAI,UAAU,S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MAAM,OAAO,GAAG,MAAM;MAClC,IAAI,SAAS,IAClB,OAAO,WAAW,WAAW,KAAK;CAEpC,OAAO,WAAW,KAAK;AACzB"}
|
package/es/lib/ds-utils.js
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { clsx } from "clsx";
|
|
2
|
-
import moment from "moment-timezone";
|
|
3
2
|
import { twMerge } from "tailwind-merge";
|
|
4
3
|
//#region src/lib/ds-utils.ts
|
|
5
4
|
function cn(...inputs) {
|
|
@@ -30,62 +29,6 @@ var kebabToPascalCase = (str) => {
|
|
|
30
29
|
const processed = str.replace(/[-_]([a-z0-9])/gi, (_, char) => char.toUpperCase());
|
|
31
30
|
return processed.charAt(0).toUpperCase() + processed.slice(1);
|
|
32
31
|
};
|
|
33
|
-
var formatDisplayDate = (dateString, timezone) => {
|
|
34
|
-
if (dateString instanceof Date) dateString = dateString.toISOString();
|
|
35
|
-
if (!dateString || dateString.length === 0 || typeof dateString !== "string") return "";
|
|
36
|
-
const hasTime = dateString.includes(":");
|
|
37
|
-
const isISOFormat = dateString.includes("T") || dateString.includes("Z");
|
|
38
|
-
let day, month, year, isToday, isCurrentYear;
|
|
39
|
-
if (timezone && isISOFormat) {
|
|
40
|
-
const dateMoment = moment.tz(dateString, timezone);
|
|
41
|
-
const todayMoment = moment.tz(timezone);
|
|
42
|
-
day = dateMoment.date();
|
|
43
|
-
month = dateMoment.month();
|
|
44
|
-
year = dateMoment.year();
|
|
45
|
-
isToday = dateMoment.isSame(todayMoment, "day");
|
|
46
|
-
isCurrentYear = year === todayMoment.year();
|
|
47
|
-
} else {
|
|
48
|
-
const date = new Date(dateString);
|
|
49
|
-
const today = /* @__PURE__ */ new Date();
|
|
50
|
-
if (hasTime && !isISOFormat) {
|
|
51
|
-
day = date.getDate();
|
|
52
|
-
month = date.getMonth();
|
|
53
|
-
year = date.getFullYear();
|
|
54
|
-
isToday = date.toDateString() === today.toDateString();
|
|
55
|
-
isCurrentYear = year === today.getFullYear();
|
|
56
|
-
} else {
|
|
57
|
-
day = date.getUTCDate();
|
|
58
|
-
month = date.getUTCMonth();
|
|
59
|
-
year = date.getUTCFullYear();
|
|
60
|
-
isToday = date.toISOString().slice(0, 10) === today.toISOString().slice(0, 10);
|
|
61
|
-
isCurrentYear = year === today.getUTCFullYear();
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
const monthName = [
|
|
65
|
-
"Jan",
|
|
66
|
-
"Feb",
|
|
67
|
-
"Mar",
|
|
68
|
-
"Apr",
|
|
69
|
-
"May",
|
|
70
|
-
"Jun",
|
|
71
|
-
"Jul",
|
|
72
|
-
"Aug",
|
|
73
|
-
"Sep",
|
|
74
|
-
"Oct",
|
|
75
|
-
"Nov",
|
|
76
|
-
"Dec"
|
|
77
|
-
][month];
|
|
78
|
-
if (isToday) return `${day} ${monthName}`;
|
|
79
|
-
return isCurrentYear ? `${day} ${monthName}` : `${day} ${monthName} ${year}`;
|
|
80
|
-
};
|
|
81
|
-
/**
|
|
82
|
-
* Format a plain time in a given time zone.
|
|
83
|
-
*
|
|
84
|
-
* @example
|
|
85
|
-
* formatDisplayTime('2020-04-20T18:09:12.345Z', 'Africa/Lagos')
|
|
86
|
-
* // 7:09pm
|
|
87
|
-
*/
|
|
88
|
-
var formatDisplayTime = (dateString, timezone) => moment(dateString).tz(timezone).format("h:mma");
|
|
89
32
|
var formatTimestamp = (timestamp) => {
|
|
90
33
|
const date = new Date(timestamp);
|
|
91
34
|
const now = /* @__PURE__ */ new Date();
|
|
@@ -153,19 +96,6 @@ var stringToHslColor = (str, saturation, lightness) => {
|
|
|
153
96
|
for (let i = 0; i < str.length; i++) hash = str.charCodeAt(i) + ((hash << 5) - hash);
|
|
154
97
|
return "hsl(" + hash % 360 + ", " + saturation + "%, " + lightness + "%)";
|
|
155
98
|
};
|
|
156
|
-
/**
|
|
157
|
-
* Formats a date based on the range
|
|
158
|
-
* - For ranges above 365 days: shows month and year (e.g. "Apr 2025")
|
|
159
|
-
* - For ranges above 91 days: shows "Week of [date]"
|
|
160
|
-
* - For other ranges: uses the default formatDisplayDate
|
|
161
|
-
*/
|
|
162
|
-
var formatDisplayDateWithRange = (date, range, showHours = false, hoursOnly = false) => {
|
|
163
|
-
if (range === 1 && hoursOnly) return moment(date).format("h:mma");
|
|
164
|
-
else if (range === 1 && showHours) return moment(date).format("MMM D, h:mma");
|
|
165
|
-
else if (range > 365) return moment(date).format("MMM YYYY");
|
|
166
|
-
else if (range >= 91) return `Week of ${formatDisplayDate(date)}`;
|
|
167
|
-
return formatDisplayDate(date);
|
|
168
|
-
};
|
|
169
99
|
var getYRange = (data) => {
|
|
170
100
|
if (!data.length) return {
|
|
171
101
|
min: 0,
|
|
@@ -209,6 +139,6 @@ var calculateYAxisWidth = (ticks, formatter) => {
|
|
|
209
139
|
return Math.max(20, maxFormattedLength * 8 + 20);
|
|
210
140
|
};
|
|
211
141
|
//#endregion
|
|
212
|
-
export { abbreviateNumber, calculateYAxisWidth, cn, debounce,
|
|
142
|
+
export { abbreviateNumber, calculateYAxisWidth, cn, debounce, formatDuration, formatNumber, formatPercentage, formatTimestamp, getCountryFlag, getScrollParent, getYRange, kebabToPascalCase, stringToHslColor };
|
|
213
143
|
|
|
214
144
|
//# sourceMappingURL=ds-utils.js.map
|