code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
import * as React from "react" import { cva, type VariantProps } from "class-variance-authority" import { cn } from "@/lib/utils" const alertVariants = cva( "relative w-full rounded-lg border px-4 py-3 text-sm [&:has(svg)]:pl-11 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground", { variants: { variant: { default: "bg-background text-foreground", destructive: "border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive", }, }, defaultVariants: { variant: "default", }, } ) const Alert = React.forwardRef< HTMLDivElement, React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof alertVariants> >(({ className, variant, ...props }, ref) => ( <div ref={ref} role="alert" className={cn(alertVariants({ variant }), className)} {...props} /> )) Alert.displayName = "Alert" const AlertTitle = React.forwardRef< HTMLParagraphElement, React.HTMLAttributes<HTMLHeadingElement> >(({ className, ...props }, ref) => ( <h5 ref={ref} className={cn("mb-1 font-medium leading-none tracking-tight", className)} {...props} /> )) AlertTitle.displayName = "AlertTitle" const AlertDescription = React.forwardRef< HTMLParagraphElement, React.HTMLAttributes<HTMLParagraphElement> >(({ className, ...props }, ref) => ( <div ref={ref} className={cn("text-sm [&_p]:leading-relaxed", className)} {...props} /> )) AlertDescription.displayName = "AlertDescription" export { Alert, AlertTitle, AlertDescription }
2302_79757062/commit
dashboard/src/components/ui/alert.tsx
TSX
agpl-3.0
1,602
import * as React from "react" import * as AvatarPrimitive from "@radix-ui/react-avatar" import { cn } from "@/lib/utils" const Avatar = React.forwardRef< React.ElementRef<typeof AvatarPrimitive.Root>, React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Root> >(({ className, ...props }, ref) => ( <AvatarPrimitive.Root ref={ref} className={cn( "relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full", className )} {...props} /> )) Avatar.displayName = AvatarPrimitive.Root.displayName const AvatarImage = React.forwardRef< React.ElementRef<typeof AvatarPrimitive.Image>, React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Image> >(({ className, ...props }, ref) => ( <AvatarPrimitive.Image ref={ref} className={cn("aspect-square h-full w-full", className)} {...props} /> )) AvatarImage.displayName = AvatarPrimitive.Image.displayName const AvatarFallback = React.forwardRef< React.ElementRef<typeof AvatarPrimitive.Fallback>, React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Fallback> >(({ className, ...props }, ref) => ( <AvatarPrimitive.Fallback ref={ref} className={cn( "flex h-full w-full items-center justify-center rounded-full bg-muted", className )} {...props} /> )) AvatarFallback.displayName = AvatarPrimitive.Fallback.displayName export { Avatar, AvatarImage, AvatarFallback }
2302_79757062/commit
dashboard/src/components/ui/avatar.tsx
TSX
agpl-3.0
1,405
import * as React from "react" import { cva, type VariantProps } from "class-variance-authority" import { cn } from "@/lib/utils" const badgeVariants = cva( "inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2", { variants: { variant: { default: "border-transparent bg-primary text-primary-foreground shadow hover:bg-primary/80", secondary: "border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80", destructive: "border-transparent bg-destructive text-destructive-foreground shadow hover:bg-destructive/80", outline: "text-foreground", }, }, defaultVariants: { variant: "default", }, } ) export interface BadgeProps extends React.HTMLAttributes<HTMLDivElement>, VariantProps<typeof badgeVariants> {} function Badge({ className, variant, ...props }: BadgeProps) { return ( <div className={cn(badgeVariants({ variant }), className)} {...props} /> ) } export { Badge, badgeVariants }
2302_79757062/commit
dashboard/src/components/ui/badge.tsx
TSX
agpl-3.0
1,140
import * as React from "react" import { Slot } from "@radix-ui/react-slot" import { cva, type VariantProps } from "class-variance-authority" import { cn } from "@/lib/utils" const buttonVariants = cva( "inline-flex items-center justify-center rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50", { variants: { variant: { default: "bg-primary text-primary-foreground shadow hover:bg-primary/90", destructive: "bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90", outline: "border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground", secondary: "bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80", ghost: "hover:bg-accent hover:text-accent-foreground", link: "text-primary underline-offset-4 hover:underline", }, size: { default: "h-9 px-4 py-2", sm: "h-8 rounded-md px-3 text-xs", lg: "h-10 rounded-md px-8", icon: "h-9 w-9", }, }, defaultVariants: { variant: "default", size: "default", }, } ) export interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement>, VariantProps<typeof buttonVariants> { asChild?: boolean } const Button = React.forwardRef<HTMLButtonElement, ButtonProps>( ({ className, variant, size, asChild = false, ...props }, ref) => { const Comp = asChild ? Slot : "button" return ( <Comp className={cn(buttonVariants({ variant, size, className }))} ref={ref} {...props} /> ) } ) Button.displayName = "Button" export { Button, buttonVariants }
2302_79757062/commit
dashboard/src/components/ui/button.tsx
TSX
agpl-3.0
1,818
import * as React from "react" import { cn } from "@/lib/utils" const Card = React.forwardRef< HTMLDivElement, React.HTMLAttributes<HTMLDivElement> >(({ className, ...props }, ref) => ( <div ref={ref} className={cn( "rounded-xl border bg-card text-card-foreground shadow", className )} {...props} /> )) Card.displayName = "Card" const CardHeader = React.forwardRef< HTMLDivElement, React.HTMLAttributes<HTMLDivElement> >(({ className, ...props }, ref) => ( <div ref={ref} className={cn("flex flex-col space-y-1.5 p-6", className)} {...props} /> )) CardHeader.displayName = "CardHeader" const CardTitle = React.forwardRef< HTMLParagraphElement, React.HTMLAttributes<HTMLHeadingElement> >(({ className, ...props }, ref) => ( <h3 ref={ref} className={cn("font-semibold leading-none tracking-tight", className)} {...props} /> )) CardTitle.displayName = "CardTitle" const CardDescription = React.forwardRef< HTMLParagraphElement, React.HTMLAttributes<HTMLParagraphElement> >(({ className, ...props }, ref) => ( <p ref={ref} className={cn("text-sm text-muted-foreground", className)} {...props} /> )) CardDescription.displayName = "CardDescription" const CardContent = React.forwardRef< HTMLDivElement, React.HTMLAttributes<HTMLDivElement> >(({ className, ...props }, ref) => ( <div ref={ref} className={cn("p-6 pt-0", className)} {...props} /> )) CardContent.displayName = "CardContent" const CardFooter = React.forwardRef< HTMLDivElement, React.HTMLAttributes<HTMLDivElement> >(({ className, ...props }, ref) => ( <div ref={ref} className={cn(" flex items-center p-6 pt-0", className)} {...props} /> )) CardFooter.displayName = "CardFooter" export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }
2302_79757062/commit
dashboard/src/components/ui/card.tsx
TSX
agpl-3.0
1,848
import * as React from "react" import * as CheckboxPrimitive from "@radix-ui/react-checkbox" import { CheckIcon } from "@radix-ui/react-icons" import { cn } from "@/lib/utils" const Checkbox = React.forwardRef< React.ElementRef<typeof CheckboxPrimitive.Root>, React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root> >(({ className, ...props }, ref) => ( <CheckboxPrimitive.Root ref={ref} className={cn( "peer h-4 w-4 shrink-0 rounded-sm border border-primary shadow focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground", className )} {...props} > <CheckboxPrimitive.Indicator className={cn("flex items-center justify-center text-current")} > <CheckIcon className="h-4 w-4" /> </CheckboxPrimitive.Indicator> </CheckboxPrimitive.Root> )) Checkbox.displayName = CheckboxPrimitive.Root.displayName export { Checkbox }
2302_79757062/commit
dashboard/src/components/ui/checkbox.tsx
TSX
agpl-3.0
1,029
import * as React from "react" import { DialogProps } from "@radix-ui/react-dialog" import { MagnifyingGlassIcon } from "@radix-ui/react-icons" import { Command as CommandPrimitive } from "cmdk" import { cn } from "@/lib/utils" import { Dialog, DialogContent } from "@/components/ui/dialog" const Command = React.forwardRef< React.ElementRef<typeof CommandPrimitive>, React.ComponentPropsWithoutRef<typeof CommandPrimitive> >(({ className, ...props }, ref) => ( <CommandPrimitive ref={ref} className={cn( "flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground", className )} {...props} /> )) Command.displayName = CommandPrimitive.displayName interface CommandDialogProps extends DialogProps {} const CommandDialog = ({ children, ...props }: CommandDialogProps) => { return ( <Dialog {...props}> <DialogContent className="overflow-hidden p-0"> <Command className="[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5"> {children} </Command> </DialogContent> </Dialog> ) } const CommandInput = React.forwardRef< React.ElementRef<typeof CommandPrimitive.Input>, React.ComponentPropsWithoutRef<typeof CommandPrimitive.Input> >(({ className, ...props }, ref) => ( <div className="flex items-center border-b px-3" cmdk-input-wrapper=""> <MagnifyingGlassIcon className="mr-2 h-4 w-4 shrink-0 opacity-50" /> <CommandPrimitive.Input ref={ref} className={cn( "flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50", className )} {...props} /> </div> )) CommandInput.displayName = CommandPrimitive.Input.displayName const CommandList = React.forwardRef< React.ElementRef<typeof CommandPrimitive.List>, React.ComponentPropsWithoutRef<typeof CommandPrimitive.List> >(({ className, ...props }, ref) => ( <CommandPrimitive.List ref={ref} className={cn("max-h-[300px] overflow-y-auto overflow-x-hidden", className)} {...props} /> )) CommandList.displayName = CommandPrimitive.List.displayName const CommandEmpty = React.forwardRef< React.ElementRef<typeof CommandPrimitive.Empty>, React.ComponentPropsWithoutRef<typeof CommandPrimitive.Empty> >((props, ref) => ( <CommandPrimitive.Empty ref={ref} className="py-6 text-center text-sm" {...props} /> )) CommandEmpty.displayName = CommandPrimitive.Empty.displayName const CommandGroup = React.forwardRef< React.ElementRef<typeof CommandPrimitive.Group>, React.ComponentPropsWithoutRef<typeof CommandPrimitive.Group> >(({ className, ...props }, ref) => ( <CommandPrimitive.Group ref={ref} className={cn( "overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground", className )} {...props} /> )) CommandGroup.displayName = CommandPrimitive.Group.displayName const CommandSeparator = React.forwardRef< React.ElementRef<typeof CommandPrimitive.Separator>, React.ComponentPropsWithoutRef<typeof CommandPrimitive.Separator> >(({ className, ...props }, ref) => ( <CommandPrimitive.Separator ref={ref} className={cn("-mx-1 h-px bg-border", className)} {...props} /> )) CommandSeparator.displayName = CommandPrimitive.Separator.displayName const CommandItem = React.forwardRef< React.ElementRef<typeof CommandPrimitive.Item>, React.ComponentPropsWithoutRef<typeof CommandPrimitive.Item> >(({ className, ...props }, ref) => ( <CommandPrimitive.Item ref={ref} className={cn( "relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none aria-selected:bg-accent aria-selected:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50", className )} {...props} /> )) CommandItem.displayName = CommandPrimitive.Item.displayName const CommandShortcut = ({ className, ...props }: React.HTMLAttributes<HTMLSpanElement>) => { return ( <span className={cn( "ml-auto text-xs tracking-widest text-muted-foreground", className )} {...props} /> ) } CommandShortcut.displayName = "CommandShortcut" export { Command, CommandDialog, CommandInput, CommandList, CommandEmpty, CommandGroup, CommandItem, CommandShortcut, CommandSeparator, }
2302_79757062/commit
dashboard/src/components/ui/command.tsx
TSX
agpl-3.0
4,873
import * as React from "react" import * as DialogPrimitive from "@radix-ui/react-dialog" import { Cross2Icon } from "@radix-ui/react-icons" import { cn } from "@/lib/utils" const Dialog = DialogPrimitive.Root const DialogTrigger = DialogPrimitive.Trigger const DialogPortal = ({ className, ...props }: DialogPrimitive.DialogPortalProps) => ( <DialogPrimitive.Portal className={cn(className)} {...props} /> ) DialogPortal.displayName = DialogPrimitive.Portal.displayName const DialogOverlay = React.forwardRef< React.ElementRef<typeof DialogPrimitive.Overlay>, React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay> >(({ className, ...props }, ref) => ( <DialogPrimitive.Overlay ref={ref} className={cn( "fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0", className )} {...props} /> )) DialogOverlay.displayName = DialogPrimitive.Overlay.displayName const DialogContent = React.forwardRef< React.ElementRef<typeof DialogPrimitive.Content>, React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> >(({ className, children, ...props }, ref) => ( <DialogPortal> <DialogOverlay /> <DialogPrimitive.Content ref={ref} className={cn( "fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg md:w-full", className )} {...props} > {children} <DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground"> <Cross2Icon className="h-4 w-4" /> <span className="sr-only">Close</span> </DialogPrimitive.Close> </DialogPrimitive.Content> </DialogPortal> )) DialogContent.displayName = DialogPrimitive.Content.displayName const DialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => ( <div className={cn( "flex flex-col space-y-1.5 text-center sm:text-left", className )} {...props} /> ) DialogHeader.displayName = "DialogHeader" const DialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => ( <div className={cn( "flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2", className )} {...props} /> ) DialogFooter.displayName = "DialogFooter" const DialogTitle = React.forwardRef< React.ElementRef<typeof DialogPrimitive.Title>, React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title> >(({ className, ...props }, ref) => ( <DialogPrimitive.Title ref={ref} className={cn( "text-lg font-semibold leading-none tracking-tight", className )} {...props} /> )) DialogTitle.displayName = DialogPrimitive.Title.displayName const DialogDescription = React.forwardRef< React.ElementRef<typeof DialogPrimitive.Description>, React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description> >(({ className, ...props }, ref) => ( <DialogPrimitive.Description ref={ref} className={cn("text-sm text-muted-foreground", className)} {...props} /> )) DialogDescription.displayName = DialogPrimitive.Description.displayName export { Dialog, DialogTrigger, DialogContent, DialogHeader, DialogFooter, DialogTitle, DialogDescription, }
2302_79757062/commit
dashboard/src/components/ui/dialog.tsx
TSX
agpl-3.0
3,979
import * as React from "react" import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu" import { CheckIcon, ChevronRightIcon, DotFilledIcon, } from "@radix-ui/react-icons" import { cn } from "@/lib/utils" const DropdownMenu = DropdownMenuPrimitive.Root const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger const DropdownMenuGroup = DropdownMenuPrimitive.Group const DropdownMenuPortal = DropdownMenuPrimitive.Portal const DropdownMenuSub = DropdownMenuPrimitive.Sub const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup const DropdownMenuSubTrigger = React.forwardRef< React.ElementRef<typeof DropdownMenuPrimitive.SubTrigger>, React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubTrigger> & { inset?: boolean } >(({ className, inset, children, ...props }, ref) => ( <DropdownMenuPrimitive.SubTrigger ref={ref} className={cn( "flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent", inset && "pl-8", className )} {...props} > {children} <ChevronRightIcon className="ml-auto h-4 w-4" /> </DropdownMenuPrimitive.SubTrigger> )) DropdownMenuSubTrigger.displayName = DropdownMenuPrimitive.SubTrigger.displayName const DropdownMenuSubContent = React.forwardRef< React.ElementRef<typeof DropdownMenuPrimitive.SubContent>, React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubContent> >(({ className, ...props }, ref) => ( <DropdownMenuPrimitive.SubContent ref={ref} className={cn( "z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2", className )} {...props} /> )) DropdownMenuSubContent.displayName = DropdownMenuPrimitive.SubContent.displayName const DropdownMenuContent = React.forwardRef< React.ElementRef<typeof DropdownMenuPrimitive.Content>, React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content> >(({ className, sideOffset = 4, ...props }, ref) => ( <DropdownMenuPrimitive.Portal> <DropdownMenuPrimitive.Content ref={ref} sideOffset={sideOffset} className={cn( "z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md", "data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2", className )} {...props} /> </DropdownMenuPrimitive.Portal> )) DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName const DropdownMenuItem = React.forwardRef< React.ElementRef<typeof DropdownMenuPrimitive.Item>, React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & { inset?: boolean } >(({ className, inset, ...props }, ref) => ( <DropdownMenuPrimitive.Item ref={ref} className={cn( "relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50", inset && "pl-8", className )} {...props} /> )) DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName const DropdownMenuCheckboxItem = React.forwardRef< React.ElementRef<typeof DropdownMenuPrimitive.CheckboxItem>, React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.CheckboxItem> >(({ className, children, checked, ...props }, ref) => ( <DropdownMenuPrimitive.CheckboxItem ref={ref} className={cn( "relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50", className )} checked={checked} {...props} > <span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center"> <DropdownMenuPrimitive.ItemIndicator> <CheckIcon className="h-4 w-4" /> </DropdownMenuPrimitive.ItemIndicator> </span> {children} </DropdownMenuPrimitive.CheckboxItem> )) DropdownMenuCheckboxItem.displayName = DropdownMenuPrimitive.CheckboxItem.displayName const DropdownMenuRadioItem = React.forwardRef< React.ElementRef<typeof DropdownMenuPrimitive.RadioItem>, React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.RadioItem> >(({ className, children, ...props }, ref) => ( <DropdownMenuPrimitive.RadioItem ref={ref} className={cn( "relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50", className )} {...props} > <span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center"> <DropdownMenuPrimitive.ItemIndicator> <DotFilledIcon className="h-4 w-4 fill-current" /> </DropdownMenuPrimitive.ItemIndicator> </span> {children} </DropdownMenuPrimitive.RadioItem> )) DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName const DropdownMenuLabel = React.forwardRef< React.ElementRef<typeof DropdownMenuPrimitive.Label>, React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & { inset?: boolean } >(({ className, inset, ...props }, ref) => ( <DropdownMenuPrimitive.Label ref={ref} className={cn( "px-2 py-1.5 text-sm font-semibold", inset && "pl-8", className )} {...props} /> )) DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName const DropdownMenuSeparator = React.forwardRef< React.ElementRef<typeof DropdownMenuPrimitive.Separator>, React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Separator> >(({ className, ...props }, ref) => ( <DropdownMenuPrimitive.Separator ref={ref} className={cn("-mx-1 my-1 h-px bg-muted", className)} {...props} /> )) DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName const DropdownMenuShortcut = ({ className, ...props }: React.HTMLAttributes<HTMLSpanElement>) => { return ( <span className={cn("ml-auto text-xs tracking-widest opacity-60", className)} {...props} /> ) } DropdownMenuShortcut.displayName = "DropdownMenuShortcut" export { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem, DropdownMenuCheckboxItem, DropdownMenuRadioItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuShortcut, DropdownMenuGroup, DropdownMenuPortal, DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuRadioGroup, }
2302_79757062/commit
dashboard/src/components/ui/dropdown-menu.tsx
TSX
agpl-3.0
7,352
import * as React from "react" import * as LabelPrimitive from "@radix-ui/react-label" import { Slot } from "@radix-ui/react-slot" import { Controller, ControllerProps, FieldPath, FieldValues, FormProvider, useFormContext, } from "react-hook-form" import { cn } from "@/lib/utils" import { Label } from "@/components/ui/label" const Form = FormProvider type FormFieldContextValue< TFieldValues extends FieldValues = FieldValues, TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues> > = { name: TName } const FormFieldContext = React.createContext<FormFieldContextValue>( {} as FormFieldContextValue ) const FormField = < TFieldValues extends FieldValues = FieldValues, TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues> >({ ...props }: ControllerProps<TFieldValues, TName>) => { return ( <FormFieldContext.Provider value={{ name: props.name }}> <Controller {...props} /> </FormFieldContext.Provider> ) } const useFormField = () => { const fieldContext = React.useContext(FormFieldContext) const itemContext = React.useContext(FormItemContext) const { getFieldState, formState } = useFormContext() const fieldState = getFieldState(fieldContext.name, formState) if (!fieldContext) { throw new Error("useFormField should be used within <FormField>") } const { id } = itemContext return { id, name: fieldContext.name, formItemId: `${id}-form-item`, formDescriptionId: `${id}-form-item-description`, formMessageId: `${id}-form-item-message`, ...fieldState, } } type FormItemContextValue = { id: string } const FormItemContext = React.createContext<FormItemContextValue>( {} as FormItemContextValue ) const FormItem = React.forwardRef< HTMLDivElement, React.HTMLAttributes<HTMLDivElement> >(({ className, ...props }, ref) => { const id = React.useId() return ( <FormItemContext.Provider value={{ id }}> <div ref={ref} className={cn("space-y-2", className)} {...props} /> </FormItemContext.Provider> ) }) FormItem.displayName = "FormItem" const FormLabel = React.forwardRef< React.ElementRef<typeof LabelPrimitive.Root>, React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> >(({ className, ...props }, ref) => { const { error, formItemId } = useFormField() return ( <Label ref={ref} className={cn(error && "text-destructive", className)} htmlFor={formItemId} {...props} /> ) }) FormLabel.displayName = "FormLabel" const FormControl = React.forwardRef< React.ElementRef<typeof Slot>, React.ComponentPropsWithoutRef<typeof Slot> >(({ ...props }, ref) => { const { error, formItemId, formDescriptionId, formMessageId } = useFormField() return ( <Slot ref={ref} id={formItemId} aria-describedby={ !error ? `${formDescriptionId}` : `${formDescriptionId} ${formMessageId}` } aria-invalid={!!error} {...props} /> ) }) FormControl.displayName = "FormControl" const FormDescription = React.forwardRef< HTMLParagraphElement, React.HTMLAttributes<HTMLParagraphElement> >(({ className, ...props }, ref) => { const { formDescriptionId } = useFormField() return ( <p ref={ref} id={formDescriptionId} className={cn("text-[0.8rem] text-muted-foreground", className)} {...props} /> ) }) FormDescription.displayName = "FormDescription" const FormMessage = React.forwardRef< HTMLParagraphElement, React.HTMLAttributes<HTMLParagraphElement> >(({ className, children, ...props }, ref) => { const { error, formMessageId } = useFormField() const body = error ? String(error?.message) : children if (!body) { return null } return ( <p ref={ref} id={formMessageId} className={cn("text-[0.8rem] font-medium text-destructive", className)} {...props} > {body} </p> ) }) FormMessage.displayName = "FormMessage" export { useFormField, Form, FormItem, FormLabel, FormControl, FormDescription, FormMessage, FormField, }
2302_79757062/commit
dashboard/src/components/ui/form.tsx
TSX
agpl-3.0
4,097
import * as React from "react" import * as HoverCardPrimitive from "@radix-ui/react-hover-card" import { cn } from "@/lib/utils" const HoverCard = HoverCardPrimitive.Root const HoverCardTrigger = HoverCardPrimitive.Trigger const HoverCardContent = React.forwardRef< React.ElementRef<typeof HoverCardPrimitive.Content>, React.ComponentPropsWithoutRef<typeof HoverCardPrimitive.Content> >(({ className, align = "center", sideOffset = 4, ...props }, ref) => ( <HoverCardPrimitive.Content ref={ref} align={align} sideOffset={sideOffset} className={cn( "z-50 w-64 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2", className )} {...props} /> )) HoverCardContent.displayName = HoverCardPrimitive.Content.displayName export { HoverCard, HoverCardTrigger, HoverCardContent }
2302_79757062/commit
dashboard/src/components/ui/hover-card.tsx
TSX
agpl-3.0
1,184
import * as React from "react" import { cn } from "@/lib/utils" export interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {} const Input = React.forwardRef<HTMLInputElement, InputProps>( ({ className, type, ...props }, ref) => { return ( <input type={type} className={cn( "flex h-9 w-full rounded-md border border-input bg-background px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50", className )} ref={ref} {...props} /> ) } ) Input.displayName = "Input" export { Input }
2302_79757062/commit
dashboard/src/components/ui/input.tsx
TSX
agpl-3.0
800
import * as React from "react" import * as LabelPrimitive from "@radix-ui/react-label" import { cva, type VariantProps } from "class-variance-authority" import { cn } from "@/lib/utils" const labelVariants = cva( "text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70" ) const Label = React.forwardRef< React.ElementRef<typeof LabelPrimitive.Root>, React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> & VariantProps<typeof labelVariants> >(({ className, ...props }, ref) => ( <LabelPrimitive.Root ref={ref} className={cn(labelVariants(), className)} {...props} /> )) Label.displayName = LabelPrimitive.Root.displayName export { Label }
2302_79757062/commit
dashboard/src/components/ui/label.tsx
TSX
agpl-3.0
710
import * as React from "react" import * as PopoverPrimitive from "@radix-ui/react-popover" import { cn } from "@/lib/utils" const Popover = PopoverPrimitive.Root const PopoverTrigger = PopoverPrimitive.Trigger const PopoverContent = React.forwardRef< React.ElementRef<typeof PopoverPrimitive.Content>, React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content> >(({ className, align = "center", sideOffset = 4, ...props }, ref) => ( <PopoverPrimitive.Portal> <PopoverPrimitive.Content ref={ref} align={align} sideOffset={sideOffset} className={cn( "z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2", className )} {...props} /> </PopoverPrimitive.Portal> )) PopoverContent.displayName = PopoverPrimitive.Content.displayName export { Popover, PopoverTrigger, PopoverContent }
2302_79757062/commit
dashboard/src/components/ui/popover.tsx
TSX
agpl-3.0
1,230
import * as React from "react" import * as ProgressPrimitive from "@radix-ui/react-progress" import { cn } from "@/lib/utils" const Progress = React.forwardRef< React.ElementRef<typeof ProgressPrimitive.Root>, React.ComponentPropsWithoutRef<typeof ProgressPrimitive.Root> >(({ className, value, ...props }, ref) => ( <ProgressPrimitive.Root ref={ref} className={cn( "relative h-2 w-full overflow-hidden rounded-full bg-primary/20", className )} {...props} > <ProgressPrimitive.Indicator className="h-full w-full flex-1 bg-primary transition-all" style={{ transform: `translateX(-${100 - (value || 0)}%)` }} /> </ProgressPrimitive.Root> )) Progress.displayName = ProgressPrimitive.Root.displayName export { Progress }
2302_79757062/commit
dashboard/src/components/ui/progress.tsx
TSX
agpl-3.0
778
import * as React from "react" import { CheckIcon } from "@radix-ui/react-icons" import * as RadioGroupPrimitive from "@radix-ui/react-radio-group" import { cn } from "@/lib/utils" const RadioGroup = React.forwardRef< React.ElementRef<typeof RadioGroupPrimitive.Root>, React.ComponentPropsWithoutRef<typeof RadioGroupPrimitive.Root> >(({ className, ...props }, ref) => { return ( <RadioGroupPrimitive.Root className={cn("grid gap-2", className)} {...props} ref={ref} /> ) }) RadioGroup.displayName = RadioGroupPrimitive.Root.displayName const RadioGroupItem = React.forwardRef< React.ElementRef<typeof RadioGroupPrimitive.Item>, React.ComponentPropsWithoutRef<typeof RadioGroupPrimitive.Item> >(({ className, children, ...props }, ref) => { return ( <RadioGroupPrimitive.Item ref={ref} className={cn( "aspect-square h-4 w-4 rounded-full border border-primary text-primary shadow focus:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50", className )} {...props} > <RadioGroupPrimitive.Indicator className="flex items-center justify-center"> <CheckIcon className="h-3.5 w-3.5 fill-primary" /> </RadioGroupPrimitive.Indicator> </RadioGroupPrimitive.Item> ) }) RadioGroupItem.displayName = RadioGroupPrimitive.Item.displayName export { RadioGroup, RadioGroupItem }
2302_79757062/commit
dashboard/src/components/ui/radio-group.tsx
TSX
agpl-3.0
1,435
import * as React from "react" import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area" import { cn } from "@/lib/utils" const ScrollArea = React.forwardRef< React.ElementRef<typeof ScrollAreaPrimitive.Root>, React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root> >(({ className, children, ...props }, ref) => ( <ScrollAreaPrimitive.Root ref={ref} className={cn("relative overflow-hidden", className)} {...props} > <ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]"> {children} </ScrollAreaPrimitive.Viewport> <ScrollBar /> <ScrollAreaPrimitive.Corner /> </ScrollAreaPrimitive.Root> )) ScrollArea.displayName = ScrollAreaPrimitive.Root.displayName const ScrollBar = React.forwardRef< React.ElementRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>, React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar> >(({ className, orientation = "vertical", ...props }, ref) => ( <ScrollAreaPrimitive.ScrollAreaScrollbar ref={ref} orientation={orientation} className={cn( "flex touch-none select-none transition-colors", orientation === "vertical" && "h-full w-2.5 border-l border-l-transparent p-[1px]", orientation === "horizontal" && "h-2.5 border-t border-t-transparent p-[1px]", className )} {...props} > <ScrollAreaPrimitive.ScrollAreaThumb className="relative flex-1 rounded-full bg-border" /> </ScrollAreaPrimitive.ScrollAreaScrollbar> )) ScrollBar.displayName = ScrollAreaPrimitive.ScrollAreaScrollbar.displayName export { ScrollArea, ScrollBar }
2302_79757062/commit
dashboard/src/components/ui/scroll-area.tsx
TSX
agpl-3.0
1,633
import * as React from "react" import { CaretSortIcon, CheckIcon } from "@radix-ui/react-icons" import * as SelectPrimitive from "@radix-ui/react-select" import { cn } from "@/lib/utils" const Select = SelectPrimitive.Root const SelectGroup = SelectPrimitive.Group const SelectValue = SelectPrimitive.Value const SelectTrigger = React.forwardRef< React.ElementRef<typeof SelectPrimitive.Trigger>, React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger> >(({ className, children, ...props }, ref) => ( <SelectPrimitive.Trigger ref={ref} className={cn( "flex h-9 w-full items-center justify-between rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50", className )} {...props} > {children} <SelectPrimitive.Icon asChild> <CaretSortIcon className="h-4 w-4 opacity-50" /> </SelectPrimitive.Icon> </SelectPrimitive.Trigger> )) SelectTrigger.displayName = SelectPrimitive.Trigger.displayName const SelectContent = React.forwardRef< React.ElementRef<typeof SelectPrimitive.Content>, React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content> >(({ className, children, position = "popper", ...props }, ref) => ( <SelectPrimitive.Portal> <SelectPrimitive.Content ref={ref} className={cn( "relative z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2", position === "popper" && "data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1", className )} position={position} {...props} > <SelectPrimitive.Viewport className={cn( "p-1", position === "popper" && "h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]" )} > {children} </SelectPrimitive.Viewport> </SelectPrimitive.Content> </SelectPrimitive.Portal> )) SelectContent.displayName = SelectPrimitive.Content.displayName const SelectLabel = React.forwardRef< React.ElementRef<typeof SelectPrimitive.Label>, React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label> >(({ className, ...props }, ref) => ( <SelectPrimitive.Label ref={ref} className={cn("px-2 py-1.5 text-sm font-semibold", className)} {...props} /> )) SelectLabel.displayName = SelectPrimitive.Label.displayName const SelectItem = React.forwardRef< React.ElementRef<typeof SelectPrimitive.Item>, React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item> >(({ className, children, ...props }, ref) => ( <SelectPrimitive.Item ref={ref} className={cn( "relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50", className )} {...props} > <span className="absolute right-2 flex h-3.5 w-3.5 items-center justify-center"> <SelectPrimitive.ItemIndicator> <CheckIcon className="h-4 w-4" /> </SelectPrimitive.ItemIndicator> </span> <SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText> </SelectPrimitive.Item> )) SelectItem.displayName = SelectPrimitive.Item.displayName const SelectSeparator = React.forwardRef< React.ElementRef<typeof SelectPrimitive.Separator>, React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator> >(({ className, ...props }, ref) => ( <SelectPrimitive.Separator ref={ref} className={cn("-mx-1 my-1 h-px bg-muted", className)} {...props} /> )) SelectSeparator.displayName = SelectPrimitive.Separator.displayName export { Select, SelectGroup, SelectValue, SelectTrigger, SelectContent, SelectLabel, SelectItem, SelectSeparator, }
2302_79757062/commit
dashboard/src/components/ui/select.tsx
TSX
agpl-3.0
4,361
import * as React from "react" import * as SeparatorPrimitive from "@radix-ui/react-separator" import { cn } from "@/lib/utils" const Separator = React.forwardRef< React.ElementRef<typeof SeparatorPrimitive.Root>, React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root> >( ( { className, orientation = "horizontal", decorative = true, ...props }, ref ) => ( <SeparatorPrimitive.Root ref={ref} decorative={decorative} orientation={orientation} className={cn( "shrink-0 bg-border", orientation === "horizontal" ? "h-[1px] w-full" : "h-full w-[1px]", className )} {...props} /> ) ) Separator.displayName = SeparatorPrimitive.Root.displayName export { Separator }
2302_79757062/commit
dashboard/src/components/ui/separator.tsx
TSX
agpl-3.0
756
import * as React from "react" import * as SheetPrimitive from "@radix-ui/react-dialog" import { Cross2Icon } from "@radix-ui/react-icons" import { cva, type VariantProps } from "class-variance-authority" import { cn } from "@/lib/utils" const Sheet = SheetPrimitive.Root const SheetTrigger = SheetPrimitive.Trigger const SheetClose = SheetPrimitive.Close const SheetPortal = ({ className, ...props }: SheetPrimitive.DialogPortalProps) => ( <SheetPrimitive.Portal className={cn(className)} {...props} /> ) SheetPortal.displayName = SheetPrimitive.Portal.displayName const SheetOverlay = React.forwardRef< React.ElementRef<typeof SheetPrimitive.Overlay>, React.ComponentPropsWithoutRef<typeof SheetPrimitive.Overlay> >(({ className, ...props }, ref) => ( <SheetPrimitive.Overlay className={cn( "fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0", className )} {...props} ref={ref} /> )) SheetOverlay.displayName = SheetPrimitive.Overlay.displayName const sheetVariants = cva( "fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500", { variants: { side: { top: "inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top", bottom: "inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom", left: "inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm", right: "inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm", }, }, defaultVariants: { side: "right", }, } ) interface SheetContentProps extends React.ComponentPropsWithoutRef<typeof SheetPrimitive.Content>, VariantProps<typeof sheetVariants> {} const SheetContent = React.forwardRef< React.ElementRef<typeof SheetPrimitive.Content>, SheetContentProps >(({ side = "right", className, children, ...props }, ref) => ( <SheetPortal> <SheetOverlay /> <SheetPrimitive.Content ref={ref} className={cn(sheetVariants({ side }), className)} {...props} > {children} <SheetPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary"> <Cross2Icon className="h-4 w-4" /> <span className="sr-only">Close</span> </SheetPrimitive.Close> </SheetPrimitive.Content> </SheetPortal> )) SheetContent.displayName = SheetPrimitive.Content.displayName const SheetHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => ( <div className={cn( "flex flex-col space-y-2 text-center sm:text-left", className )} {...props} /> ) SheetHeader.displayName = "SheetHeader" const SheetFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => ( <div className={cn( "flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2", className )} {...props} /> ) SheetFooter.displayName = "SheetFooter" const SheetTitle = React.forwardRef< React.ElementRef<typeof SheetPrimitive.Title>, React.ComponentPropsWithoutRef<typeof SheetPrimitive.Title> >(({ className, ...props }, ref) => ( <SheetPrimitive.Title ref={ref} className={cn("text-lg font-semibold text-foreground", className)} {...props} /> )) SheetTitle.displayName = SheetPrimitive.Title.displayName const SheetDescription = React.forwardRef< React.ElementRef<typeof SheetPrimitive.Description>, React.ComponentPropsWithoutRef<typeof SheetPrimitive.Description> >(({ className, ...props }, ref) => ( <SheetPrimitive.Description ref={ref} className={cn("text-sm text-muted-foreground", className)} {...props} /> )) SheetDescription.displayName = SheetPrimitive.Description.displayName export { Sheet, SheetTrigger, SheetClose, SheetContent, SheetHeader, SheetFooter, SheetTitle, SheetDescription, }
2302_79757062/commit
dashboard/src/components/ui/sheet.tsx
TSX
agpl-3.0
4,457
import { cn } from "@/lib/utils" function Skeleton({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) { return ( <div className={cn("animate-pulse rounded-md bg-primary/10", className)} {...props} /> ) } export { Skeleton }
2302_79757062/commit
dashboard/src/components/ui/skeleton.tsx
TSX
agpl-3.0
266
import * as React from "react" import { cn } from "@/lib/utils" const Table = React.forwardRef< HTMLTableElement, React.HTMLAttributes<HTMLTableElement> >(({ className, ...props }, ref) => ( <div className="w-full overflow-auto"> <table ref={ref} className={cn("w-full caption-bottom text-sm", className)} {...props} /> </div> )) Table.displayName = "Table" const TableHeader = React.forwardRef< HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement> >(({ className, ...props }, ref) => ( <thead ref={ref} className={cn("[&_tr]:border-b", className)} {...props} /> )) TableHeader.displayName = "TableHeader" const TableBody = React.forwardRef< HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement> >(({ className, ...props }, ref) => ( <tbody ref={ref} className={cn("[&_tr:last-child]:border-0", className)} {...props} /> )) TableBody.displayName = "TableBody" const TableFooter = React.forwardRef< HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement> >(({ className, ...props }, ref) => ( <tfoot ref={ref} className={cn("bg-primary font-medium text-primary-foreground", className)} {...props} /> )) TableFooter.displayName = "TableFooter" const TableRow = React.forwardRef< HTMLTableRowElement, React.HTMLAttributes<HTMLTableRowElement> >(({ className, ...props }, ref) => ( <tr ref={ref} className={cn( "border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted", className )} {...props} /> )) TableRow.displayName = "TableRow" const TableHead = React.forwardRef< HTMLTableCellElement, React.ThHTMLAttributes<HTMLTableCellElement> >(({ className, ...props }, ref) => ( <th ref={ref} className={cn( "h-10 px-2 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]", className )} {...props} /> )) TableHead.displayName = "TableHead" const TableCell = React.forwardRef< HTMLTableCellElement, React.TdHTMLAttributes<HTMLTableCellElement> >(({ className, ...props }, ref) => ( <td ref={ref} className={cn( "p-2 align-middle [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]", className )} {...props} /> )) TableCell.displayName = "TableCell" const TableCaption = React.forwardRef< HTMLTableCaptionElement, React.HTMLAttributes<HTMLTableCaptionElement> >(({ className, ...props }, ref) => ( <caption ref={ref} className={cn("mt-4 text-sm text-muted-foreground", className)} {...props} /> )) TableCaption.displayName = "TableCaption" export { Table, TableHeader, TableBody, TableFooter, TableHead, TableRow, TableCell, TableCaption, }
2302_79757062/commit
dashboard/src/components/ui/table.tsx
TSX
agpl-3.0
2,823
import * as React from "react" import * as TabsPrimitive from "@radix-ui/react-tabs" import { cn } from "@/lib/utils" const Tabs = TabsPrimitive.Root const TabsList = React.forwardRef< React.ElementRef<typeof TabsPrimitive.List>, React.ComponentPropsWithoutRef<typeof TabsPrimitive.List> >(({ className, ...props }, ref) => ( <TabsPrimitive.List ref={ref} className={cn( "inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground", className )} {...props} /> )) TabsList.displayName = TabsPrimitive.List.displayName const TabsTrigger = React.forwardRef< React.ElementRef<typeof TabsPrimitive.Trigger>, React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger> >(({ className, ...props }, ref) => ( <TabsPrimitive.Trigger ref={ref} className={cn( "inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow", className )} {...props} /> )) TabsTrigger.displayName = TabsPrimitive.Trigger.displayName const TabsContent = React.forwardRef< React.ElementRef<typeof TabsPrimitive.Content>, React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content> >(({ className, ...props }, ref) => ( <TabsPrimitive.Content ref={ref} className={cn( "mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2", className )} {...props} /> )) TabsContent.displayName = TabsPrimitive.Content.displayName export { Tabs, TabsList, TabsTrigger, TabsContent }
2302_79757062/commit
dashboard/src/components/ui/tabs.tsx
TSX
agpl-3.0
1,877
import * as React from "react" import { cn } from "@/lib/utils" export interface TextareaProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {} const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>( ({ className, ...props }, ref) => { return ( <textarea className={cn( "flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50", className )} ref={ref} {...props} /> ) } ) Textarea.displayName = "Textarea" export { Textarea }
2302_79757062/commit
dashboard/src/components/ui/textArea.tsx
TSX
agpl-3.0
732
import * as React from "react" import { Cross2Icon } from "@radix-ui/react-icons" import * as ToastPrimitives from "@radix-ui/react-toast" import { cva, type VariantProps } from "class-variance-authority" import { cn } from "@/lib/utils" const ToastProvider = ToastPrimitives.Provider const ToastViewport = React.forwardRef< React.ElementRef<typeof ToastPrimitives.Viewport>, React.ComponentPropsWithoutRef<typeof ToastPrimitives.Viewport> >(({ className, ...props }, ref) => ( <ToastPrimitives.Viewport ref={ref} className={cn( "fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]", className )} {...props} /> )) ToastViewport.displayName = ToastPrimitives.Viewport.displayName const toastVariants = cva( "group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full", { variants: { variant: { default: "border bg-background", destructive: "destructive group border-destructive bg-destructive text-destructive-foreground", }, }, defaultVariants: { variant: "default", }, } ) const Toast = React.forwardRef< React.ElementRef<typeof ToastPrimitives.Root>, React.ComponentPropsWithoutRef<typeof ToastPrimitives.Root> & VariantProps<typeof toastVariants> >(({ className, variant, ...props }, ref) => { return ( <ToastPrimitives.Root ref={ref} className={cn(toastVariants({ variant }), className)} {...props} /> ) }) Toast.displayName = ToastPrimitives.Root.displayName const ToastAction = React.forwardRef< React.ElementRef<typeof ToastPrimitives.Action>, React.ComponentPropsWithoutRef<typeof ToastPrimitives.Action> >(({ className, ...props }, ref) => ( <ToastPrimitives.Action ref={ref} className={cn( "inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium transition-colors hover:bg-secondary focus:outline-none focus:ring-1 focus:ring-ring disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive", className )} {...props} /> )) ToastAction.displayName = ToastPrimitives.Action.displayName const ToastClose = React.forwardRef< React.ElementRef<typeof ToastPrimitives.Close>, React.ComponentPropsWithoutRef<typeof ToastPrimitives.Close> >(({ className, ...props }, ref) => ( <ToastPrimitives.Close ref={ref} className={cn( "absolute right-1 top-1 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-1 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600", className )} toast-close="" {...props} > <Cross2Icon className="h-4 w-4" /> </ToastPrimitives.Close> )) ToastClose.displayName = ToastPrimitives.Close.displayName const ToastTitle = React.forwardRef< React.ElementRef<typeof ToastPrimitives.Title>, React.ComponentPropsWithoutRef<typeof ToastPrimitives.Title> >(({ className, ...props }, ref) => ( <ToastPrimitives.Title ref={ref} className={cn("text-sm font-semibold [&+div]:text-xs", className)} {...props} /> )) ToastTitle.displayName = ToastPrimitives.Title.displayName const ToastDescription = React.forwardRef< React.ElementRef<typeof ToastPrimitives.Description>, React.ComponentPropsWithoutRef<typeof ToastPrimitives.Description> >(({ className, ...props }, ref) => ( <ToastPrimitives.Description ref={ref} className={cn("text-sm opacity-90", className)} {...props} /> )) ToastDescription.displayName = ToastPrimitives.Description.displayName type ToastProps = React.ComponentPropsWithoutRef<typeof Toast> type ToastActionElement = React.ReactElement<typeof ToastAction> export { type ToastProps, type ToastActionElement, ToastProvider, ToastViewport, Toast, ToastTitle, ToastDescription, ToastClose, ToastAction, }
2302_79757062/commit
dashboard/src/components/ui/toast.tsx
TSX
agpl-3.0
4,829
import { Toast, ToastClose, ToastDescription, ToastProvider, ToastTitle, ToastViewport, } from "@/components/ui/toast" import { useToast } from "@/components/ui/use-toast" export function Toaster() { const { toasts } = useToast() return ( <ToastProvider> {toasts.map(function ({ id, title, description, action, ...props }) { return ( <Toast key={id} {...props}> <div className="grid gap-1"> {title && <ToastTitle>{title}</ToastTitle>} {description && ( <ToastDescription>{description}</ToastDescription> )} </div> {action} <ToastClose /> </Toast> ) })} <ToastViewport /> </ToastProvider> ) }
2302_79757062/commit
dashboard/src/components/ui/toaster.tsx
TSX
agpl-3.0
780
import * as React from "react" import * as TooltipPrimitive from "@radix-ui/react-tooltip" import { cn } from "@/lib/utils" const TooltipProvider = TooltipPrimitive.Provider const Tooltip = TooltipPrimitive.Root const TooltipTrigger = TooltipPrimitive.Trigger const TooltipContent = React.forwardRef< React.ElementRef<typeof TooltipPrimitive.Content>, React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content> >(({ className, sideOffset = 4, ...props }, ref) => ( <TooltipPrimitive.Content ref={ref} sideOffset={sideOffset} className={cn( "z-50 overflow-hidden rounded-md bg-primary px-3 py-1.5 text-xs text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2", className )} {...props} /> )) TooltipContent.displayName = TooltipPrimitive.Content.displayName export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }
2302_79757062/commit
dashboard/src/components/ui/tooltip.tsx
TSX
agpl-3.0
1,128
// Inspired by react-hot-toast library import * as React from "react" import type { ToastActionElement, ToastProps, } from "@/components/ui/toast" const TOAST_LIMIT = 1 const TOAST_REMOVE_DELAY = 1000000 type ToasterToast = ToastProps & { id: string title?: React.ReactNode description?: React.ReactNode action?: ToastActionElement } const actionTypes = { ADD_TOAST: "ADD_TOAST", UPDATE_TOAST: "UPDATE_TOAST", DISMISS_TOAST: "DISMISS_TOAST", REMOVE_TOAST: "REMOVE_TOAST", } as const let count = 0 function genId() { count = (count + 1) % Number.MAX_VALUE return count.toString() } type ActionType = typeof actionTypes type Action = | { type: ActionType["ADD_TOAST"] toast: ToasterToast } | { type: ActionType["UPDATE_TOAST"] toast: Partial<ToasterToast> } | { type: ActionType["DISMISS_TOAST"] toastId?: ToasterToast["id"] } | { type: ActionType["REMOVE_TOAST"] toastId?: ToasterToast["id"] } interface State { toasts: ToasterToast[] } const toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>() const addToRemoveQueue = (toastId: string) => { if (toastTimeouts.has(toastId)) { return } const timeout = setTimeout(() => { toastTimeouts.delete(toastId) dispatch({ type: "REMOVE_TOAST", toastId: toastId, }) }, TOAST_REMOVE_DELAY) toastTimeouts.set(toastId, timeout) } export const reducer = (state: State, action: Action): State => { switch (action.type) { case "ADD_TOAST": return { ...state, toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT), } case "UPDATE_TOAST": return { ...state, toasts: state.toasts.map((t) => t.id === action.toast.id ? { ...t, ...action.toast } : t ), } case "DISMISS_TOAST": { const { toastId } = action // ! Side effects ! - This could be extracted into a dismissToast() action, // but I'll keep it here for simplicity if (toastId) { addToRemoveQueue(toastId) } else { state.toasts.forEach((toast) => { addToRemoveQueue(toast.id) }) } return { ...state, toasts: state.toasts.map((t) => t.id === toastId || toastId === undefined ? { ...t, open: false, } : t ), } } case "REMOVE_TOAST": if (action.toastId === undefined) { return { ...state, toasts: [], } } return { ...state, toasts: state.toasts.filter((t) => t.id !== action.toastId), } } } const listeners: Array<(state: State) => void> = [] let memoryState: State = { toasts: [] } function dispatch(action: Action) { memoryState = reducer(memoryState, action) listeners.forEach((listener) => { listener(memoryState) }) } type Toast = Omit<ToasterToast, "id"> function toast({ ...props }: Toast) { const id = genId() const update = (props: ToasterToast) => dispatch({ type: "UPDATE_TOAST", toast: { ...props, id }, }) const dismiss = () => dispatch({ type: "DISMISS_TOAST", toastId: id }) dispatch({ type: "ADD_TOAST", toast: { ...props, id, open: true, onOpenChange: (open) => { if (!open) dismiss() }, }, }) return { id: id, dismiss, update, } } function useToast() { const [state, setState] = React.useState<State>(memoryState) React.useEffect(() => { listeners.push(setState) return () => { const index = listeners.indexOf(setState) if (index > -1) { listeners.splice(index, 1) } } }, [state]) return { ...state, toast, dismiss: (toastId?: string) => dispatch({ type: "DISMISS_TOAST", toastId }), } } export { useToast, toast }
2302_79757062/commit
dashboard/src/components/ui/use-toast.ts
TypeScript
agpl-3.0
3,927
import moment from "moment" import { Moment } from "moment-timezone" /** * Converts a Frappe timestamp to a readable time ago string * @param timestamp A frappe timestamp string in the format YYYY-MM-DD HH:mm:ss * @param withoutSuffix remove the suffix from the time ago string * @returns */ export const convertFrappeTimestampToTimeAgo = (timestamp?: string, withoutSuffix?: boolean) => { if (timestamp) { const date = convertFrappeTimestampToUserTimezone(timestamp) return date.fromNow(withoutSuffix) } return '' } export const convertFrappeTimestampToUserTimezone = (timestamp: string): Moment => { // @ts-ignore const systemTimezone = window.frappe?.boot?.time_zone?.system // @ts-ignore const userTimezone = window.frappe?.boot?.time_zone?.user if (systemTimezone && userTimezone) { return moment.tz(timestamp, systemTimezone).clone().tz(userTimezone) } else { return moment(timestamp) } }
2302_79757062/commit
dashboard/src/components/utils/dateconversion.ts
TypeScript
agpl-3.0
977
const host = window.location.hostname; const web_port = window.location.port ? `:${window.location.port}` : ''; const protocol = web_port ? 'http' : 'https'; export const web_url = `${protocol}://${host}${web_port}`;
2302_79757062/commit
dashboard/src/config/socket.ts
TypeScript
agpl-3.0
217
import { useState, useEffect } from 'react'; /** * Hook to debounce a value * @param value Value to be debounced * @param delay Delay in milliseconds (default 200) * @returns Debounced value */ export const useDebounce = <T = any>(value: T, delay = 200): T => { const [debouncedValue, setDebouncedValue] = useState(value); useEffect(() => { const handler = setTimeout(() => { setDebouncedValue(value); }, delay); return () => { clearTimeout(handler); }; }, [value, delay]); return debouncedValue; }
2302_79757062/commit
dashboard/src/hooks/useDebounce.ts
TypeScript
agpl-3.0
580
import { FrappeConfig, FrappeContext, useFrappeGetCall } from "frappe-react-sdk" import { useContext } from "react" export const useGetDoctypeMeta = (doctype: string, with_parent: 0 | 1 = 1, cached_timestamp?: Date) => { //@ts-ignore const localData = locals?.['DocType']?.[doctype] || null const { data, error, isLoading } = useFrappeGetCall('frappe.desk.form.load.getdoctype', { doctype: doctype, with_parent: with_parent, cached_timestamp: cached_timestamp ?? null, }, localData || !doctype ? null : undefined, { onSuccess: (data) => { if (data) { data?.docs?.forEach((d: any) => { //@ts-ignore frappe.model.add_to_locals(d) }) } }, revalidateIfStale: false, revalidateOnFocus: false, }) return { data: localData || (data?.docs?.[0] ?? null), error, isLoading: localData ? false : isLoading } } export const useGetDoctypeMetaOnCall = () => { const { call } = useContext(FrappeContext) as FrappeConfig const getDoctypeMeta = async (doctype: string, with_parent: 0 | 1 = 1, cached_timestamp?: Date) => { //@ts-ignore const localData = locals?.['DocType']?.[doctype] || null if (localData) { return Promise.resolve(localData) } return call.get('frappe.desk.form.load.getdoctype', { doctype: doctype, with_parent: with_parent, cached_timestamp: cached_timestamp ?? null, }).then((r: any) => { if (r) { r?.docs?.forEach((d: any) => { //@ts-ignore frappe.model.add_to_locals(d) }) return r.docs[0] } }) } return getDoctypeMeta } export const useDoctypeForField = () => { // doctype is the doctype on which filter is going to be applied // fieldname is the fieldname of the filter // metaData is the metaData of that doctype from where this filter is being applied const stdFieldsList = [ "name", "owner", "creation", "modified", "modified_by", "_user_tags", "_comments", "_assign", "_liked_by", "docstatus", "idx", ] const getDoctypeMeta = useGetDoctypeMetaOnCall() const isFieldInDoctype = (fieldname: string, docmeta: any) => { const hasField = docmeta?.fields?.some((field: any) => { if (field.fieldname === fieldname) { return true } return false }) return hasField } /** * * @param doctype * @param fieldname * return promise that resolves to the doctype of the field */ const getDoctypeForField = (doctype: string, fieldname: string) => { /** * 1. check if fieldname is in stdFieldsList * 2. Check if field exists in the parent doctype * 3. If not, loop over all table fields and check if field exists in any of the child tables */ if (stdFieldsList.includes(fieldname)) { return Promise.resolve(doctype) } // If not in standard fields, check if field exists in parent doctype return getDoctypeMeta(doctype).then((data: any) => { // Check if field exists in parent doctype const hasField = isFieldInDoctype(fieldname, data) if (hasField) { return doctype } else { // Check if field exists in any of the child tables const tableFields = data?._table_fields || [] const checkInChildTables = async () => { let outDoctype = '' for (const f of tableFields) { const doctypeName = f.options const fieldExists = await getDoctypeMeta(doctypeName).then((doctypeMeta: any) => { const hasField = isFieldInDoctype(fieldname, doctypeMeta) return hasField }) if (fieldExists) { outDoctype = doctypeName break } } return outDoctype } return checkInChildTables() } }) } return getDoctypeForField }
2302_79757062/commit
dashboard/src/hooks/useGetDoctypeMeta.ts
TypeScript
agpl-3.0
4,549
@tailwind base; @tailwind components; @tailwind utilities; @layer base { :root { --background: 0 0% 100%; --foreground: 222.2 84% 4.9%; --muted: 210 40% 96.1%; --muted-foreground: 215.4 16.3% 46.9%; --popover: 0 0% 100%; --popover-foreground: 222.2 84% 4.9%; --card: 0 0% 100%; --card-foreground: 222.2 84% 4.9%; --border: 214.3 31.8% 91.4%; --input: 214.3 31.8% 91.4%; --primary: 222.2 47.4% 11.2%; --primary-foreground: 210 40% 98%; --secondary: 210 40% 96.1%; --secondary-foreground: 222.2 47.4% 11.2%; --accent: 210 40% 96.1%; --accent-foreground: 222.2 47.4% 11.2%; --destructive: 0 84.2% 60.2%; --destructive-foreground: 210 40% 98%; --ring: 215 20.2% 65.1%; --radius: 0.5rem; } .dark { --background: 222.2 84% 4.9%; --foreground: 210 40% 98%; --muted: 217.2 32.6% 17.5%; --muted-foreground: 215 20.2% 65.1%; --popover: 222.2 84% 4.9%; --popover-foreground: 210 40% 98%; --card: 222.2 84% 4.9%; --card-foreground: 210 40% 98%; --border: 217.2 32.6% 17.5%; --input: 217.2 32.6% 17.5%; --primary: 210 40% 98%; --primary-foreground: 222.2 47.4% 11.2%; --secondary: 217.2 32.6% 17.5%; --secondary-foreground: 210 40% 98%; --accent: 217.2 32.6% 17.5%; --accent-foreground: 210 40% 98%; --destructive: 0 62.8% 30.6%; --destructive-foreground: 0 85.7% 97.3%; --ring: 217.2 32.6% 17.5%; } } @layer base { * { @apply border-border; } body { @apply bg-background text-foreground; } }
2302_79757062/commit
dashboard/src/index.css
CSS
agpl-3.0
1,603
import { type ClassValue, clsx } from "clsx" import { twMerge } from "tailwind-merge" import moment from "moment-timezone" export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)) } export const convertStringDateToMoment = (date: string) => { if (date) { return moment(date, 'YYYY/MM/DD') } return null } export const convertFrappeTimestampToReadableDate = (timestamp?: string, format = 'MM-DD-YYYY') => { if (timestamp) { return moment(timestamp, 'YYYY-MM-DD HH:mm:ss').format(format) } return '' }
2302_79757062/commit
dashboard/src/lib/utils.ts
TypeScript
agpl-3.0
543
import React from 'react' import ReactDOM from 'react-dom/client' import App from './App.tsx' import './index.css' import { Toaster } from './components/ui/toaster.tsx' import './utils/namespace' if (import.meta.env.DEV) { fetch('/api/method/commit.www.commit.get_context_for_dev', { method: 'POST', }) .then(response => response.json()) .then((values) => { const v = JSON.parse(values.message) // @ts-expect-error if (!window.frappe) window.frappe = {}; //@ts-ignore frappe.boot = v //@ts-ignore frappe._messages = frappe.boot["__messages"]; //@ts-ignore frappe.model.sync(frappe.boot.docs); }) } ReactDOM.createRoot(document.getElementById('root')!).render( <React.StrictMode> <App /> <Toaster /> </React.StrictMode>, )
2302_79757062/commit
dashboard/src/main.tsx
TSX
agpl-3.0
812
import { Button } from "@/components/ui/button"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"; import { DocField } from "@/types/Core/DocField"; import { DotsHorizontalIcon } from "@radix-ui/react-icons"; import { useState } from "react"; import { FieldActionModal } from "./FieldModal"; export const FieldActionButton = ({ field }: { field: DocField }) => { const [open, setOpen] = useState(false) const onOpen = () => setOpen(true) const onClose = () => setOpen(false) return ( <> <DropdownMenu> <DropdownMenuTrigger asChild> <Button variant="ghost" className="h-8 w-8 p-0"> <span className="sr-only">Open menu</span> <DotsHorizontalIcon className="h-4 w-4" /> </Button> </DropdownMenuTrigger> <DropdownMenuContent align="end"> <DropdownMenuLabel>Actions</DropdownMenuLabel> <DropdownMenuItem onClick={onOpen}>View details</DropdownMenuItem> </DropdownMenuContent> </DropdownMenu> <FieldActionModal field={field} open={open} onClose={onClose} key={field.name} /> </> ) }
2302_79757062/commit
dashboard/src/pages/features/TableDrawer/FieldTable/FieldActionButton.tsx
TSX
agpl-3.0
1,337
import CopyButton from "@/components/common/CopyToClipboard/CopyToClipboard" import { Badge } from "@/components/ui/badge" import { Button } from "@/components/ui/button" import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog" import { convertFrappeTimestampToReadableDate } from "@/lib/utils" import { DocField } from "@/types/Core/DocField" import { CheckCircleIcon, ExclamationCircleIcon, EyeIcon, LinkIcon, RocketLaunchIcon } from "@heroicons/react/24/outline" import { CrossCircledIcon } from "@radix-ui/react-icons" export const FieldActionModal = ({ field, open, onClose }: { field: DocField, open: boolean, onClose: () => void }) => { return ( <Dialog open={open} onOpenChange={onClose}> <DialogContent className="p-6 w-[90vw] sm:max-w-[44vw] overflow-hidden"> <DialogHeader className="text-left"> <DialogTitle> <div className='pr-2'>{field.label} ({field.fieldname}) <CopyButton value={field.fieldname ?? ''} className="h-6 w-6 hover:bg-gray-300 ml-2 align-middle" /> </div> {field.documentation_url && <button type="button" className="rounded-md bg-white text-gray-400 hover:text-gray-600 focus:ring-2 focus:[ring-indigo-500 p-1]" onClick={() => window.open(field.documentation_url)} > <span className="sr-only">Open Documentation</span> <LinkIcon className="h-4 w-4" aria-hidden="true" /> </button>} </DialogTitle> <DialogDescription> <div className="grid gap-1"> <div className="flex justify-between"> <Badge variant={'outline'}>{field.fieldtype}</Badge> <div className="text-sm text-gray-500 italic">{convertFrappeTimestampToReadableDate(field.creation)}</div> </div> {field.description} <div className='flex gap-2'> {field.reqd === 1 && <div className="flex gap-1 bg-yellow-500 rounded-md p-1"> <span className="text-xs text-cyan-50 font-semibold">Mandatory</span> <ExclamationCircleIcon className="h-4 w-4 text-cyan-50" /> </div>} {field.is_virtual === 1 && <div className="flex gap-1 bg-yellow-500 rounded-md p-1"> <span className="text-xs text-cyan-50 font-semibold">Virtual</span> <EyeIcon className="h-4 w-4 text-cyan-50" /> </div>} {field.search_index === 1 && <div className="flex gap-1 bg-yellow-500 rounded-md p-1"> <span className="text-xs text-cyan-50 font-semibold">Index</span> <RocketLaunchIcon className="h-4 w-4 text-cyan-50" /> </div>} </div> </div> </DialogDescription> </DialogHeader> <div> <div className="flex flex-col justify-between gap-2 items-start"> <div className="grid gap-2 h-full"> <div className="grid items-start gap-2"> <div className="text-sm font-semibold">Visibility</div> <div className="grid grid-cols-3 gap-2"> <div className={`flex gap-1 justify-between ${field.hidden === 1 ? 'bg-green-600' : 'bg-gray-400'} rounded-md p-1`}> <span className="text-xs text-cyan-50 font-semibold">Hidden</span> {field.hidden === 1 ? <CheckCircleIcon className="h-4 w-4 text-cyan-50" /> : <CrossCircledIcon className="h-4 w-4 text-cyan-50" />} </div> <div className={`flex gap-1 justify-between ${field.bold === 1 ? 'bg-green-600' : 'bg-gray-400'} rounded-md p-1`}> <span className="text-xs text-cyan-50 font-semibold">Bold</span> {field.bold === 1 ? <CheckCircleIcon className="h-4 w-4 text-cyan-50" /> : <CrossCircledIcon className="h-4 w-4 text-cyan-50" />} </div> <div className={`flex gap-1 justify-between ${field.allow_in_quick_entry === 1 ? 'bg-green-500' : 'bg-gray-400'} rounded-md p-1`}> <span className="text-xs text-cyan-50 font-semibold">Quick Entry</span> {field.allow_in_quick_entry === 1 ? <CheckCircleIcon className="h-4 w-4 text-cyan-50" /> : <CrossCircledIcon className="h-4 w-4 text-cyan-50" />} </div> <div className={`flex gap-1 justify-between ${field.translatable === 1 ? 'bg-green-600' : 'bg-gray-400'} rounded-md p-1`}> <span className="text-xs text-cyan-50 font-semibold">Translatable</span> {field.translatable === 1 ? <CheckCircleIcon className="h-4 w-4 text-cyan-50" /> : <CrossCircledIcon className="h-4 w-4 text-cyan-50" />} </div> <div className={`flex gap-1 justify-between ${field.print_hide === 1 ? 'bg-green-600' : 'bg-gray-400'} rounded-md p-1`}> <span className="text-xs text-cyan-50 font-semibold">Print Hide</span> {field.print_hide === 1 ? <CheckCircleIcon className="h-4 w-4 text-cyan-50" /> : <CrossCircledIcon className="h-4 w-4 text-cyan-50" />} </div> <div className={`flex gap-1 justify-between ${field.report_hide === 1 ? 'bg-green-600' : 'bg-gray-400'} rounded-md p-1`}> <span className="text-xs text-cyan-50 font-semibold">Report Hide</span> {field.report_hide === 1 ? <CheckCircleIcon className="h-4 w-4 text-cyan-50" /> : <CrossCircledIcon className="h-4 w-4 text-cyan-50" />} </div> </div> </div> <div className="grid items-start gap-2"> <div className="text-sm font-semibold">List / Search Settings</div> <div className="grid grid-cols-3 gap-2"> <div className={`flex gap-1 justify-between ${field.in_list_view === 1 ? 'bg-green-600' : 'bg-gray-400'} rounded-md p-1`}> <span className="text-xs text-cyan-50 font-semibold">List View</span> {field.in_list_view === 1 ? <CheckCircleIcon className="h-4 w-4 text-cyan-50" /> : <CrossCircledIcon className="h-4 w-4 text-cyan-50" />} </div> <div className={`flex gap-1 justify-between ${field.in_standard_filter === 1 ? 'bg-green-600' : 'bg-gray-400'} rounded-md p-1`}> <span className="text-xs text-cyan-50 font-semibold">Standard Filter</span> {field.in_standard_filter === 1 ? <CheckCircleIcon className="h-4 w-4 text-cyan-50" /> : <CrossCircledIcon className="h-4 w-4 text-cyan-50" />} </div> <div className={`flex gap-1 justify-between ${field.in_preview === 1 ? 'bg-green-500' : 'bg-gray-400'} rounded-md p-1`}> <span className="text-xs text-cyan-50 font-semibold">Preview</span> {field.in_preview === 1 ? <CheckCircleIcon className="h-4 w-4 text-cyan-50" /> : <CrossCircledIcon className="h-4 w-4 text-cyan-50" />} </div> <div className={`flex gap-1 justify-between ${field.in_filter === 1 ? 'bg-green-600' : 'bg-gray-400'} rounded-md p-1`}> <span className="text-xs text-cyan-50 font-semibold">Filter</span> {field.in_filter === 1 ? <CheckCircleIcon className="h-4 w-4 text-cyan-50" /> : <CrossCircledIcon className="h-4 w-4 text-cyan-50" />} </div> <div className={`flex gap-1 justify-between ${field.in_global_search === 1 ? 'bg-green-600' : 'bg-gray-400'} rounded-md p-1`}> <span className="text-xs text-cyan-50 font-semibold">Global Search</span> {field.in_global_search === 1 ? <CheckCircleIcon className="h-4 w-4 text-cyan-50" /> : <CrossCircledIcon className="h-4 w-4 text-cyan-50" />} </div> </div> </div> <div className="grid items-start gap-2"> <div className="text-sm font-semibold">Permissions and Constraints</div> <div className="grid grid-cols-3 gap-2"> <div className={`flex gap-1 justify-between ${field.read_only === 1 ? 'bg-green-600' : 'bg-gray-400'} rounded-md p-1`}> <span className="text-xs text-cyan-50 font-semibold">Read Only</span> {field.read_only === 1 ? <CheckCircleIcon className="h-4 w-4 text-cyan-50" /> : <CrossCircledIcon className="h-4 w-4 text-gray-50" />} </div> <div className={`flex gap-1 justify-between ${field.allow_on_submit === 1 ? 'bg-green-600' : 'bg-gray-400'} rounded-md p-1`}> <span className="text-xs text-cyan-50 font-semibold">Allow on Submit</span> {field.allow_on_submit === 1 ? <CheckCircleIcon className="h-4 w-4 text-cyan-50" /> : <CrossCircledIcon className="h-4 w-4 text-gray-50" />} </div> <div className={`flex gap-1 justify-between ${field.set_only_once === 1 ? 'bg-green-600' : 'bg-gray-400'} rounded-md p-1`}> <span className="text-xs text-cyan-50 font-semibold">Set Only Once</span> {field.set_only_once === 1 ? <CheckCircleIcon className="h-4 w-4 text-cyan-50" /> : <CrossCircledIcon className="h-4 w-4 text-gray-50" />} </div> <div className={`flex gap-1 justify-between ${field.unique === 1 ? 'bg-green-600' : 'bg-gray-400'} rounded-md p-1`}> <span className="text-xs text-cyan-50 font-semibold">Unique</span> {field.unique === 1 ? <CheckCircleIcon className="h-4 w-4 text-cyan-50" /> : <CrossCircledIcon className="h-4 w-4 text-gray-50" />} </div> <div className={`flex gap-1 justify-between ${field.no_copy === 1 ? 'bg-green-600' : 'bg-gray-400'} rounded-md p-1`}> <span className="text-xs text-cyan-50 font-semibold">No Copy</span> {field.no_copy === 1 ? <CheckCircleIcon className="h-4 w-4 text-cyan-50" /> : <CrossCircledIcon className="h-4 w-4 text-gray-50" />} </div> <div className={`flex gap-1 justify-between ${field.ignore_user_permissions === 1 ? 'bg-green-500' : 'bg-gray-400'} rounded-md p-1`}> <span className="text-xs text-cyan-50 font-semibold">Ignore User Permissions</span> {field.ignore_user_permissions === 1 ? <CheckCircleIcon className="h-4 w-4 text-cyan-50" /> : <CrossCircledIcon className="h-4 w-4 text-gray-50" />} </div> </div> </div> </div> <div className="grid gap-2"> {field.default && <div className="grid items-start gap-2"> <div className="text-sm font-semibold">Default</div> <code className="flex justify-between items-start bg-gray-100 w-[300px] px-2 py-1 border-2 border-gray-200 rounded-md text-sm"> <div> {field.default} </div> <CopyButton value={field.default} className="h-6 w-6 hover:bg-gray-300" /> </code> </div>} <div className="grid items-start gap-2"> <div className="text-sm font-semibold">Options</div> <code className="flex justify-between items-start bg-gray-100 w-[300px] p-2 border-2 border-gray-200 rounded-md text-sm h-40 overflow-y-auto"> <div> {field.options?.split('\n').map((option, index) => { return <div key={index}>{option}</div> })} </div> {field.options && <CopyButton value={field.options} className="h-6 w-6 hover:bg-gray-300" />} </code> </div> {field.fetch_from && <div className="grid items-start gap-2"> <div className="text-sm font-semibold">Fetch From</div> <div className="flex gap-2"> <div className="grid gap-0"> <Badge variant={'outline'}>{field.fetch_from.split(".")[0].split('_').map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(' ')}</Badge> <div className="text-[10px] text-gray-500 px-1">DocType</div> </div> <div className="grid gap-0"> <Badge variant={'secondary'}> {field.fetch_from.split(".")[1]} </Badge> <div className="text-[10px] text-gray-500 px-1">Field</div> </div> </div> </div>} </div> </div> </div> <DialogFooter> <Button onClick={onClose}>Close</Button> </DialogFooter> </DialogContent> </Dialog> ) }
2302_79757062/commit
dashboard/src/pages/features/TableDrawer/FieldTable/FieldModal.tsx
TSX
agpl-3.0
15,963
import { Badge } from "@/components/ui/badge" import { Button } from "@/components/ui/button" import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandSeparator } from "@/components/ui/command" import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover" import { Separator } from "@/components/ui/separator" import { cn } from "@/lib/utils" import { CheckIcon, PlusCircledIcon } from "@radix-ui/react-icons" import { Column } from "@tanstack/react-table" interface DataTableFacetedFilter<TData, TValue> { column?: Column<TData, TValue> title?: string options: { label: string value: string icon?: React.ComponentType<{ className?: string }> }[] } export function DataTableFacetedFilter<TData, TValue>({ column, title, options, }: DataTableFacetedFilter<TData, TValue>) { const facets = column?.getFacetedUniqueValues() const selectedValues = new Set(column?.getFilterValue() as string[]) return ( <Popover> <PopoverTrigger asChild> <Button variant="outline" size="sm" className="h-8 border-dashed"> <PlusCircledIcon className="mr-2 h-4 w-4" /> {title} {selectedValues?.size > 0 && ( <> <Separator orientation="vertical" className="mx-2 h-4" /> <Badge variant="secondary" className="rounded-sm px-1 font-normal lg:hidden" > {selectedValues.size} </Badge> <div className="hidden space-x-1 lg:flex"> {selectedValues.size > 2 ? ( <Badge variant="secondary" className="rounded-sm px-1 font-normal" > {selectedValues.size} selected </Badge> ) : ( options .filter((option) => selectedValues.has(option.value)) .map((option) => ( <Badge variant="secondary" key={option.value} className="rounded-sm px-1 font-normal" > {option.label} </Badge> )) )} </div> </> )} </Button> </PopoverTrigger> <PopoverContent className="w-[200px] p-0" align="start"> <Command> <CommandInput placeholder={title} /> <CommandList> <CommandEmpty>No results found.</CommandEmpty> <CommandGroup> {options.sort((option1, option2) => { const length1 = facets?.get(option1.value) ?? 0 const length2 = facets?.get(option2.value) ?? 0 return length2 - length1 }).map((option) => { const isSelected = selectedValues.has(option.value) return ( <CommandItem key={option.value} onSelect={() => { if (isSelected) { selectedValues.delete(option.value) } else { selectedValues.add(option.value) } const filterValues = Array.from(selectedValues) column?.setFilterValue( filterValues.length ? filterValues : undefined ) }} > <div className={cn( "mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary", isSelected ? "bg-primary text-primary-foreground" : "opacity-50 [&_svg]:invisible" )} > <CheckIcon className={cn("h-4 w-4")} /> </div> {option.icon && ( <option.icon className="mr-2 h-4 w-4 text-muted-foreground" /> )} <span>{option.label}</span> {facets?.get(option.value) ? ( <span className="ml-auto flex h-4 w-4 items-center justify-center font-mono text-xs"> {facets.get(option.value)} </span> ) : ( <span className="ml-auto flex h-4 w-4 items-center justify-center font-mono text-xs"> 0 </span> )} </CommandItem> ) })} </CommandGroup> {selectedValues.size > 0 && ( <> <CommandSeparator /> <CommandGroup> <CommandItem onSelect={() => column?.setFilterValue(undefined)} className="justify-center text-center" > Clear filters </CommandItem> </CommandGroup> </> )} </CommandList> </Command> </PopoverContent> </Popover> ) } export default DataTableFacetedFilter
2302_79757062/commit
dashboard/src/pages/features/TableDrawer/FieldTable/FieldTypeFilters.tsx
TSX
agpl-3.0
7,276
import { ICON_KEY_MAP } from "@/components/common/Icons" export interface FieldTypeOptionsType { label: string value: string icon?: React.ComponentType<{ className?: string }> } export type ICON_KEY = 'Autocomplete' | 'Attach' | 'Attach Image' | 'Check' | 'Color' | 'Currency' | 'Data' | 'Date' | 'Datetime' | 'Duration' | 'Dynamic Link' | 'Float' | 'Geolocation' | 'Image' | 'Int' | 'JSON' | 'Link' | 'Long Text' | 'Password' | 'Percent' | 'Phone' | 'Read Only' | 'Rating' | 'Select' | 'Signature' | 'Small Text' | 'Table' | 'Table MultiSelect' | 'Text' | 'Time' export const FieldTypeOptions: FieldTypeOptionsType[] = [ { label: 'Autocomplete', value: 'Autocomplete', icon: ICON_KEY_MAP['Autocomplete'] }, { label: 'Attach', value: 'Attach', icon: ICON_KEY_MAP['Attach'] }, { label: 'Attach Image', value: 'Attach Image', icon: ICON_KEY_MAP['Attach Image'] }, { label: 'Check', value: 'Check', icon: ICON_KEY_MAP['Check'] }, { label: 'Color', value: 'Color', icon: ICON_KEY_MAP['Color'] }, { label: 'Currency', value: 'Currency', icon: ICON_KEY_MAP['Currency'] }, { label: 'Data', value: 'Data', icon: ICON_KEY_MAP['Data'] }, { label: 'Date', value: 'Date', icon: ICON_KEY_MAP['Date'] }, { label: 'Datetime', value: 'Datetime', icon: ICON_KEY_MAP['Datetime'] }, { label: 'Duration', value: 'Duration', icon: ICON_KEY_MAP['Duration'] }, { label: 'Dynamic Link', value: 'Dynamic Link', icon: ICON_KEY_MAP['Dynamic Link'] }, { label: 'Float', value: 'Float', icon: ICON_KEY_MAP['Float'] }, { label: 'Geolocation', value: 'Geolocation', icon: ICON_KEY_MAP['Geolocation'] }, { label: 'Image', value: 'Image', icon: ICON_KEY_MAP['Image'] }, { label: 'Int', value: 'Int', icon: ICON_KEY_MAP['Int'] }, { label: 'JSON', value: 'JSON', icon: ICON_KEY_MAP['JSON'] }, { label: 'Link', value: 'Link', icon: ICON_KEY_MAP['Link'] }, { label: 'Long Text', value: 'Long Text', icon: ICON_KEY_MAP['Long Text'] }, { label: 'Password', value: 'Password', icon: ICON_KEY_MAP['Password'] }, { label: 'Percent', value: 'Percent', icon: ICON_KEY_MAP['Percent'] }, { label: 'Phone', value: 'Phone', icon: ICON_KEY_MAP['Phone'] }, { label: 'Read Only', value: 'Read Only', icon: ICON_KEY_MAP['Read Only'] }, { label: 'Rating', value: 'Rating', icon: ICON_KEY_MAP['Rating'] }, { label: 'Select', value: 'Select', icon: ICON_KEY_MAP['Select'] }, { label: 'Signature', value: 'Signature', icon: ICON_KEY_MAP['Signature'] }, { label: 'Small Text', value: 'Small Text', icon: ICON_KEY_MAP['Small Text'] }, { label: 'Table', value: 'Table', icon: ICON_KEY_MAP['Table'] }, { label: 'Table MultiSelect', value: 'Table MultiSelect', icon: ICON_KEY_MAP['Table MultiSelect'] }, { label: 'Text', value: 'Text', icon: ICON_KEY_MAP['Text'] }, { label: 'Time', value: 'Time', icon: ICON_KEY_MAP['Time'] }, ]
2302_79757062/commit
dashboard/src/pages/features/TableDrawer/FieldTable/FieldTypeOptions.ts
TypeScript
agpl-3.0
3,741
import { ChevronDownIcon, } from "@radix-ui/react-icons" import { ColumnDef, ColumnFiltersState, SortingState, VisibilityState, flexRender, getCoreRowModel, getFilteredRowModel, getSortedRowModel, getFacetedUniqueValues, useReactTable, } from "@tanstack/react-table" import { Button } from "@/components/ui/button" import { DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu" import { Input } from "@/components/ui/input" import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from "@/components/ui/table" import { DocField } from "@/types/Core/DocField" import { useMemo, useState } from "react" import { FieldTypeOptions } from "./FieldTypeOptions" import { DataTableFacetedFilter } from "./FieldTypeFilters" import { Checkbox } from "@/components/ui/checkbox" import { OptionsComponent } from "./IconTextComponent" import CopyButton from "@/components/common/CopyToClipboard/CopyToClipboard" import { FieldActionButton } from "./FieldActionButton" export interface DrawerTableProps { data: DocField[] } export const UnwantedDataTypes = [ 'Tab Break', 'Column Break', 'Section Break', 'HTML', 'Button', 'Barcode', 'Fold', 'Heading', 'HTML Editor', 'Markdown Editor', 'Icon', ] export const FieldsTable = ({ data }: DrawerTableProps) => { const columns: ColumnDef<DocField>[] = [ // { // id: "select", // header: ({ table }) => ( // <Checkbox // checked={table.getIsAllPageRowsSelected()} // onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)} // aria-label="Select all" // /> // ), // cell: ({ row }) => ( // <Checkbox // checked={row.getIsSelected()} // onCheckedChange={(value) => row.toggleSelected(!!value)} // aria-label="Select row" // /> // ), // enableSorting: false, // enableHiding: false, // }, { accessorKey: "label", header: "Label", cell: ({ row }) => <CopyHovor value={row.getValue('label')} />, }, { accessorKey: "fieldname", header: () => <div className="text-start">Name</div>, cell: ({ row }) => <CopyHovor value={row.getValue('fieldname')} />, }, { accessorKey: "fieldtype", header: () => <div className="text-start">Type</div>, cell: ({ row }) => <div> <OptionsComponent field={row.original} /></div>, filterFn: (row, id, value: string) => { return value.includes(row.getValue(id)) }, }, { id: "actions", enableHiding: false, cell: ({ row }) => <FieldActionButton field={row.original} />, }, ] const ValidData = useMemo(() => { return data.filter((field) => { return !UnwantedDataTypes.includes(field.fieldtype) }) }, [data]) const [isFetchFrom, setIsFetchFrom] = useState(false) const FilterData = useMemo(() => { if (isFetchFrom) { return ValidData.filter((field) => { return field.fetch_from !== undefined && field.fetch_from !== null && field.fetch_from !== '' }) } return ValidData }, [ValidData, isFetchFrom]) const [sorting, setSorting] = useState<SortingState>([]) const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([]) const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({}) const [rowSelection, setRowSelection] = useState({}) const table = useReactTable({ data: FilterData, columns, onSortingChange: setSorting, onColumnFiltersChange: setColumnFilters, getCoreRowModel: getCoreRowModel(), getSortedRowModel: getSortedRowModel(), getFilteredRowModel: getFilteredRowModel(), onColumnVisibilityChange: setColumnVisibility, onRowSelectionChange: setRowSelection, getFacetedUniqueValues: getFacetedUniqueValues(), state: { sorting, columnFilters, columnVisibility, rowSelection, }, }) return ( <div className="w-full"> <div className="flex items-center py-2"> <Input placeholder="Filter label..." value={(table.getColumn("label")?.getFilterValue() as string) ?? ""} onChange={(event) => table.getColumn("label")?.setFilterValue(event.target.value) } className="max-w-xs" /> <div className="px-2"> {table.getColumn("fieldtype") && ( <DataTableFacetedFilter column={table.getColumn("fieldtype")} title="Fieldtype" options={FieldTypeOptions} /> )} </div> <div className="px-2 flex items-center"> <Checkbox id="fetch_from" checked={isFetchFrom} onCheckedChange={(value) => setIsFetchFrom(!!value)} /> <label htmlFor="fetch_from" className="ml-2 text-xs text-gray-700">Fetch From</label> </div> <DropdownMenu> <DropdownMenuTrigger asChild> <Button variant="outline" className="ml-auto"> Columns <ChevronDownIcon className="ml-2 h-4 w-4" /> </Button> </DropdownMenuTrigger> <DropdownMenuContent align="end"> {table .getAllColumns() .filter((column) => column.getCanHide()) .map((column) => { return ( <DropdownMenuCheckboxItem key={column.id} className="capitalize" checked={column.getIsVisible()} onCheckedChange={(value) => column.toggleVisibility(!!value) } > {column.id} </DropdownMenuCheckboxItem> ) })} </DropdownMenuContent> </DropdownMenu> </div> <div className="rounded-md border"> <Table> <TableHeader> {table.getHeaderGroups().map((headerGroup) => ( <TableRow key={headerGroup.id}> {headerGroup.headers.map((header) => { return ( <TableHead key={header.id} style={{ paddingTop: '0.25rem', paddingBottom: '0.25rem', }} > {header.isPlaceholder ? null : flexRender( header.column.columnDef.header, header.getContext() )} </TableHead> ) })} </TableRow> ))} </TableHeader> <TableBody> {table.getRowModel().rows?.length ? ( table.getRowModel().rows.map((row) => ( <TableRow key={row.id} data-state={row.getIsSelected() && "selected"} > {row.getVisibleCells().map((cell) => ( <TableCell key={cell.id} style={{ paddingTop: '0.25rem', paddingBottom: '0.25rem', }} > {flexRender( cell.column.columnDef.cell, cell.getContext() )} </TableCell> ))} </TableRow> )) ) : ( <TableRow> <TableCell colSpan={columns.length} className="h-24 text-center" > No results. </TableCell> </TableRow> )} </TableBody> </Table> </div> <div className="flex items-center justify-end space-x-2 py-4"> <div className="flex-1 text-sm text-muted-foreground"> Total {table.getFilteredRowModel().rows.length} row(s). </div> </div> </div> ) } export const CopyHovor = ({ value }: { value: string }) => { return ( <div className="group flex space-x-2 items-center"> <div className="">{value}</div> <CopyButton value={value} className="h-6 w-6 invisible bg-zinc-200 hover:bg-zinc-400 group-hover:visible" /> </div> ) }
2302_79757062/commit
dashboard/src/pages/features/TableDrawer/FieldTable/FieldsTable.tsx
TSX
agpl-3.0
10,561
import { Badge } from "@/components/ui/badge" import { DocField } from "@/types/Core/DocField" export const OptionsComponent = ({ field }: { field: DocField }) => { if (field.fieldtype === 'Link' || field.fieldtype === 'Table' || field.fieldtype === 'Table MultiSelect') { return <div className='flex flex-row'> <div className='mr-1'>{field.fieldtype} - </div> <div className='text-blue-500 hover:underline'>{field.options}</div> </div> } if (field.fieldtype === 'Select') { return <div className='flex flex-row'> <div className='mr-1'>{field.fieldtype} - </div> <div className='text-gray-500'>{field.options?.split('\n').length ?? 0} options</div> </div> } if (field.fieldtype === 'Data' && field.options) { return <div className='flex flex-row'> <div className='mr-2'>{field.fieldtype}</div> <EmailLinkPhoneIcon options={field.options} /> </div> } return <div>{field.fieldtype}</div> } export const EmailLinkPhoneIcon = ({ options }: { options: string }) => { if (options === 'Email') { return <Badge variant={'default'} style={{ backgroundColor: '#718096' }} className='text-xs'>Email</Badge> } if (options === 'Phone') { return <Badge variant={'default'} style={{ backgroundColor: '#38A169' }} className='text-xs'>Phone</Badge> } if (options === 'Link') { return <Badge variant={'default'} style={{ backgroundColor: '#3182CE' }} className='text-xs'>Link</Badge> } return null }
2302_79757062/commit
dashboard/src/pages/features/TableDrawer/FieldTable/IconTextComponent.tsx
TSX
agpl-3.0
1,645
import { Button } from "@/components/ui/button"; import { Checkbox } from "@/components/ui/checkbox"; import { DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"; import { Table, TableHeader, TableRow, TableHead, TableBody, TableCell } from "@/components/ui/table"; import { DocTypeLink } from "@/types/Core/DocTypeLink"; import { ChevronDownIcon } from "@radix-ui/react-icons"; import { ColumnDef, VisibilityState, flexRender, getCoreRowModel, getFacetedUniqueValues, getFilteredRowModel, getSortedRowModel, useReactTable } from "@tanstack/react-table"; import { useState } from "react"; export const LinkTable = ({ links }: { links: DocTypeLink[] }) => { const columns: ColumnDef<DocTypeLink>[] = [ { accessorKey: "link_doctype", header: "Link Doctype", cell: ({ row }) => ( <div>{row.getValue("link_doctype")}</div> ), }, { accessorKey: "link_fieldname", header: "Link Fieldname", cell: ({ row }) => <div>{row.getValue("link_fieldname")}</div>, }, { accessorKey: "group", header: "Group", cell: ({ row }) => <div>{row.getValue("group")}</div>, }, { accessorKey: "table_fieldname", header: "Table Field", cell: ({ row }) => <div>{row.getValue("table_fieldname")}</div>, }, { accessorKey: "hidden", header: "Hidden", cell: ({ row }) => <Checkbox id={row.id} checked={row.getValue("hidden") ? true : false} disabled={true} />, }, { accessorKey: "is_child_table", header: "Child Table", cell: ({ row }) => <Checkbox id={row.id} checked={row.getValue("is_child_table") ? true : false} disabled={true} />, }, ] const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({ 'hidden': false, 'is_child_table': false, 'table_fieldname': false }) const table = useReactTable({ data: links, columns, getCoreRowModel: getCoreRowModel(), getSortedRowModel: getSortedRowModel(), getFilteredRowModel: getFilteredRowModel(), getFacetedUniqueValues: getFacetedUniqueValues(), onColumnVisibilityChange: setColumnVisibility, state: { columnVisibility } }) return ( <div className="w-full"> <div className="flex items-center py-2"> <DropdownMenu> <DropdownMenuTrigger asChild> <Button variant="outline" className="ml-auto"> Columns <ChevronDownIcon className="ml-2 h-4 w-4" /> </Button> </DropdownMenuTrigger> <DropdownMenuContent align="end"> {table .getAllColumns() .filter((column) => column.getCanHide()) .map((column) => { return ( <DropdownMenuCheckboxItem key={column.id} className="capitalize" checked={column.getIsVisible()} onCheckedChange={(value) => column.toggleVisibility(!!value) } > {column.id} </DropdownMenuCheckboxItem> ) })} </DropdownMenuContent> </DropdownMenu> </div> <div className="rounded-md border"> <Table> <TableHeader> {table.getHeaderGroups().map((headerGroup) => ( <TableRow key={headerGroup.id}> {headerGroup.headers.map((header) => { return ( <TableHead key={header.id}> {header.isPlaceholder ? null : flexRender( header.column.columnDef.header, header.getContext() )} </TableHead> ) })} </TableRow> ))} </TableHeader> <TableBody> {table.getRowModel().rows?.length ? ( table.getRowModel().rows.map((row) => ( <TableRow key={row.id} data-state={row.getIsSelected() && "selected"} > {row.getVisibleCells().map((cell) => ( <TableCell key={cell.id} > {flexRender( cell.column.columnDef.cell, cell.getContext() )} </TableCell> ))} </TableRow> )) ) : ( <TableRow> <TableCell colSpan={columns.length} className="h-24 text-center" > No results. </TableCell> </TableRow> )} </TableBody> </Table> </div> <div className="flex items-center justify-end space-x-2 py-4"> <div className="flex-1 text-sm text-muted-foreground"> Total {table.getFilteredRowModel().rows.length} row(s). </div> </div> </div> ) }
2302_79757062/commit
dashboard/src/pages/features/TableDrawer/LinkTable/LinkTable.tsx
TSX
agpl-3.0
6,679
import { LinkIcon, XMarkIcon } from '@heroicons/react/24/outline' import { useFrappeGetCall } from "frappe-react-sdk" import { DocType } from "@/types/Core/DocType" import { convertFrappeTimestampToReadableDate } from '@/lib/utils' import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs" import { DocField } from '@/types/Core/DocField' import { Badge } from '@/components/ui/badge' import { FieldsTable } from './FieldTable/FieldsTable' import { PermissionsTable } from './PermissionsTable/PermissionsTable' import { DocPerm } from '@/types/Core/DocPerm' import { LinkTable } from './LinkTable/LinkTable' import { DocTypeLink } from '@/types/Core/DocTypeLink' import { FullPageLoader } from '@/components/common/FullPageLoader/FullPageLoader' export interface Props { doctype?: string isOpen: boolean onClose: () => void } export interface DocTypeResponse { doctype_json: DocType } export const MetaTableDrawer = ({ doctype, isOpen, onClose }: Props) => { const { data, error, isLoading } = useFrappeGetCall<{ message: DocType }>('commit.api.erd_viewer.get_meta_for_doctype', { doctype }, doctype ? undefined : null) const doctypeMeta = data?.message return ( <div data-state={isOpen ? 'open' : 'closed'} className={`fixed z-50 grid gap-4 border bg-background p-6 py-4 shadow-lg transition-transform duration-500 ease-in-out sm:h-full sm:w-[60vw] sm:top-0 sm:right-0 ${isOpen ? 'sm:translate-x-0' : 'sm:translate-x-full'} w-full h-[70vh] bottom-0 ${isOpen ? 'translate-y-0' : 'translate-y-full'}`} > {error && <div>{error.message}</div>} {isLoading && <FullPageLoader />} {doctypeMeta && <div className="flex h-full flex-col overflow-y-scroll"> <div className='flex flex-col space-y-1.5 text-center sm:text-left'> <div className='flex justify-between'> <div className='font-semibold text-left px-2 tracking-tight text-2xl'> <div className='pr-2'>{doctypeMeta.name}</div> {doctypeMeta.documentation && <button type="button" className="rounded-md bg-white text-gray-400 hover:text-gray-600 focus:ring-2 focus:[ring-indigo-500 p-1]" onClick={() => window.open(doctypeMeta.documentation)} > <span className="sr-only">Open Documentation</span> <LinkIcon className="h-4 w-4" aria-hidden="true" /> </button>} </div> <button type="button" title='Close' className="rounded-md bg-white border border-transparent hover:border-blue-200 focus:ring-2 focus:[ring-indigo-500 p-1]" onClick={onClose} > <span className="sr-only">Close panel</span> <XMarkIcon className="h-5 w-5 m-1" aria-hidden="true" /> </button> </div> <div className='flex flex-col gap-1 text-sm text-left text-muted-foreground'> {/* class="text-sm text-muted-foreground" */} {doctypeMeta.description && <div> <p className="text-sm text-gray-500 px-2">{doctypeMeta.description}</p> </div>} <div className='flex flex-row px-2 pt-1'> <Badge variant={'default'} style={{ backgroundColor: '#319795' }} className='mr-1'>{doctypeMeta.module}</Badge> {doctypeMeta.istable ? <Badge variant={'default'} style={{ backgroundColor: '#3182CE' }} className='mr-1'>Child Table</Badge> : null} {doctypeMeta.issingle ? <Badge variant={'default'} style={{ backgroundColor: '#38A169' }} className='mr-1'>Single</Badge> : null} </div> <div className="sm:px-0 sm:pt-2 pb-2"> <dl className="space-y-4 px-2 sm:space-y-4 sm:px-2 items-start"> <div className='space-y-2'> <div> <dt className="text-sm font-medium text-gray-500">Created on: {convertFrappeTimestampToReadableDate(doctypeMeta.creation)}</dt> </div> <div> <dt className="text-sm font-medium text-gray-500">Last Modified: {convertFrappeTimestampToReadableDate(doctypeMeta.modified)}</dt> </div> </div> </dl> </div> </div> </div> <div className="px-2 sm:px-2"> <Tabs defaultValue="fields" className="w-full"> <TabsList className='w-full justify-start'> <TabsTrigger value="fields">Fields</TabsTrigger> <TabsTrigger value="permissions">Permissions</TabsTrigger> <TabsTrigger value="links">Link</TabsTrigger> </TabsList> <TabsContent value="fields"><FieldsTable data={doctypeMeta.fields ?? [] as DocField[]} /></TabsContent> <TabsContent value="permissions"><PermissionsTable permissions={doctypeMeta.permissions ?? [] as DocPerm[]} /> </TabsContent> <TabsContent value="links"><LinkTable links={doctypeMeta.links ?? [] as DocTypeLink[]} /></TabsContent> </Tabs> </div> </div>} </div> ) }
2302_79757062/commit
dashboard/src/pages/features/TableDrawer/MetaTableDrawer.tsx
TSX
agpl-3.0
6,220
import { Button } from "@/components/ui/button"; import { Checkbox } from "@/components/ui/checkbox"; import { DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; import { DocPerm } from "@/types/Core/DocPerm"; import { ChevronDownIcon } from "@radix-ui/react-icons"; import { ColumnDef, useReactTable, getCoreRowModel, getFilteredRowModel, getSortedRowModel, getFacetedUniqueValues, VisibilityState, flexRender, } from "@tanstack/react-table"; import { useState } from "react"; export const PermissionsTable = ({ permissions }: { permissions: DocPerm[] }) => { const columns: ColumnDef<DocPerm>[] = [ { accessorKey: "role", header: "Role", cell: ({ row }) => ( <div>{row.getValue("role")}</div> ), }, { accessorKey: "permlevel", header: "Level", cell: ({ row }) => <div>{row.getValue("permlevel") ?? 0}</div>, }, { accessorKey: "select", header: "Select", cell: ({ row }) => <Checkbox id={row.id} checked={row.getValue("select") ? true : false} disabled={true} />, }, { accessorKey: "read", header: "Read", cell: ({ row }) => <Checkbox id={row.id} checked={row.getValue("read") ? true : false} disabled={true} />, }, { accessorKey: "write", header: "Write", cell: ({ row }) => <Checkbox id={row.id} checked={row.getValue("write") ? true : false} disabled={true} />, }, { accessorKey: "create", header: "Create", cell: ({ row }) => <Checkbox id={row.id} checked={row.getValue("create") ? true : false} disabled={true} />, }, { accessorKey: "delete", header: "Delete", cell: ({ row }) => <Checkbox id={row.id} checked={row.getValue("delete") ? true : false} disabled={true} />, }, { accessorKey: "submit", header: "Submit", cell: ({ row }) => <Checkbox id={row.id} checked={row.getValue("submit") ? true : false} disabled={true} />, }, { accessorKey: "cancel", header: "Cancel", cell: ({ row }) => <Checkbox id={row.id} checked={row.getValue("cancel") ? true : false} disabled={true} />, }, { accessorKey: "amend", header: "Amend", cell: ({ row }) => <Checkbox id={row.id} checked={row.getValue("amend") ? true : false} disabled={true} />, }, { accessorKey: "report", header: "Report", cell: ({ row }) => <Checkbox id={row.id} checked={row.getValue("report") ? true : false} disabled={true} />, }, { accessorKey: "import", header: "Import", cell: ({ row }) => <Checkbox id={row.id} checked={row.getValue("import") ? true : false} disabled={true} />, }, { accessorKey: "export", header: "Export", cell: ({ row }) => <Checkbox id={row.id} checked={row.getValue("export") ? true : false} disabled={true} />, }, { accessorKey: "print", header: "Print", cell: ({ row }) => <Checkbox id={row.id} checked={row.getValue("print") ? true : false} disabled={true} />, }, { accessorKey: "email", header: "Email", cell: ({ row }) => <Checkbox id={row.id} checked={row.getValue("email") ? true : false} disabled={true} />, }, { accessorKey: "share", header: "Share", cell: ({ row }) => <Checkbox id={row.id} checked={row.getValue("share") ? true : false} disabled={true} />, }, ] const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({ 'cancel': false, 'amend': false, 'report': false, 'import': false, 'export': false, 'print': false, 'email': false, 'share': false }) const table = useReactTable({ data: permissions, columns, getCoreRowModel: getCoreRowModel(), getSortedRowModel: getSortedRowModel(), getFilteredRowModel: getFilteredRowModel(), getFacetedUniqueValues: getFacetedUniqueValues(), onColumnVisibilityChange: setColumnVisibility, state: { columnVisibility } }) return ( <div className="w-full"> <div className="flex items-center py-2"> <DropdownMenu> <DropdownMenuTrigger asChild> <Button variant="outline" className="ml-auto"> Columns <ChevronDownIcon className="ml-2 h-4 w-4" /> </Button> </DropdownMenuTrigger> <DropdownMenuContent align="end"> {table .getAllColumns() .filter((column) => column.getCanHide()) .map((column) => { return ( <DropdownMenuCheckboxItem key={column.id} className="capitalize" checked={column.getIsVisible()} onCheckedChange={(value) => column.toggleVisibility(!!value) } > {column.id} </DropdownMenuCheckboxItem> ) })} </DropdownMenuContent> </DropdownMenu> </div> <div className="rounded-md border"> <Table> <TableHeader> {table.getHeaderGroups().map((headerGroup) => ( <TableRow key={headerGroup.id}> {headerGroup.headers.map((header) => { return ( <TableHead key={header.id} > {header.isPlaceholder ? null : flexRender( header.column.columnDef.header, header.getContext() )} </TableHead> ) })} </TableRow> ))} </TableHeader> <TableBody> {table.getRowModel().rows?.length ? ( table.getRowModel().rows.map((row) => ( <TableRow key={row.id} data-state={row.getIsSelected() && "selected"} > {row.getVisibleCells().map((cell) => ( <TableCell key={cell.id}> {flexRender( cell.column.columnDef.cell, cell.getContext() )} </TableCell> ))} </TableRow> )) ) : ( <TableRow> <TableCell colSpan={columns.length} className="h-24 text-center" > No results. </TableCell> </TableRow> )} </TableBody> </Table> </div> <div className="flex items-center justify-end space-x-2 py-4"> <div className="flex-1 text-sm text-muted-foreground"> Total {table.getFilteredRowModel().rows.length} row(s). </div> </div> </div> ) }
2302_79757062/commit
dashboard/src/pages/features/TableDrawer/PermissionsTable/PermissionsTable.tsx
TSX
agpl-3.0
8,864
// import { Dialog, Transition } from '@headlessui/react' import { LinkIcon, XMarkIcon } from '@heroicons/react/24/outline' import { useFrappeGetCall } from "frappe-react-sdk" import { DocType } from "@/types/Core/DocType" import { convertFrappeTimestampToReadableDate } from '@/lib/utils' import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs" import { DocField } from '@/types/Core/DocField' import { Badge } from '@/components/ui/badge' import { FieldsTable } from './FieldTable/FieldsTable' import { PermissionsTable } from './PermissionsTable/PermissionsTable' import { DocPerm } from '@/types/Core/DocPerm' import { LinkTable } from './LinkTable/LinkTable' import { DocTypeLink } from '@/types/Core/DocTypeLink' import { FullPageLoader } from '@/components/common/FullPageLoader/FullPageLoader' export interface Props { project_branch?: string doctype?: string isOpen: boolean onClose: () => void } export interface DocTypeResponse { doctype_json: DocType } export const TableDrawer = ({ doctype, isOpen, onClose, project_branch }: Props) => { const { data, error, isLoading } = useFrappeGetCall<{ message: DocType }>('commit.api.erd_viewer.get_doctype_json', { project_branch: project_branch, doctype: doctype }, doctype ? undefined : null) return ( <div data-state={isOpen ? 'open' : 'closed'} className={`fixed z-50 grid gap-4 border bg-background p-6 py-4 shadow-lg transition-transform duration-500 ease-in-out sm:h-full sm:w-[60vw] sm:top-0 sm:right-0 ${isOpen ? 'sm:translate-x-0' : 'sm:translate-x-full'} w-full h-[70vh] bottom-0 ${isOpen ? 'translate-y-0' : 'translate-y-full'}`} > {error && <div>{error.message}</div>} {isLoading && <FullPageLoader />} {data && data.message && <div className="flex h-full flex-col overflow-y-scroll"> <div className='flex flex-col space-y-1.5 text-center sm:text-left'> <div className='flex justify-between'> <div className='font-semibold text-left px-2 tracking-tight text-2xl'> <div className='pr-2'>{data.message.name}</div> {data.message.documentation && <button type="button" className="rounded-md bg-white text-gray-400 hover:text-gray-600 focus:ring-2 focus:[ring-indigo-500 p-1]" onClick={() => window.open(data.message.documentation)} > <span className="sr-only">Open Documentation</span> <LinkIcon className="h-4 w-4" aria-hidden="true" /> </button>} </div> <button type="button" title='Close' className="rounded-md bg-white border border-transparent hover:border-blue-200 focus:ring-2 focus:[ring-indigo-500 p-1]" onClick={onClose} > <span className="sr-only">Close panel</span> <XMarkIcon className="h-5 w-5 m-1" aria-hidden="true" /> </button> </div> <div className='flex flex-col gap-1 text-sm text-left text-muted-foreground'> {/* class="text-sm text-muted-foreground" */} {data.message.description && <div> <p className="text-sm text-gray-500 px-2">{data.message.description}</p> </div>} <div className='flex flex-row px-2 pt-1'> <Badge variant={'default'} style={{ backgroundColor: '#319795' }} className='mr-1'>{data.message.module}</Badge> {data.message.istable ? <Badge variant={'default'} style={{ backgroundColor: '#3182CE' }} className='mr-1'>Child Table</Badge> : null} {data.message.issingle ? <Badge variant={'default'} style={{ backgroundColor: '#38A169' }} className='mr-1'>Single</Badge> : null} </div> <div className="sm:px-0 sm:pt-2 pb-2"> <dl className="space-y-4 px-2 sm:space-y-4 sm:px-2 items-start"> <div className='space-y-2'> <div> <dt className="text-sm font-medium text-gray-500">Created on: {convertFrappeTimestampToReadableDate(data.message.creation)}</dt> </div> <div> <dt className="text-sm font-medium text-gray-500">Last Modified: {convertFrappeTimestampToReadableDate(data.message.modified)}</dt> </div> </div> </dl> </div> </div> </div> <div className="px-2 sm:px-2"> <Tabs defaultValue="fields" className="w-full"> <TabsList className='w-full justify-start'> <TabsTrigger value="fields">Fields</TabsTrigger> <TabsTrigger value="permissions">Permissions</TabsTrigger> <TabsTrigger value="links">Link</TabsTrigger> </TabsList> <TabsContent value="fields"><FieldsTable data={data.message.fields ?? [] as DocField[]} /></TabsContent> <TabsContent value="permissions"><PermissionsTable permissions={data.message.permissions ?? [] as DocPerm[]} /> </TabsContent> <TabsContent value="links"><LinkTable links={data.message.links ?? [] as DocTypeLink[]} /></TabsContent> </Tabs> </div> </div>} </div> ) }
2302_79757062/commit
dashboard/src/pages/features/TableDrawer/TableDrawer.tsx
TSX
agpl-3.0
6,367
import { APIDetails } from "@/components/features/api_viewer/APIDetails" import { APIList } from "@/components/features/api_viewer/APIList" import { useState } from "react" import { useFrappeGetCall } from "frappe-react-sdk" import { APIData } from "@/types/APIData" import { useParams } from "react-router-dom" import { Header } from "@/components/common/Header" import { FullPageLoader } from "@/components/common/FullPageLoader/FullPageLoader" import { ErrorBanner } from "@/components/common/ErrorBanner/ErrorBanner" interface GetAPIResponse { apis: APIData[] app_name: string branch_name: string organization_name: string, organization_id: string, app_logo?: string, org_logo?: string, last_updated: string, project_branch: string, } export const APIViewerContainer = () => { const { ID } = useParams() if (ID) { return <APIViewer projectBranch={ID} /> } return null } export const APIViewer = ({ projectBranch }: { projectBranch: string }) => { const [selectedendpoint, setSelectedEndpoint] = useState<string>('') const { data, isLoading, error } = useFrappeGetCall<{ message: GetAPIResponse }>('commit.api.api_explorer.get_apis_for_project', { project_branch: projectBranch }, undefined, { revalidateOnFocus: false, revalidateIfStale: false, onSuccess: (d: { message: GetAPIResponse }) => setSelectedEndpoint(d.message.apis[0].name) }) if (isLoading) { return <FullPageLoader /> } return ( // show API details column only if there is selected endpoint else show only API list in full width. <div className="overflow-hidden"> <Header text="API Explorer" /> {error && <ErrorBanner error={error} />} {data && <div className="flex w-full h-[calc(100vh-4rem)]"> <div className={selectedendpoint ? "w-full sm:w-[55%]" : "w-full"}> <APIList apiList={data?.message.apis ?? []} app_name={data?.message.app_name ?? ''} branch_name={data?.message.branch_name ?? ''} setSelectedEndpoint={setSelectedEndpoint} selectedEndpoint={selectedendpoint} /> </div> {selectedendpoint && ( <div className={`fixed z-10 right-0 w-[80vw] h-full bg-white shadow-lg transition-transform transform ${selectedendpoint ? 'translate-x-0' : 'translate-x-full' } md:relative md:translate-x-0 sm:w-[45%]`} > <APIDetails project_branch={projectBranch} endpointData={data?.message.apis ?? []} selectedEndpoint={selectedendpoint} setSelectedEndpoint={setSelectedEndpoint} viewerType="project" /> </div> )} </div>} </div> ) }
2302_79757062/commit
dashboard/src/pages/features/api_viewer/APIViewer.tsx
TSX
agpl-3.0
3,129
import { ErrorBanner } from "@/components/common/ErrorBanner/ErrorBanner" import { FullPageLoader } from "@/components/common/FullPageLoader/FullPageLoader" import { Header } from "@/components/common/Header" import { APIDetails } from "@/components/features/api_viewer/APIDetails" import { APIList } from "@/components/features/api_viewer/APIList" import { APIData } from "@/types/APIData" import { useFrappeGetCall } from "frappe-react-sdk" import { useState } from "react" import { useParams } from "react-router-dom" interface GetAPIResponse { apis: APIData[] app_name: string branch_name: string } export const AppAPIViewerContainer = () => { const { ID } = useParams() if (ID) { return <AppAPIViewer appName={ID} /> } return null } export const AppAPIViewer = ({ appName }: { appName: string }) => { const [selectedendpoint, setSelectedEndpoint] = useState<string>('') const { data, isLoading, error } = useFrappeGetCall<{ message: GetAPIResponse }>('commit.api.meta_data.get_apis_for_app', { app_name: appName }, undefined, { revalidateIfStale: false, revalidateOnFocus: false, onSuccess: (d: { message: GetAPIResponse }) => setSelectedEndpoint(d.message.apis?.[0]?.name) }) if (isLoading) { return <FullPageLoader /> } return ( // show API details column only if there is selected endpoint else show only API list in full width. <div className="overflow-hidden"> <Header text="API Explorer" /> {error && <ErrorBanner error={error} />} {data && <div className="flex w-full h-[calc(100vh-4rem)]"> <div className={selectedendpoint ? "w-full sm:w-[55%]" : "w-full"}> <APIList apiList={data?.message.apis ?? []} app_name={data?.message.app_name ?? ''} branch_name={data?.message.branch_name ?? ''} setSelectedEndpoint={setSelectedEndpoint} selectedEndpoint={selectedendpoint} /> </div> {selectedendpoint && ( <div className={`fixed z-10 right-0 w-[80vw] h-full bg-white shadow-lg transition-transform transform ${selectedendpoint ? 'translate-x-0' : 'translate-x-full' } md:relative md:translate-x-0 sm:w-[45%]`} > <APIDetails project_branch={appName} endpointData={data?.message.apis ?? []} selectedEndpoint={selectedendpoint} setSelectedEndpoint={setSelectedEndpoint} viewerType="app" /> </div> )} </div>} </div> ) }
2302_79757062/commit
dashboard/src/pages/features/api_viewer/AppAPIViewer.tsx
TSX
agpl-3.0
2,772
import { FullPageLoader } from "@/components/common/FullPageLoader/FullPageLoader" import { PostgresRelationship, PostgresTable } from "@/types/Table" import { useFrappePostCall } from "frappe-react-sdk" import { Graph } from "./Graph" import { useEffect, useState } from "react" import { ErrorBanner } from "@/components/common/ErrorBanner/ErrorBanner" export interface SchemaData { tables: PostgresTable[] relationships: PostgresRelationship[] } export interface Props { project_branch: string[] doctypes: { doctype: string, project_branch: string }[] setDocTypes: React.Dispatch<React.SetStateAction<{ doctype: string, project_branch: string }[]>> flowRef: React.MutableRefObject<null> } export const ERDForDoctypes = ({ project_branch, doctypes, setDocTypes, flowRef }: Props) => { const [data, setData] = useState<SchemaData | null>(null) const { call, error, loading } = useFrappePostCall<{ message: SchemaData }>('commit.api.erd_viewer.get_erd_schema_for_doctypes') useEffect(() => { call({ project_branch: project_branch, doctypes: JSON.stringify(doctypes) }).then(res => { setData(res.message) }).catch(err => { throw err }) }, [project_branch, doctypes, call]) if (loading) { return <FullPageLoader /> } if (error) { return <div><ErrorBanner error={error} /></div> } if (data) { return <Graph tables={data.tables} relationships={data.relationships} project_branch={project_branch} setDoctypes={setDocTypes} doctypes={doctypes} flowRef={flowRef} /> } return null }
2302_79757062/commit
dashboard/src/pages/features/erd/ERDForDoctypes.tsx
TSX
agpl-3.0
1,653
import { FullPageLoader } from "@/components/common/FullPageLoader/FullPageLoader" import { Button } from "@/components/ui/button" import { Checkbox } from "@/components/ui/checkbox" import { AppModuleData } from "@/types/CommitProjectBranch" import { Dialog, Transition } from "@headlessui/react" import { XMarkIcon } from "@heroicons/react/20/solid" import { useFrappeGetCall } from "frappe-react-sdk" import { Fragment, useEffect, useMemo, useRef, useState } from "react" import { useLocation } from "react-router-dom" import { Header } from "@/components/common/Header" import { Input } from "@/components/ui/input" import { ErrorBanner } from "@/components/common/ErrorBanner/ErrorBanner" import { ERDForDoctypes } from "./ERDForDoctypes" import { Dialog as Dialog2 } from "@/components/ui/dialog" import { Popover, PopoverTrigger } from "@/components/ui/popover" import { DoctypeListPopover, ViewERDAppList } from "./meta/ERDDoctypeAndAppModal" import { BsDownload } from "react-icons/bs" import { toPng } from 'html-to-image' export const ERDViewer = () => { const [open, setOpen] = useState(true) const location = useLocation() const { apps } = location.state as { apps: string[] } const [selectedApps, setSelectedApps] = useState<string[]>(apps) const [erdDoctypes, setERDDocTypes] = useState<{ doctype: string, project_branch: string }[]>([]) useEffect(() => { const doctypes = JSON.parse(window.sessionStorage.getItem('ERDDoctypes') ?? '[]') const filteredDoctypes = doctypes.filter((d: { doctype: string, project_branch: string }) => selectedApps.includes(d.project_branch)) ?? [] setERDDocTypes(filteredDoctypes) if (filteredDoctypes.length) { setOpen(false) } }, []) const flowRef = useRef(null) return ( <div className="h-screen"> <Header text="ERD Viewer" /> <div className="border-r border-gray-200"> <div className="fixed bottom-4 flex flex-row gap-2 left-[50%] -translate-x-[50%] z-40" hidden={open}> <Button onClick={() => setOpen(!open)} className="w-max sm:w-max"> Select DocTypes ({erdDoctypes.length}) </Button> <Button variant={'outline'} onClick={() => { if (flowRef.current === null) return toPng(flowRef.current, { filter: node => !( node?.classList?.contains('react-flow__minimap') || node?.classList?.contains('react-flow__controls') ), }).then(dataUrl => { const a = document.createElement('a'); a.setAttribute('download', 'erd.png'); a.setAttribute('href', dataUrl); a.click(); }); }}> <div className="flex items-center gap-2"> <BsDownload /> Download </div> </Button> </div> {selectedApps && <ModuleDoctypeListDrawer open={open} setOpen={setOpen} apps={selectedApps} erdDoctypes={erdDoctypes} setERDDocTypes={setERDDocTypes} setSelectedApps={setSelectedApps} />} {/* fixed height container */} <div className="flex h-[93vh] overflow-hidden"> {/* <ListView list={apiList} setSelectedEndpoint={setSelectedEndpoint} /> */} {selectedApps && erdDoctypes && <ERDForDoctypes project_branch={selectedApps} doctypes={erdDoctypes} setDocTypes={setERDDocTypes} flowRef={flowRef} />} </div> </div> </div> ) } export interface ModuleDoctypeListDrawerProps { open: boolean setOpen: (open: boolean) => void apps: string[] setSelectedApps: React.Dispatch<React.SetStateAction<string[]>> erdDoctypes: { doctype: string, project_branch: string }[] setERDDocTypes: React.Dispatch<React.SetStateAction<{ doctype: string; project_branch: string; }[]>> } export const ModuleDoctypeListDrawer = ({ open, setOpen, apps, setSelectedApps, erdDoctypes, setERDDocTypes }: ModuleDoctypeListDrawerProps) => { const [doctype, setDocType] = useState<{ doctype: string project_branch: string }[]>(erdDoctypes) const onGenerateERD = () => { setERDDocTypes(doctype) window.sessionStorage.setItem('ERDDoctypes', JSON.stringify(doctype)) setOpen(false) } useEffect(() => { setDocType(erdDoctypes) }, [erdDoctypes]) const [openDialog, setOpenDialog] = useState(false) const dialogOnClose = () => { setOpenDialog(false) } return ( <> <Transition.Root show={open} as={Fragment}> <Dialog as="div" className="relative z-50" onClose={setOpen}> <div className="fixed inset-0" /> <div className="fixed inset-0 overflow-hidden"> <div className="absolute inset-0 overflow-hidden"> <div className="pointer-events-none fixed inset-y-0 left-0 pr-10 flex max-w-full"> <Transition.Child as={Fragment} enter="transform transition ease-in-out duration-500 sm:duration-700" enterFrom="translate-x-[-100%]" enterTo="translate-x-[0]" leave="transform transition ease-in-out duration-500 sm:duration-700" leaveFrom="translate-x-0" leaveTo="translate-x-[-100%]" > <Dialog.Panel className="pointer-events-auto w-[480px]"> <div className="flex h-full flex-col overflow-y-scroll bg-white pt-6 shadow-xl"> <div className="px-4 sm:px-6"> <div className="flex items-start justify-between"> <Dialog.Title className="flex space-x-2 "> <div className="text-base font-semibold leading-6 text-gray-900"> Select DocTypes </div> <Popover> {doctype.length ? <PopoverTrigger asChild> <Button variant={'outline'} className="h-6 px-2">{doctype.length} DocTypes</Button> </PopoverTrigger> : null} <DoctypeListPopover doctypes={doctype} setDoctypes={setDocType} /> </Popover> {apps.length ? <Button variant={'outline'} onClick={() => setOpenDialog(true)} className="h-6 px-2">{apps.length} Apps</Button> : null} </Dialog.Title> <div className="ml-3 flex h-7 items-center"> <button type="button" className="relative rounded-md bg-white text-gray-400 hover:text-gray-500 focus:outline-none " onClick={() => setOpen(false)} > <span className="absolute -inset-2.5" /> <span className="sr-only">Close panel</span> <XMarkIcon className="h-6 w-6" aria-hidden="true" /> </button> </div> </div> </div> <div className="relative mt-6 flex-1 px-4 sm:px-6"> <ModuleList apps={apps} doctype={doctype} setDocType={setDocType} /> </div> </div> <div className="sticky bottom-0 items-center justify-end p-4 flex w-full bg-white border-t"> <Button onClick={onGenerateERD} size="sm" className="bg-blue-500">Generate ERD</Button> </div> </Dialog.Panel> </Transition.Child> </div> </div> </div> </Dialog> </Transition.Root> <Dialog2 open={openDialog} onOpenChange={setOpenDialog}> <ViewERDAppList apps={apps} setApps={setSelectedApps} onClose={dialogOnClose} /> </Dialog2> </> ) } export interface DoctypesData { app_name: string, module_name: string, doctype_name: string } export const ModuleList = ({ apps, doctype, setDocType }: { apps: string[], doctype: { doctype: string, project_branch: string }[], setDocType: React.Dispatch<React.SetStateAction<{ doctype: string; project_branch: string; }[]>> }) => { const { data, error, isLoading } = useFrappeGetCall<{ message: AppModuleData }>('commit.commit.doctype.commit_project_branch.commit_project_branch.get_module_doctype_map_for_branches', { branches: JSON.stringify(apps) }) const [filter, setFilter] = useState<string>("") const filterDoctypes = useMemo(() => { const apps_module_data = data?.message ?? {} const allDoctypes: DoctypesData[] = [] Object.keys(apps_module_data).forEach((app_name) => { Object.keys(apps_module_data[app_name]).forEach((module_name) => { const moduleData = apps_module_data[app_name][module_name] const doctypeNames: string[] = moduleData?.doctype_names ?? [] doctypeNames.forEach((doctype_name) => { allDoctypes.push({ app_name, module_name, doctype_name }) }) }) }) const filterDoctypes = allDoctypes.filter((d) => d.doctype_name.toLowerCase().includes(filter.toLowerCase()) || d.module_name.toLowerCase().includes(filter.toLowerCase()) ) const uniqueDoctypes = filterDoctypes.filter((v, i, a) => a.findIndex(t => (t.doctype_name === v.doctype_name)) === i) return uniqueDoctypes }, [data, filter]) if (error) { return <ErrorBanner error={error} /> } if (isLoading) { return <FullPageLoader className="w-[240px]" /> } if (data) { return ( <div> <Input placeholder="Filter DocType..." value={filter} onChange={(event) => setFilter(event.target.value)} className="w-full" /> <div> <ul role="list" className="divide-y divide-gray-200"> { filterDoctypes.map((doctypeName: DoctypesData) => { return ( <li className="py-3 flex justify-between items-center pl-4" key={doctypeName.doctype_name}> <label htmlFor={doctypeName.doctype_name} className="text-sm font-normal" >{doctypeName.doctype_name}</label> <div className="min-h-[24px] flex flex-row gap-2"> {/* add graytext instead of badge */} <span className="text-gray-500 text-xs">{doctypeName.module_name}</span> <Checkbox id={doctypeName.doctype_name} checked={doctype.some(d => d.doctype === doctypeName.doctype_name)} onCheckedChange={(checked) => { if (checked) { setDocType([...new Set([...doctype, { doctype: doctypeName.doctype_name, project_branch: doctypeName.app_name }])]) } else { setDocType(doctype.filter((d) => d.doctype !== doctypeName.doctype_name)) } }}> {doctypeName.doctype_name} </Checkbox> </div> </li> ) }) } </ul> </div> </div> ) } return null }
2302_79757062/commit
dashboard/src/pages/features/erd/ERDViewer.tsx
TSX
agpl-3.0
13,773
import dagre from '@dagrejs/dagre' import { FC, useCallback, useEffect, useMemo, useState } from 'react' import '../../../styles/flow.css' import ReactFlow, { Background, Controls, Edge, Node, Position, ReactFlowProvider, useReactFlow, MarkerType, ControlButton, getConnectedEdges, useStoreApi, useEdgesState, useNodesState } from 'reactflow' import 'reactflow/dist/style.css' import { PostgresTable, PostgresRelationship, TableNodeData } from '@/types/Table' import { CgMaximizeAlt } from 'react-icons/cg' import { TbArrowsMinimize } from 'react-icons/tb' import { TableNode } from './TableNode' import { TableDrawer } from '../TableDrawer/TableDrawer' // ReactFlow is scaling everything by the factor of 2 export const NODE_WIDTH = 320 export const NODE_ROW_HEIGHT = 40 export const Graph = ({ tables, relationships, project_branch, setDoctypes, doctypes, flowRef }: { tables: PostgresTable[] relationships: PostgresRelationship[] project_branch: string[] setDoctypes: React.Dispatch<React.SetStateAction<{ doctype: string; project_branch: string; }[]>> doctypes: { doctype: string; project_branch: string; }[] flowRef: React.MutableRefObject<null> }) => { return ( <ReactFlowProvider> <TablesGraph tables={tables} relationships={relationships} project_branch={project_branch} setDoctypes={setDoctypes} doctypes={doctypes} flowRef={flowRef} /> </ReactFlowProvider> ) } function getGraphDataFromTables(tables: PostgresTable[], relationships: PostgresRelationship[]): { nodes: Node<TableNodeData>[] edges: Edge[] } { if (!tables.length) { return { nodes: [], edges: [] } } const nodes = tables.map((table) => { const columns = (table.columns || []).map((column) => { return { id: column.id, name: column.name, format: column.format, is_custom_field: column.is_custom_field, } }) return { id: `${table.id}`, type: 'table', data: { name: table.name, isForeign: false, istable: table.istable, columns, }, position: { x: 0, y: 0 }, } }) const edges: Edge[] = [] const uniqueRelationships: PostgresRelationship[] = relationships for (const rel of uniqueRelationships) { const [source, sourceHandle] = findTablesHandleIds( tables, rel.source_table_name, rel.source_column_name ) const [target, targetHandle] = findTablesHandleIds( tables, rel.target_table_name, rel.target_column_name ) // We do not support [external->this] flow currently. if (source && target) { edges.push({ id: String(rel.id), source, sourceHandle, target, targetHandle, animated: true, }) } } return getLayoutedElements(nodes, edges) } function findTablesHandleIds( tables: PostgresTable[], table_name: string, column_name: string ): [string?, string?] { for (const table of tables) { if (table_name !== table.id) continue for (const column of table.columns || []) { if (column_name !== column.id) continue return [String(table.id), column.id] } } return [] } const getLayoutedElements = (nodes: Node<TableNodeData>[], edges: Edge[]) => { const dagreGraph = new dagre.graphlib.Graph() dagreGraph.setDefaultEdgeLabel(() => ({})) dagreGraph.setGraph({ rankdir: 'TB', align: 'UL', nodesep: 80, ranksep: 80, }) nodes.forEach((node) => { dagreGraph.setNode(node.id, { width: NODE_WIDTH / 2, height: (NODE_ROW_HEIGHT / 2) * (node.data.columns.length + 1), // columns + header }) }) edges.forEach((edge) => { dagreGraph.setEdge(edge.source, edge.target) }) dagre.layout(dagreGraph) nodes.forEach((node) => { const nodeWithPosition = dagreGraph.node(node.id) node.targetPosition = Position.Left node.sourcePosition = Position.Right // We are shifting the dagre node position (anchor=center center) to the top left // so it matches the React Flow node anchor point (top left). node.position = { x: nodeWithPosition.x - nodeWithPosition.width / 2, y: nodeWithPosition.y - nodeWithPosition.height / 2, } return node }) return { nodes, edges } } const TablesGraph: FC<{ tables: PostgresTable[], relationships: PostgresRelationship[], project_branch: string[], setDoctypes: React.Dispatch<React.SetStateAction< { doctype: string; project_branch: string; }[] >> doctypes: { doctype: string; project_branch: string; }[] flowRef: React.MutableRefObject<null> }> = ({ tables, relationships, setDoctypes, doctypes, flowRef }) => { const [nodes, setNodes, onNodesChange] = useNodesState([]); const [edges, setEdges, onEdgesChange] = useEdgesState([]); const [fullscreenOn, setFullScreen] = useState(false); // const [nodeHoverActive, setNodeHoverActive] = useState(true); const reactFlowInstance = useReactFlow() const nodeTypes = useMemo( () => ({ table: TableNode, }), [] ) const toggleFullScreen = () => { if (fullscreenOn) { document.exitFullscreen().then(function () { setFullScreen(false) }) .catch(function (error) { alert("Can't exit fullscreen") console.error(error) }); } else { const element = document.querySelector("body"); // make the element go to full-screen mode element && element.requestFullscreen() .then(function () { setFullScreen(true) }) .catch(function (error) { alert("Can't turn on fullscreen") console.error(error) }); } } const store = useStoreApi(); const onNodeMouseEnter = useCallback( (_: any, node: Node) => { const state = store.getState(); state.resetSelectedElements(); state.addSelectedNodes([node.id]); const connectedEdges = getConnectedEdges([node], edges); setEdges(eds => { return eds.map((ed) => { if (connectedEdges.find(e => e.id === ed.id)) { ed.animated = false ed.style = { ...ed.style, stroke: '#042f2e', } // setHighlightEdgeClassName(ed); } return ed; }); }); }, [edges, setEdges, store] ); const onNodeMouseLeave = useCallback( (_: any, node: Node) => { const state = store.getState(); state.resetSelectedElements(); state.addSelectedNodes([node.id]); const connectedEdges = getConnectedEdges([node], edges); setEdges(eds => { return eds.map((ed) => { if (connectedEdges.find(e => e.id === ed.id)) { ed.animated = true ed.style = { ...ed.style, stroke: '#0ea5e9', } } return ed; }); }); }, [edges, setEdges, store] ); const [selectedDoctype, setSelectedDoctype] = useState<string | null>(null); const onNodeClick = useCallback((_: any, node: Node<{ name: string }>) => { setSelectedDoctype(node.data?.name) }, [] ); const onNodesDelete = useCallback( (nodesToDelete: Node[]) => { const nodes = nodesToDelete.map((node) => node.id); setNodes((ns) => ns.filter((n) => !nodes.includes(n.id))); setEdges((es) => es.filter((e) => { return ( !nodes.includes(e.source) && !nodes.includes(e.target) ); }) ); setDoctypes((doctypes) => { const doc = doctypes.filter((doctype) => { return !nodes.includes(doctype.doctype); }) window.sessionStorage.setItem('ERDDoctypes', JSON.stringify(doc)) return doc }) }, [setNodes, setEdges, setDoctypes] ); useEffect(() => { const { nodes, edges } = getGraphDataFromTables(tables, relationships) setNodes(nodes) setEdges(edges) setTimeout(() => reactFlowInstance.fitView({})) // it needs to happen during next event tick }, [tables, relationships, setNodes, setEdges, reactFlowInstance]) return ( <> <div className='Flow' style={{ width: '100vw', height: 'auto', padding: 2 }}> {/* <Markers /> */} <ReactFlow style={{ backgroundColor: '#F7FAFC', }} ref={flowRef} nodes={nodes} edges={edges} onNodesChange={onNodesChange} onEdgesChange={onEdgesChange} onNodeClick={onNodeClick} onNodesDelete={onNodesDelete} defaultNodes={[]} defaultEdges={[]} onNodeMouseEnter={onNodeMouseEnter} onNodeMouseLeave={onNodeMouseLeave} snapToGrid={true} snapGrid={[16, 16]} maxZoom={10} defaultEdgeOptions={{ type: 'smoothstep', markerEnd: MarkerType.ArrowClosed, deletable: false, style: { stroke: '#0ea5e9', }, }} nodeTypes={nodeTypes} fitView proOptions={{ hideAttribution: true, }} > <Controls showFitView={false}> <ControlButton onClick={toggleFullScreen}> {!fullscreenOn && <CgMaximizeAlt />} {fullscreenOn && <TbArrowsMinimize />} </ControlButton> </Controls> <div className="absolute top-0 right-0 p-2 pr-16 m-1 bg-white z-10 flex flex-col gap-2 rounded-lg shadow-lg"> <div className="flex items-center gap-2"> <div className="h-4 w-4 bg-blue-500 rounded-full border border-blue-600" /> <div className="text-xs">Table</div> </div> <div className="flex items-center gap-2"> <div className="h-4 w-4 bg-teal-500 rounded-full border border-teal-600" /> <div className="text-xs">Child Table</div> </div> <div className="flex items-center gap-2"> <div className="h-4 w-4 bg-yellow-50 rounded-full border border-yellow-600" /> <div className="text-xs">Custom Field</div> </div> </div> <Background color="#171923" gap={16} /> </ReactFlow> <TableDrawer isOpen={!!selectedDoctype} onClose={() => setSelectedDoctype(null)} doctype={selectedDoctype ?? ''} project_branch={doctypes.find(d => d.doctype === selectedDoctype)?.project_branch} key={selectedDoctype} /> </div> </> ) }
2302_79757062/commit
dashboard/src/pages/features/erd/Graph.tsx
TSX
agpl-3.0
12,457
export function Markers() { return ( <svg style={{ position: "absolute", top: 0, left: 0 }}> <defs> <marker id="hasMany" viewBox="0 0 10 13" markerHeight="10" markerWidth="13" refX="10" refY="6.5" fill="none"> <path d="M10 12C2.57803 12 0.909955 8.66667 1.00367 7" stroke="#B1B1B6" /> <path d="M10 1C2.57803 1 0.909955 5 1.00367 7" stroke="#B1B1B6" /> </marker> </defs> <defs> <marker id="hasManySelected" viewBox="0 0 10 13" markerHeight="10" markerWidth="13" refX="10" refY="6.5" fill="none"> <path d="M10 12C2.57803 12 0.909955 8.66667 1.00367 7" stroke="#2186EB" /> <path d="M10 1C2.57803 1 0.909955 5 1.00367 7" stroke="#2186EB" /> </marker> </defs> <defs> <marker id="hasManyReversed" viewBox="0 0 10 13" markerHeight="10" markerWidth="13" refX="10" refY="6.5" fill="none" orient="auto-start-reverse"> <path d="M10 12C2.57803 12 0.909955 8.66667 1.00367 7" stroke="#B1B1B6" /> <path d="M10 1C2.57803 1 0.909955 5 1.00367 7" stroke="#B1B1B6" /> </marker> </defs> <defs> <marker id="hasManyReversedSelected" viewBox="0 0 10 13" markerHeight="10" markerWidth="13" refX="10" refY="6.5" fill="none" orient="auto-start-reverse"> <path d="M10 12C2.57803 12 0.909955 8.66667 1.00367 7" stroke="#2186EB" /> <path d="M10 1C2.57803 1 0.909955 5 1.00367 7" stroke="#2186EB" /> </marker> </defs> <defs> <marker id="hasManyHighlighted" viewBox="0 0 10 13" markerHeight="10" markerWidth="13" refX="10" refY="6.5" fill="none"> <path d="M10 12C2.57803 12 0.909955 8.66667 1.00367 7" stroke="#2186EB" /> <path d="M10 1C2.57803 1 0.909955 5 1.00367 7" stroke="#2186EB" /> </marker> </defs> <defs> <marker id="hasManyReversedHighlighted" viewBox="0 0 10 13" markerHeight="10" markerWidth="13" refX="10" refY="6.5" fill="none" orient="auto-start-reverse"> <path d="M10 12C2.57803 12 0.909955 8.66667 1.00367 7" stroke="#2186EB" /> <path d="M10 1C2.57803 1 0.909955 5 1.00367 7" stroke="#2186EB" /> </marker> </defs> <defs> <marker id="hasOne" viewBox="0 0 6 6" markerHeight="6" markerWidth="6" refX="6" refY="3" fill="none"> <circle cx="3" cy="3" r="3" fill="#B1B1B6" /> </marker> </defs> <defs> <marker id="hasOneSelected" viewBox="0 0 6 6" markerHeight="6" markerWidth="6" refX="6" refY="3" fill="none"> <circle cx="3" cy="3" r="3" fill="#2186EB" /> </marker> </defs> <defs> <marker id="hasOneReversed" viewBox="0 0 6 6" markerHeight="6" markerWidth="6" refX="6" refY="3" fill="none" orient="auto-start-reverse"> <circle cx="3" cy="3" r="3" fill="#B1B1B6" /> </marker> </defs> <defs> <marker id="hasOneReversedSelected" viewBox="0 0 6 6" markerHeight="6" markerWidth="6" refX="6" refY="3" fill="none" orient="auto-start-reverse"> <circle cx="3" cy="3" r="3" fill="#2186EB" /> </marker> </defs> <defs> <marker id="hasOneHighlighted" viewBox="0 0 6 6" markerHeight="6" markerWidth="6" refX="6" refY="3" fill="none"> <circle cx="3" cy="3" r="3" fill="#2186EB" /> </marker> </defs> <defs> <marker id="hasOneReversedHighlighted" viewBox="0 0 6 6" markerHeight="6" markerWidth="6" refX="6" refY="3" fill="none" orient="auto-start-reverse"> <circle cx="3" cy="3" r="3" fill="#2186EB" /> </marker> </defs> </svg> ); }
2302_79757062/commit
dashboard/src/pages/features/erd/Markers.tsx
TSX
agpl-3.0
3,625
import { ICON_KEY, ICON_KEY_MAP } from "@/components/common/Icons"; import { PostgresColumn } from "@/types/Table"; import { Arrow, HoverCardContent } from "@radix-ui/react-hover-card"; // import { AiOutlineLink } from "react-icons/ai"; export const TableHoverCard = ({ column }: { column: PostgresColumn }) => { const IconComponent = ICON_KEY_MAP[column.format as ICON_KEY] return ( <HoverCardContent className="w-auto bg-white z-10 border border-gray-200 p-2" side='right'> <Arrow className="color-gray-200" /> <div className="flex space-x-2 items-center"> {/* <div className="flex gap-x-1 items-center"> */} {/* <img className="h-12 w-12 flex-none rounded-full bg-gray-50" src={column.imageUrl} alt="" /> */} <div className="h-8 w-8 flex-none rounded-full border border-gray-200 flex items-center justify-center"> <IconComponent className="h-4 w-4" /> </div> <div className="flex-auto "> <p className="text-xs font-semibold leading-3 text-gray-900">{column.name}</p> <p className="mt-1 truncate text-xs leading-3 text-gray-500">{column.id}</p> </div> {/* </div> */} </div> </HoverCardContent> ) }
2302_79757062/commit
dashboard/src/pages/features/erd/TableHoverCard.tsx
TSX
agpl-3.0
1,339
import { PostgresTable } from "@/types/Table"; import { NodeProps, Handle, useReactFlow } from "reactflow"; import { NODE_WIDTH } from "./Graph"; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"; import { XMarkIcon } from '@heroicons/react/24/outline' import { cn } from "@/lib/utils"; export const TableNode = ({ data, targetPosition, sourcePosition }: NodeProps<PostgresTable>) => { const hiddenNodeConnector = '!h-px !w-px !min-w-0 !min-h-0 !cursor-grab !border-0 !opacity-0' const { getNode, deleteElements } = useReactFlow(); const onDelete = () => { const nodeToDelete = getNode(data.name) if (nodeToDelete) { deleteElements({ nodes: [nodeToDelete], } ) } } return ( <TooltipProvider> <Tooltip> <TooltipTrigger asChild> <div className={`w-[${NODE_WIDTH / 2}px ] rounded-lg overflow-hidden bg-white shadow-sm`}> {data.istable ? <header className="text-[0.5rem] leading-7 px-2 font-bold text-center bg-teal-500 text-white"> {data.name} </header> : <header className="text-[0.5rem] leading-7 px-2 font-bold text-center bg-blue-500 text-white"> {data.name} </header>} {data.columns.map((column) => ( <div className={`text-[8px] leading-5 relative flex justify-between odd:bg-scale-300 even:bg-scale-400 border-slate-100 border ${cn(column.is_custom_field ? 'bg-yellow-50' : '')}`} key={column.id} > <span className={`${column.id === "name" ? `border-l-2 ${data.istable ? 'border-l-teal-500' : 'border-l-blue-500'} pl-[6px] pr-2` : 'px-2' } text-ellipsis overflow-hidden whitespace-nowrap`} > {column.name} </span> <span className="px-2">{column.format}</span> {targetPosition && ( <Handle type="target" id={column.id} position={targetPosition} className={`${hiddenNodeConnector} !left-0`} /> )} {sourcePosition && ( <Handle type="source" id={column.id} position={sourcePosition} className={`${hiddenNodeConnector} !right-0`} /> )} </div> ))} </div> </TooltipTrigger> <TooltipContent align="start" side="right" sideOffset={0.5} className="p-0 rounded-full bg-white border border-black shadow-sm"> <XMarkIcon className="h-2 w-2 m-1 text-black" aria-hidden="true" onClick={onDelete} /> </TooltipContent> </Tooltip> </TooltipProvider> ) }
2302_79757062/commit
dashboard/src/pages/features/erd/TableNode.tsx
TSX
agpl-3.0
3,651
import { Header } from "@/components/common/Header" import { Button } from "@/components/ui/button" import { Dialog, Transition } from "@headlessui/react" import { Fragment, useEffect, useRef, useState } from "react" import { XMarkIcon } from "@heroicons/react/20/solid" import { ErrorBanner } from "@/components/common/ErrorBanner/ErrorBanner" import { FullPageLoader } from "@/components/common/FullPageLoader/FullPageLoader" import { Input } from "@/components/ui/input" import { useFrappeGetDocList } from "frappe-react-sdk" import { DocType } from "@/types/Core/DocType" import { Checkbox } from "@/components/ui/checkbox" import { useDebounce } from "@/hooks/useDebounce" import { ERDForMetaDoctypes } from "./ERDForMetaDoctype" import { Popover, PopoverTrigger } from "@/components/ui/popover" import { DoctypeListPopoverForMeta } from "./ERDDoctypeAndAppModal" import { BsDownload } from "react-icons/bs" import { toPng } from 'html-to-image' export const CreateERD = () => { const [open, setOpen] = useState(true) const [erdDoctypes, setERDDocTypes] = useState<string[]>([]) useEffect(() => { const doctypes = JSON.parse(window.sessionStorage.getItem('ERDMetaDoctypes') ?? '[]') if (doctypes.length) { setERDDocTypes(doctypes) setOpen(false) } }, []) const flowRef = useRef(null) return ( <div className="h-screen"> <Header text="ERD Viewer" /> <div className="border-r border-gray-200"> <div className="fixed bottom-4 flex flex-row gap-2 left-[50%] -translate-x-[50%] z-40" hidden={open}> <Button onClick={() => setOpen(!open)} className="w-max sm:w-max"> Select DocTypes ({erdDoctypes.length}) </Button> <Button variant={'outline'} onClick={() => { if (flowRef.current === null) return toPng(flowRef.current, { filter: node => !( node?.classList?.contains('react-flow__minimap') || node?.classList?.contains('react-flow__controls') ), }).then(dataUrl => { const a = document.createElement('a'); a.setAttribute('download', 'erd.png'); a.setAttribute('href', dataUrl); a.click(); }); }}> <div className="flex items-center gap-2"> <BsDownload /> Download </div> </Button> </div> <ModuleDoctypeListDrawer open={open} setOpen={setOpen} erdDoctypes={erdDoctypes} setERDDocTypes={setERDDocTypes} /> {/* fixed height container */} <div className="flex h-[93vh]"> {erdDoctypes && <ERDForMetaDoctypes doctypes={erdDoctypes} setDocTypes={setERDDocTypes} flowRef={flowRef} />} </div> </div> </div> ) } export interface ModuleDoctypeListDrawerProps { open: boolean setOpen: (open: boolean) => void erdDoctypes: string[] setERDDocTypes: React.Dispatch<React.SetStateAction<string[]>> } export const ModuleDoctypeListDrawer = ({ open, setOpen, erdDoctypes, setERDDocTypes }: ModuleDoctypeListDrawerProps) => { const [doctype, setDocType] = useState<string[]>(erdDoctypes) const onGenerateERD = () => { setERDDocTypes(doctype) window.sessionStorage.setItem('ERDMetaDoctypes', JSON.stringify(doctype)) setOpen(false) } useEffect(() => { setDocType(erdDoctypes) }, [erdDoctypes]) return ( <Transition.Root show={open} as={Fragment}> <Dialog as="div" className="relative z-50" onClose={setOpen}> <div className="fixed inset-0" /> <div className="fixed inset-0 overflow-hidden"> <div className="absolute inset-0 overflow-hidden"> <div className="pointer-events-none fixed inset-y-0 left-0 pr-10 flex max-w-full"> <Transition.Child as={Fragment} enter="transform transition ease-in-out duration-500 sm:duration-700" enterFrom="translate-x-[-100%]" enterTo="translate-x-[0]" leave="transform transition ease-in-out duration-500 sm:duration-700" leaveFrom="translate-x-0" leaveTo="translate-x-[-100%]" > <Dialog.Panel className="pointer-events-auto w-[480px]"> <div className="flex h-full flex-col overflow-y-scroll bg-white pt-6 shadow-xl"> <div className="px-4 sm:px-6"> <div className="flex items-start justify-between"> <Dialog.Title className="flex space-x-2 "> <div className="text-base font-semibold leading-6 text-gray-900"> Select DocTypes </div> <Popover> {doctype.length ? <PopoverTrigger asChild> <Button variant={'outline'} className="h-6 px-2">{doctype.length} DocTypes</Button> </PopoverTrigger> : null} <DoctypeListPopoverForMeta doctypes={doctype} setDoctypes={setDocType} /> </Popover> </Dialog.Title> <div className="ml-3 flex h-7 items-center"> <button type="button" className="relative rounded-md bg-white text-gray-400 hover:text-gray-500 focus:outline-none " onClick={() => setOpen(false)} > <span className="absolute -inset-2.5" /> <span className="sr-only">Close panel</span> <XMarkIcon className="h-6 w-6" aria-hidden="true" /> </button> </div> </div> </div> <div className="relative mt-6 flex-1 px-4 sm:px-6"> <ModuleList doctype={doctype} setDocType={setDocType} /> </div> </div> <div className="sticky bottom-0 items-center justify-end p-4 flex w-full bg-white border-t"> <Button onClick={onGenerateERD} size="sm" className="bg-blue-500">Generate ERD</Button> </div> </Dialog.Panel> </Transition.Child> </div> </div> </div> </Dialog> </Transition.Root> ) } export interface DoctypesData { module_name: string, doctype_name: string } export const ModuleList = ({ doctype, setDocType }: { doctype: string[], setDocType: React.Dispatch<React.SetStateAction<string[]>> }) => { const [filter, setFilter] = useState<string>("") const debouncedInput = useDebounce(filter, 500) const { data, error, isLoading } = useFrappeGetDocList<DocType>('DocType', { fields: ['name', 'module'], orFilters: [['module', 'like', `%${debouncedInput}%`], ['name', 'like', `%${debouncedInput}%`]], limit: 100 }) if (error) { return <ErrorBanner error={error} /> } if (isLoading) { return <FullPageLoader className="w-[240px]" /> } if (data) { return ( <div> <Input placeholder="Filter DocType..." value={filter} onChange={(event) => setFilter(event.target.value)} className="w-full" autoFocus /> <div> <ul role="list" className="divide-y divide-gray-200"> { data?.map((doc: DocType) => { return ( <li className="py-3 flex justify-between items-center pl-4" key={doc.name}> <label htmlFor={doc.name} className="text-sm font-normal" >{doc.name}</label> <div className="min-h-[24px] flex flex-row gap-2"> <span className="text-gray-500 text-xs">{doc.module}</span> <Checkbox id={doc.name} checked={doctype.some(d => d === doc.name)} onCheckedChange={(checked) => { if (checked) { setDocType([...new Set([...doctype, doc.name])]) } else { setDocType(doctype.filter((d) => d !== doc.name)) } }}> {doc.name} </Checkbox> </div> </li> ) }) } </ul> </div> </div> ) } return null }
2302_79757062/commit
dashboard/src/pages/features/erd/meta/CreateERDForMeta.tsx
TSX
agpl-3.0
10,704
import { ErrorBanner } from "@/components/common/ErrorBanner/ErrorBanner"; import { FullPageLoader } from "@/components/common/FullPageLoader/FullPageLoader"; import { ProjectData } from "@/components/features/projects/Projects"; import { ViewERDProjectCard } from "@/components/features/projects/ViewERDAppDialog"; import { Button } from "@/components/ui/button"; import { DialogHeader, DialogFooter, DialogContent, DialogTitle, DialogDescription } from "@/components/ui/dialog"; import { PopoverContent } from "@/components/ui/popover"; import { useFrappeGetCall } from "frappe-react-sdk"; import { useState } from "react"; export interface DoctypeListPopoverProps { doctypes: { doctype: string; project_branch: string; }[]; setDoctypes: React.Dispatch<React.SetStateAction<{ doctype: string; project_branch: string; }[]>> } export const DoctypeListPopover = ({ doctypes, setDoctypes }: DoctypeListPopoverProps) => { return ( <PopoverContent className="w-[350px] p-4 bg-white shadow-lg rounded-lg"> <div className="col-span-2 grid grid-cols-2 gap-2"> {doctypes.map((doctype) => ( <span className="inline-flex justify-between items-center gap-x-0.5 rounded-md bg-gray-100 px-2 py-1 text-xs font-medium text-gray-600 ring-1 ring-inset ring-gray-500/10" key={doctype.doctype}> {doctype.doctype} <button className="group relative h-4 w-4 rounded-sm hover:bg-gray-500/20" onClick={() => setDoctypes(doctypes.filter((d) => d.doctype !== doctype.doctype))}> <span className="sr-only">Remove</span> <svg viewBox="0 0 14 14" className="h-4 w-4 stroke-gray-600/50 group-hover:stroke-gray-600/75"> <path d="M4 4l6 6m0-6l-6 6" /> </svg> <span className="absolute -inset-1" /> </button> </span> ))} </div> </PopoverContent > ) } export const DoctypeListPopoverForMeta = ({ doctypes, setDoctypes }: {doctypes: string[], setDoctypes: React.Dispatch<React.SetStateAction<string[]>>}) => { return ( <PopoverContent className="w-[350px] p-4 bg-white shadow-lg rounded-lg"> <div className="col-span-2 grid grid-cols-2 gap-2"> {doctypes.map((doctype:string) => ( <span className="inline-flex justify-between items-center gap-x-0.5 rounded-md bg-gray-100 px-2 py-1 text-xs font-medium text-gray-600 ring-1 ring-inset ring-gray-500/10" key={doctype}> {doctype} <button className="group relative h-4 w-4 rounded-sm hover:bg-gray-500/20" onClick={() => setDoctypes(doctypes.filter((d) => d !== doctype))}> <span className="sr-only">Remove</span> <svg viewBox="0 0 14 14" className="h-4 w-4 stroke-gray-600/50 group-hover:stroke-gray-600/75"> <path d="M4 4l6 6m0-6l-6 6" /> </svg> <span className="absolute -inset-1" /> </button> </span> ))} </div> </PopoverContent > ) } export const ViewERDAppList = ({ apps, setApps, onClose }: { apps: string[], setApps: React.Dispatch<React.SetStateAction<string[]>>, onClose: () => void }) => { const [selectApp, setSelectApp] = useState<string[]>(apps) const { data, error, isLoading } = useFrappeGetCall<{ message: ProjectData[] }>('commit.api.commit_project.commit_project.get_project_list_with_branches', {}, 'get_project_list_with_branches', { keepPreviousData: true, revalidateOnFocus: true, revalidateIfStale: false, }) const onViewERD = () => { setApps(selectApp) onClose() } return ( <DialogContent className="p-6 w-[90vw] sm:w-full overflow-hidden"> <DialogHeader className="text-left"> <DialogTitle>Select Apps</DialogTitle> <DialogDescription> Select the apps to view ERD </DialogDescription> </DialogHeader> {error && <ErrorBanner error={error} />} {isLoading && <FullPageLoader />} {data && data?.message && <ul role="list" className="divide-y divide-gray-200 max-h-[60vh] overflow-y-scroll"> {data?.message?.map((org: ProjectData) => { return org.projects.map((project => { return ( <ViewERDProjectCard project={project} key={project.name} setApps={setSelectApp} apps={selectApp} /> ) } )) })} </ul>} <DialogFooter> <Button onClick={onViewERD}>View ERD</Button> </DialogFooter> </DialogContent> ) }
2302_79757062/commit
dashboard/src/pages/features/erd/meta/ERDDoctypeAndAppModal.tsx
TSX
agpl-3.0
5,088
import { FullPageLoader } from "@/components/common/FullPageLoader/FullPageLoader" import { PostgresRelationship, PostgresTable } from "@/types/Table" import { useFrappePostCall } from "frappe-react-sdk" import { useEffect, useState } from "react" import { ErrorBanner } from "@/components/common/ErrorBanner/ErrorBanner" import { MetaGraph } from "./MetaGraph" export interface SchemaData { tables: PostgresTable[] relationships: PostgresRelationship[] } export interface Props { doctypes: string[] setDocTypes: React.Dispatch<React.SetStateAction<string[]>> flowRef: React.MutableRefObject<null> } export const ERDForMetaDoctypes = ({ doctypes, setDocTypes, flowRef }: Props) => { const [data, setData] = useState<SchemaData | null>(null) const { call, error, loading } = useFrappePostCall<{ message: SchemaData }>('commit.api.erd_viewer.get_meta_erd_schema_for_doctypes') useEffect(() => { call({ doctypes: doctypes }).then(res => { setData(res.message) }).catch(err => { throw err }) }, [doctypes, call]) if (loading) { return <FullPageLoader /> } if (error) { return <div><ErrorBanner error={error} /></div> } if (data) { return <MetaGraph tables={data.tables} relationships={data.relationships} setDoctypes={setDocTypes} doctypes={doctypes} flowRef={flowRef} /> } return null }
2302_79757062/commit
dashboard/src/pages/features/erd/meta/ERDForMetaDoctype.tsx
TSX
agpl-3.0
1,447
import dagre from '@dagrejs/dagre' import { FC, useCallback, useEffect, useMemo, useState } from 'react' import '../../../../styles/flow.css' import ReactFlow, { Background, Controls, Edge, Node, Position, ReactFlowProvider, useReactFlow, MarkerType, ControlButton, getConnectedEdges, useStoreApi, useEdgesState, useNodesState } from 'reactflow' import 'reactflow/dist/style.css' import { PostgresTable, PostgresRelationship, TableNodeData } from '@/types/Table' import { CgMaximizeAlt } from 'react-icons/cg' import { TbArrowsMinimize } from 'react-icons/tb' import { TableNode } from '../TableNode' import { MetaTableDrawer } from '../../TableDrawer/MetaTableDrawer' import { Button } from '@/components/ui/button' import { DownloadIcon } from '@radix-ui/react-icons' // ReactFlow is scaling everything by the factor of 2 export const NODE_WIDTH = 320 export const NODE_ROW_HEIGHT = 40 export const MetaGraph = ({ tables, relationships, setDoctypes, doctypes, flowRef }: { tables: PostgresTable[] relationships: PostgresRelationship[] setDoctypes: React.Dispatch<React.SetStateAction<string[]>> doctypes: string[] flowRef: React.MutableRefObject<null> }) => { return ( <ReactFlowProvider> <TablesGraph tables={tables} relationships={relationships} setDoctypes={setDoctypes} doctypes={doctypes} flowRef={flowRef} /> </ReactFlowProvider> ) } function getGraphDataFromTables(tables: PostgresTable[], relationships: PostgresRelationship[]): { nodes: Node<TableNodeData>[] edges: Edge[] } { if (!tables.length) { return { nodes: [], edges: [] } } const nodes = tables.map((table) => { const columns = (table.columns || []).map((column) => { return { id: column.id, name: column.name, format: column.format, is_custom_field: column.is_custom_field, } }) return { id: `${table.id}`, type: 'table', data: { name: table.name, isForeign: false, istable: table.istable, columns, }, position: { x: 0, y: 0 }, } }) const edges: Edge[] = [] const uniqueRelationships: PostgresRelationship[] = relationships for (const rel of uniqueRelationships) { const [source, sourceHandle] = findTablesHandleIds( tables, rel.source_table_name, rel.source_column_name ) const [target, targetHandle] = findTablesHandleIds( tables, rel.target_table_name, rel.target_column_name ) // We do not support [external->this] flow currently. if (source && target) { edges.push({ id: String(rel.id), source, sourceHandle, target, targetHandle, animated: true, }) } } return getLayoutedElements(nodes, edges) } function findTablesHandleIds( tables: PostgresTable[], table_name: string, column_name: string ): [string?, string?] { for (const table of tables) { if (table_name !== table.id) continue for (const column of table.columns || []) { if (column_name !== column.id) continue return [String(table.id), column.id] } } return [] } const getLayoutedElements = (nodes: Node<TableNodeData>[], edges: Edge[]) => { const dagreGraph = new dagre.graphlib.Graph() dagreGraph.setDefaultEdgeLabel(() => ({})) dagreGraph.setGraph({ rankdir: 'TB', align: 'UL', nodesep: 80, ranksep: 80, }) nodes.forEach((node) => { dagreGraph.setNode(node.id, { width: NODE_WIDTH / 2, height: (NODE_ROW_HEIGHT / 2) * (node.data.columns.length + 1), // columns + header }) }) edges.forEach((edge) => { dagreGraph.setEdge(edge.source, edge.target) }) dagre.layout(dagreGraph) nodes.forEach((node) => { const nodeWithPosition = dagreGraph.node(node.id) node.targetPosition = Position.Left node.sourcePosition = Position.Right // We are shifting the dagre node position (anchor=center center) to the top left // so it matches the React Flow node anchor point (top left). node.position = { x: nodeWithPosition.x - nodeWithPosition.width / 2, y: nodeWithPosition.y - nodeWithPosition.height / 2, } return node }) return { nodes, edges } } const TablesGraph: FC<{ tables: PostgresTable[], relationships: PostgresRelationship[], setDoctypes: React.Dispatch<React.SetStateAction< string[] >> doctypes: string[] flowRef: React.MutableRefObject<null> }> = ({ tables, relationships, setDoctypes, flowRef }) => { const [nodes, setNodes, onNodesChange] = useNodesState([]); const [edges, setEdges, onEdgesChange] = useEdgesState([]); const [fullscreenOn, setFullScreen] = useState(false); // const [nodeHoverActive, setNodeHoverActive] = useState(true); const reactFlowInstance = useReactFlow() const nodeTypes = useMemo( () => ({ table: TableNode, }), [] ) const toggleFullScreen = () => { if (fullscreenOn) { document.exitFullscreen().then(function () { setFullScreen(false) }) .catch(function (error) { alert("Can't exit fullscreen") console.error(error) }); } else { const element = document.querySelector("body"); // make the element go to full-screen mode element && element.requestFullscreen() .then(function () { setFullScreen(true) }) .catch(function (error) { alert("Can't turn on fullscreen") console.error(error) }); } } const store = useStoreApi(); const onNodeMouseEnter = useCallback( (_: any, node: Node) => { const state = store.getState(); state.resetSelectedElements(); state.addSelectedNodes([node.id]); const connectedEdges = getConnectedEdges([node], edges); setEdges(eds => { return eds.map((ed) => { if (connectedEdges.find(e => e.id === ed.id)) { ed.animated = false ed.style = { ...ed.style, stroke: '#042f2e', } } return ed; }); }); }, [edges, setEdges, store] ); const onNodeMouseLeave = useCallback( (_: any, node: Node) => { const state = store.getState(); state.resetSelectedElements(); state.addSelectedNodes([node.id]); const connectedEdges = getConnectedEdges([node], edges); setEdges(eds => { return eds.map((ed) => { if (connectedEdges.find(e => e.id === ed.id)) { ed.animated = true ed.style = { ...ed.style, stroke: '#0ea5e9', } } return ed; }); }); }, [edges, setEdges, store] ); const [selectedDoctype, setSelectedDoctype] = useState<string | null>(null); const onNodeClick = useCallback((_: any, node: Node<{ name: string }>) => { setSelectedDoctype(node.data?.name) }, [] ); const onNodesDelete = useCallback( (nodesToDelete: Node[]) => { const nodes = nodesToDelete.map((node) => node.id); setNodes((ns) => ns.filter((n) => !nodes.includes(n.id))); setEdges((es) => es.filter((e) => { return ( !nodes.includes(e.source) && !nodes.includes(e.target) ); }) ); setDoctypes((doctypes) => { const doc = doctypes.filter((doctype) => { return !nodes.includes(doctype); }) window.sessionStorage.setItem('ERDMetaDoctypes', JSON.stringify(doc)) return doc }) }, [setNodes, setEdges, setDoctypes] ); useEffect(() => { const { nodes, edges } = getGraphDataFromTables(tables, relationships) setNodes(nodes) setEdges(edges) setTimeout(() => reactFlowInstance.fitView({})) // it needs to happen during next event tick }, [tables, relationships, setNodes, setEdges, reactFlowInstance]) return ( <> <div className='Flow' style={{ width: '100vw', height: 'auto', padding: 2 }}> <ReactFlow style={{ backgroundColor: '#F7FAFC', }} ref={flowRef} nodes={nodes} edges={edges} onNodesChange={onNodesChange} onEdgesChange={onEdgesChange} onNodeClick={onNodeClick} onNodesDelete={onNodesDelete} defaultNodes={[]} defaultEdges={[]} onNodeMouseEnter={onNodeMouseEnter} onNodeMouseLeave={onNodeMouseLeave} snapToGrid={true} snapGrid={[16, 16]} maxZoom={10} defaultEdgeOptions={{ type: 'smoothstep', markerEnd: MarkerType.ArrowClosed, deletable: false, style: { stroke: '#0ea5e9', }, }} nodeTypes={nodeTypes} fitView proOptions={{ hideAttribution: true, }} > <Controls showFitView={false}> <ControlButton onClick={toggleFullScreen}> {!fullscreenOn && <CgMaximizeAlt />} {fullscreenOn && <TbArrowsMinimize />} </ControlButton> </Controls> <div className="absolute top-0 right-0 p-2 pr-16 m-1 bg-white z-10 flex flex-col gap-2 rounded-lg shadow-lg"> <div className="flex items-center gap-2"> <div className="h-4 w-4 bg-blue-500 rounded-full border border-blue-600" /> <div className="text-xs">Table</div> </div> <div className="flex items-center gap-2"> <div className="h-4 w-4 bg-teal-500 rounded-full border border-teal-600" /> <div className="text-xs">Child Table</div> </div> <div className="flex items-center gap-2"> <div className="h-4 w-4 bg-yellow-50 rounded-full border border-yellow-600" /> <div className="text-xs">Custom Field</div> </div> </div> <div className="fixed bottom-4 right-[40%] -translate-x-[50%] z-50"> <Button variant={'outline'} size={'icon'} aria-label='Download ERD'> <DownloadIcon /> </Button> </div> <Background color="#171923" gap={16} /> </ReactFlow> <MetaTableDrawer isOpen={!!selectedDoctype} onClose={() => setSelectedDoctype(null)} doctype={selectedDoctype ?? ''} key={selectedDoctype} /> </div> </> ) }
2302_79757062/commit
dashboard/src/pages/features/erd/meta/MetaGraph.tsx
TSX
agpl-3.0
12,331
import { PostgresTable, PostgresRelationship } from "@/types/Table"; const tables: PostgresTable[] = [ { "name": "Opportunity", "id": "Opportunity", "module": "CRM", "columns": [ { "name": "ID", "id": "name", "format": "Data" }, { "name": "Series", "id": "naming_series", "format": "Select" }, { "name": "Opportunity From", "id": "opportunity_from", "format": "Link" }, { "name": "Customer Name", "id": "customer_name", "format": "Data" }, { "name": "Title", "id": "title", "format": "Data" }, { "name": "Opportunity Type", "id": "opportunity_type", "format": "Link" }, { "name": "Status", "id": "status", "format": "Select" }, { "name": "Detailed Reason", "id": "order_lost_reason", "format": "Small Text" }, { "name": "Currency", "id": "currency", "format": "Link" }, { "name": "Sales Stage", "id": "sales_stage", "format": "Link" }, { "name": "Items", "id": "items", "format": "Table" }, { "name": "Customer / Lead Address", "id": "customer_address", "format": "Link" }, { "name": "Address", "id": "address_display", "format": "Small Text" }, { "name": "Territory", "id": "territory", "format": "Link" }, { "name": "Customer Group", "id": "customer_group", "format": "Link" }, { "name": "Contact Person", "id": "contact_person", "format": "Link" }, { "name": "Contact", "id": "contact_display", "format": "Small Text" }, { "name": "Contact Email", "id": "contact_email", "format": "Data" }, { "name": "Contact Mobile", "id": "contact_mobile", "format": "Data" }, { "name": "Source", "id": "source", "format": "Link" }, { "name": "Campaign", "id": "campaign", "format": "Link" }, { "name": "Company", "id": "company", "format": "Link" }, { "name": "Amended From", "id": "amended_from", "format": "Link" }, { "name": "Print Language", "id": "language", "format": "Link" }, { "name": "No of Employees", "id": "no_of_employees", "format": "Select" }, { "name": "Industry", "id": "industry", "format": "Link" }, { "name": "Market Segment", "id": "market_segment", "format": "Link" }, { "name": "Opportunity Owner", "id": "opportunity_owner", "format": "Link" }, { "name": "Website", "id": "website", "format": "Data" }, { "name": "WhatsApp", "id": "whatsapp", "format": "Data" }, { "name": "Phone", "id": "phone", "format": "Data" }, { "name": "Phone Ext.", "id": "phone_ext", "format": "Data" }, { "name": "Job Title", "id": "job_title", "format": "Data" }, { "name": "Notes", "id": "notes", "format": "Table" }, { "name": "City", "id": "city", "format": "Data" }, { "name": "State", "id": "state", "format": "Data" }, { "name": "Country", "id": "country", "format": "Link" } ] }, { "name": "Prospect", "id": "Prospect", "module": "CRM", "columns": [ { "name": "ID", "id": "name", "format": "Data" }, { "name": "Company Name", "id": "company_name", "format": "Data" }, { "name": "Industry", "id": "industry", "format": "Link" }, { "name": "Market Segment", "id": "market_segment", "format": "Link" }, { "name": "Customer Group", "id": "customer_group", "format": "Link" }, { "name": "Territory", "id": "territory", "format": "Link" }, { "name": "No. of Employees", "id": "no_of_employees", "format": "Select" }, { "name": "Fax", "id": "fax", "format": "Data" }, { "name": "Website", "id": "website", "format": "Data" }, { "name": "Prospect Owner", "id": "prospect_owner", "format": "Link" }, { "name": "Company", "id": "company", "format": "Link" }, { "name": "Opportunities", "id": "opportunities", "format": "Table" }, { "name": "leads", "id": "leads", "format": "Table" }, { "name": "Notes", "id": "notes", "format": "Table" } ] }, { "name": "Prospect Opportunity", "id": "Prospect Opportunity", "module": "CRM", "columns": [ { "name": "ID", "id": "name", "format": "Data" }, { "name": "Opportunity", "id": "opportunity", "format": "Link" }, { "name": "Stage", "id": "stage", "format": "Data" }, { "name": "Currency", "id": "currency", "format": "Link" }, { "name": "Deal Owner", "id": "deal_owner", "format": "Data" }, { "name": "Contact Person", "id": "contact_person", "format": "Link" } ] }, { "name": "Prospect Lead", "id": "Prospect Lead", "module": "CRM", "columns": [ { "name": "ID", "id": "name", "format": "Data" }, { "name": "Lead", "id": "lead", "format": "Link" }, { "name": "Lead Name", "id": "lead_name", "format": "Data" }, { "name": "Status", "id": "status", "format": "Data" }, { "name": "Email", "id": "email", "format": "Data" }, { "name": "Mobile No", "id": "mobile_no", "format": "Data" }, { "name": "Lead Owner", "id": "lead_owner", "format": "Data" } ] }, { "name": "CRM Note", "id": "CRM Note", "module": "CRM", "columns": [ { "name": "ID", "id": "name", "format": "Data" }, { "name": "Added By", "id": "added_by", "format": "Link" } ] }, { "name": "Lead", "id": "Lead", "module": "CRM", "columns": [ { "name": "ID", "id": "name", "format": "Data" }, { "name": "Series", "id": "naming_series", "format": "Select" }, { "name": "Full Name", "id": "lead_name", "format": "Data" }, { "name": "Organization Name", "id": "company_name", "format": "Data" }, { "name": "Email", "id": "email_id", "format": "Data" }, { "name": "Lead Owner", "id": "lead_owner", "format": "Link" }, { "name": "Status", "id": "status", "format": "Select" }, { "name": "Salutation", "id": "salutation", "format": "Link" }, { "name": "Gender", "id": "gender", "format": "Link" }, { "name": "Source", "id": "source", "format": "Link" }, { "name": "From Customer", "id": "customer", "format": "Link" }, { "name": "Campaign Name", "id": "campaign_name", "format": "Link" }, { "name": "Phone", "id": "phone", "format": "Data" }, { "name": "Mobile No", "id": "mobile_no", "format": "Data" }, { "name": "Fax", "id": "fax", "format": "Data" }, { "name": "Lead Type", "id": "type", "format": "Select" }, { "name": "Market Segment", "id": "market_segment", "format": "Link" }, { "name": "Industry", "id": "industry", "format": "Link" }, { "name": "Request Type", "id": "request_type", "format": "Select" }, { "name": "Company", "id": "company", "format": "Link" }, { "name": "Website", "id": "website", "format": "Data" }, { "name": "Territory", "id": "territory", "format": "Link" }, { "name": "Unsubscribed", "id": "unsubscribed", "format": "Check" }, { "name": "Blog Subscriber", "id": "blog_subscriber", "format": "Check" }, { "name": "Title", "id": "title", "format": "Data" }, { "name": "Print Language", "id": "language", "format": "Link" }, { "name": "First Name", "id": "first_name", "format": "Data" }, { "name": "Middle Name", "id": "middle_name", "format": "Data" }, { "name": "Last Name", "id": "last_name", "format": "Data" }, { "name": "No of Employees", "id": "no_of_employees", "format": "Select" }, { "name": "WhatsApp", "id": "whatsapp_no", "format": "Data" }, { "name": "Phone Ext.", "id": "phone_ext", "format": "Data" }, { "name": "Qualified By", "id": "qualified_by", "format": "Link" }, { "name": "Qualification Status", "id": "qualification_status", "format": "Select" }, { "name": "Job Title", "id": "job_title", "format": "Data" }, { "name": "Notes", "id": "notes", "format": "Table" }, { "name": "Disabled", "id": "disabled", "format": "Check" }, { "name": "City", "id": "city", "format": "Data" }, { "name": "State", "id": "state", "format": "Data" }, { "name": "Country", "id": "country", "format": "Link" } ] }, { "name": "Campaign", "id": "Campaign", "module": "CRM", "columns": [ { "name": "ID", "id": "name", "format": "Data" }, { "name": "Campaign Name", "id": "campaign_name", "format": "Data" }, { "name": "Naming Series", "id": "naming_series", "format": "Select" }, { "name": "Campaign Schedules", "id": "campaign_schedules", "format": "Table" }, { "name": "Description", "id": "description", "format": "Text" } ] }, { "name": "Lead Source", "id": "Lead Source", "module": "CRM", "columns": [ { "name": "ID", "id": "name", "format": "Data" }, { "name": "Source Name", "id": "source_name", "format": "Data" } ] } ] export const relationships: PostgresRelationship[] = [ { "id": "Opportunity_opportunity_type", "source_table_name": "Opportunity", "source_column_name": "opportunity_type", "target_table_name": "Opportunity Type", "target_column_name": "name" }, { "id": "Opportunity_sales_stage", "source_table_name": "Opportunity", "source_column_name": "sales_stage", "target_table_name": "Sales Stage", "target_column_name": "name" }, { "id": "Opportunity_items", "source_table_name": "Opportunity", "source_column_name": "items", "target_table_name": "Opportunity Item", "target_column_name": "name" }, { "id": "Opportunity_source", "source_table_name": "Opportunity", "source_column_name": "source", "target_table_name": "Lead Source", "target_column_name": "name" }, { "id": "Opportunity_campaign", "source_table_name": "Opportunity", "source_column_name": "campaign", "target_table_name": "Campaign", "target_column_name": "name" }, { "id": "Opportunity_amended_from", "source_table_name": "Opportunity", "source_column_name": "amended_from", "target_table_name": "Opportunity", "target_column_name": "name" }, { "id": "Opportunity_market_segment", "source_table_name": "Opportunity", "source_column_name": "market_segment", "target_table_name": "Market Segment", "target_column_name": "name" }, { "id": "Opportunity_notes", "source_table_name": "Opportunity", "source_column_name": "notes", "target_table_name": "CRM Note", "target_column_name": "name" }, { "id": "Prospect_market_segment", "source_table_name": "Prospect", "source_column_name": "market_segment", "target_table_name": "Market Segment", "target_column_name": "name" }, { "id": "Prospect_opportunities", "source_table_name": "Prospect", "source_column_name": "opportunities", "target_table_name": "Prospect Opportunity", "target_column_name": "name" }, { "id": "Prospect_leads", "source_table_name": "Prospect", "source_column_name": "leads", "target_table_name": "Prospect Lead", "target_column_name": "name" }, { "id": "Prospect_notes", "source_table_name": "Prospect", "source_column_name": "notes", "target_table_name": "CRM Note", "target_column_name": "name" }, { "id": "Prospect Opportunity_opportunity", "source_table_name": "Prospect Opportunity", "source_column_name": "opportunity", "target_table_name": "Opportunity", "target_column_name": "name" }, { "id": "Prospect Lead_lead", "source_table_name": "Prospect Lead", "source_column_name": "lead", "target_table_name": "Lead", "target_column_name": "name" }, { "id": "Lead_source", "source_table_name": "Lead", "source_column_name": "source", "target_table_name": "Lead Source", "target_column_name": "name" }, { "id": "Lead_campaign_name", "source_table_name": "Lead", "source_column_name": "campaign_name", "target_table_name": "Campaign", "target_column_name": "name" }, { "id": "Lead_market_segment", "source_table_name": "Lead", "source_column_name": "market_segment", "target_table_name": "Market Segment", "target_column_name": "name" }, { "id": "Lead_notes", "source_table_name": "Lead", "source_column_name": "notes", "target_table_name": "CRM Note", "target_column_name": "name" }, { "id": "Campaign_campaign_schedules", "source_table_name": "Campaign", "source_column_name": "campaign_schedules", "target_table_name": "Campaign Email Schedule", "target_column_name": "name" } ] export default tables;
2302_79757062/commit
dashboard/src/pages/features/erd/tables.ts
TypeScript
agpl-3.0
20,606
import { Header } from "@/components/common/Header" import { YourApps } from "@/components/features/meta_apps/YourApps" import { Projects } from "@/components/features/projects/Projects" import { TabsContent, TabsList, TabsTrigger, Tabs } from "@/components/ui/tabs" import { isSystemAppAvailable } from "@/utils/roles" export const Overview = () => { const areAppsAvailable = isSystemAppAvailable() return ( <div className="h-screen flex flex-col gap-2 space-x-2 p-2 pt-0"> <Header /> {areAppsAvailable ? <Tabs defaultValue="projects" className="h-full"> <TabsList className="grid grid-cols-2 w-[400px]"> <TabsTrigger value="projects">Projects</TabsTrigger> <TabsTrigger value="your-apps">Site Apps</TabsTrigger> </TabsList> <TabsContent value="projects"> <Projects /> </TabsContent> <TabsContent value="your-apps"> <YourApps /> </TabsContent> </Tabs> : <Projects />} </div> ) }
2302_79757062/commit
dashboard/src/pages/overview/Overview.tsx
TSX
agpl-3.0
1,122
.Flow { width: 100%; height: 100%; flex-grow: 1; font-size: 12px; } :not(:root):fullscreen::backdrop { background-color: #fff; }
2302_79757062/commit
dashboard/src/styles/flow.css
CSS
agpl-3.0
141
export interface APIData { name: string arguments: Argument[] def: string def_index: number request_types: string[] xss_safe: boolean allow_guest: boolean other_decorators: string[] index: number file: string api_path: string block_start: number block_end: number documentation?: string } export interface Argument { argument: string type: string default: string }
2302_79757062/commit
dashboard/src/types/APIData.ts
TypeScript
agpl-3.0
433
export interface CommitProjectBranch { commit_project: string branch_name: string path_to_folder: string commit_hash: string app_name: string last_fetched: string modules: string module_doctypes_map: string doctype_module_map: string whitelisted_apis: string } export interface ModuleData { [key: string]: ModuleDataValue } export interface ModuleDataValue { doctype_names: string[]; module: string; number_of_doctypes: number; } export interface AppModuleData { [key: string]: ModuleData }
2302_79757062/commit
dashboard/src/types/CommitProjectBranch.ts
TypeScript
agpl-3.0
552
export interface DocField{ creation: string name: string modified: string owner: string modified_by: string docstatus: 0 | 1 | 2 parent?: string parentfield?: string parenttype?: string idx?: number /** Label : Data */ label?: string /** Type : Select */ fieldtype: "Autocomplete" | "Attach" | "Attach Image" | "Barcode" | "Button" | "Check" | "Code" | "Color" | "Column Break" | "Currency" | "Data" | "Date" | "Datetime" | "Duration" | "Dynamic Link" | "Float" | "Fold" | "Geolocation" | "Heading" | "HTML" | "HTML Editor" | "Icon" | "Image" | "Int" | "JSON" | "Link" | "Long Text" | "Markdown Editor" | "Password" | "Percent" | "Phone" | "Read Only" | "Rating" | "Section Break" | "Select" | "Signature" | "Small Text" | "Tab Break" | "Table" | "Table MultiSelect" | "Text" | "Text Editor" | "Time" /** Name : Data */ fieldname?: string /** Precision : Select - Set non-standard precision for a Float or Currency field */ precision?: "" | "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" /** Length : Int */ length?: number /** Non Negative : Check */ non_negative?: 0 | 1 /** Hide Days : Check */ hide_days?: 0 | 1 /** Hide Seconds : Check */ hide_seconds?: 0 | 1 /** Mandatory : Check */ reqd?: 0 | 1 /** Virtual : Check */ is_virtual?: 0 | 1 /** Index : Check */ search_index?: 0 | 1 /** Options : Small Text - For Links, enter the DocType as range. For Select, enter list of Options, each on a new line. */ options?: string /** Show Dashboard : Check */ show_dashboard?: 0 | 1 /** Default : Small Text */ default?: string /** Fetch From : Small Text */ fetch_from?: string /** Fetch only if value is not set : Check */ fetch_if_empty?: 0 | 1 /** Hidden : Check */ hidden?: 0 | 1 /** Bold : Check */ bold?: 0 | 1 /** Allow in Quick Entry : Check */ allow_in_quick_entry?: 0 | 1 /** Translatable : Check */ translatable?: 0 | 1 /** Print Hide : Check */ print_hide?: 0 | 1 /** Print Hide If No Value : Check */ print_hide_if_no_value?: 0 | 1 /** Report Hide : Check */ report_hide?: 0 | 1 /** Display Depends On (JS) : Code */ depends_on?: string /** Collapsible : Check */ collapsible?: 0 | 1 /** Collapsible Depends On (JS) : Code */ collapsible_depends_on?: string /** Hide Border : Check */ hide_border?: 0 | 1 /** In List View : Check */ in_list_view?: 0 | 1 /** In List Filter : Check */ in_standard_filter?: 0 | 1 /** In Preview : Check */ in_preview?: 0 | 1 /** In Filter : Check */ in_filter?: 0 | 1 /** In Global Search : Check */ in_global_search?: 0 | 1 /** Read Only : Check */ read_only?: 0 | 1 /** Allow on Submit : Check */ allow_on_submit?: 0 | 1 /** Ignore User Permissions : Check */ ignore_user_permissions?: 0 | 1 /** Allow Bulk Edit : Check */ allow_bulk_edit?: 0 | 1 /** Perm Level : Int */ permlevel?: number /** Ignore XSS Filter : Check - Don't encode HTML tags like &lt;script&gt; or just characters like &lt; or &gt;, as they could be intentionally used in this field */ ignore_xss_filter?: 0 | 1 /** Unique : Check */ unique?: 0 | 1 /** No Copy : Check */ no_copy?: 0 | 1 /** Set only once : Check */ set_only_once?: 0 | 1 /** Remember Last Selected Value : Check */ remember_last_selected_value?: 0 | 1 /** Mandatory Depends On (JS) : Code */ mandatory_depends_on?: string /** Read Only Depends On (JS) : Code */ read_only_depends_on?: string /** Print Width : Data */ print_width?: string /** Width : Data */ width?: string /** Max Height : Data */ max_height?: string /** Columns : Int - Number of columns for a field in a List View or a Grid (Total Columns should be less than 11) */ columns?: number /** Description : Small Text */ description?: string /** Documentation URL : Data */ documentation_url?: string /** : Data */ oldfieldname?: string /** : Data */ oldfieldtype?: string }
2302_79757062/commit
dashboard/src/types/Core/DocField.ts
TypeScript
agpl-3.0
3,849
export interface DocPerm{ creation: string name: string modified: string owner: string modified_by: string docstatus: 0 | 1 | 2 parent?: string parentfield?: string parenttype?: string idx?: number /** Role : Link - Role */ role: string /** If user is the owner : Check - Apply this rule if the User is the Owner */ if_owner?: 0 | 1 /** Level : Int */ permlevel?: number /** Select : Check */ select?: 0 | 1 /** Read : Check */ read?: 0 | 1 /** Write : Check */ write?: 0 | 1 /** Create : Check */ create?: 0 | 1 /** Delete : Check */ delete?: 0 | 1 /** Submit : Check */ submit?: 0 | 1 /** Cancel : Check */ cancel?: 0 | 1 /** Amend : Check */ amend?: 0 | 1 /** Report : Check */ report?: 0 | 1 /** Export : Check */ export?: 0 | 1 /** Import : Check */ import?: 0 | 1 /** Share : Check */ share?: 0 | 1 /** Print : Check */ print?: 0 | 1 /** Email : Check */ email?: 0 | 1 }
2302_79757062/commit
dashboard/src/types/Core/DocPerm.ts
TypeScript
agpl-3.0
921
import { DocPerm } from './DocPerm' import { DocTypeAction } from './DocTypeAction' import { DocTypeLink } from './DocTypeLink' import { DocTypeState } from './DocTypeState' import { DocField } from './DocField' export interface DocType { creation: string name: string modified: string owner: string modified_by: string docstatus: 0 | 1 | 2 parent?: string parentfield?: string parenttype?: string idx?: number /** Module : Link - Module Def */ module: string /** Is Submittable : Check - Once submitted, submittable documents cannot be changed. They can only be Cancelled and Amended. */ is_submittable?: 0 | 1 /** Is Child Table : Check - Child Tables are shown as a Grid in other DocTypes */ istable?: 0 | 1 /** Is Single : Check - Single Types have only one record no tables associated. Values are stored in tabSingles */ issingle?: 0 | 1 /** Is Tree : Check - Tree structures are implemented using Nested Set */ is_tree?: 0 | 1 /** Is Calendar and Gantt : Check - Enables Calendar and Gantt views. */ is_calendar_and_gantt?: 0 | 1 /** Editable Grid : Check */ editable_grid?: 0 | 1 /** Quick Entry : Check - Open a dialog with mandatory fields to create a new record quickly */ quick_entry?: 0 | 1 /** Track Changes : Check - If enabled, changes to the document are tracked and shown in timeline */ track_changes?: 0 | 1 /** Track Seen : Check - If enabled, the document is marked as seen, the first time a user opens it */ track_seen?: 0 | 1 /** Track Views : Check - If enabled, document views are tracked, this can happen multiple times */ track_views?: 0 | 1 /** Custom? : Check */ custom?: 0 | 1 /** Beta : Check */ beta?: 0 | 1 /** Is Virtual : Check */ is_virtual?: 0 | 1 /** Queue in Background (BETA) : Check - Enabling this will submit documents in background */ queue_in_background?: 0 | 1 /** Naming Rule : Select */ naming_rule?: "" | "Set by user" | "Autoincrement" | "By fieldname" | "By Naming Series field" | "Expression" | "Expression (old style)" | "Random" | "By script" /** Auto Name : Data - Naming Options: <ol><li><b>field:[fieldname]</b> - By Field</li><li><b>autoincrement</b> - Uses Databases' Auto Increment feature</li><li><b>naming_series:</b> - By Naming Series (field called naming_series must be present)</li><li><b>Prompt</b> - Prompt user for a name</li><li><b>[series]</b> - Series by prefix (separated by a dot); for example PRE.#####</li> <li><b>format:EXAMPLE-{MM}morewords{fieldname1}-{fieldname2}-{#####}</b> - Replace all braced words (fieldnames, date words (DD, MM, YY), series) with their value. Outside braces, any characters can be used.</li></ol> */ autoname?: string /** Allow Rename : Check */ allow_rename?: 0 | 1 /** Description : Small Text */ description?: string /** Documentation Link : Data - URL for documentation or help */ documentation?: string /** Image Field : Data - Must be of type "Attach Image" */ image_field?: string /** Timeline Field : Data - Comments and Communications will be associated with this linked document */ timeline_field?: string /** Parent Field (Tree) : Data */ nsm_parent_field?: string /** Max Attachments : Int */ max_attachments?: number /** Hide Sidebar, Menu, and Comments : Check */ hide_toolbar?: 0 | 1 /** Hide Copy : Check */ allow_copy?: 0 | 1 /** Allow Import (via Data Import Tool) : Check */ allow_import?: 0 | 1 /** Allow events in timeline : Check */ allow_events_in_timeline?: 0 | 1 /** Allow Auto Repeat : Check */ allow_auto_repeat?: 0 | 1 /** Make Attachments Public by Default : Check */ make_attachments_public?: 0 | 1 /** Title Field : Data */ title_field?: string /** Show Title in Link Fields : Check */ show_title_field_in_link?: 0 | 1 /** Translate Link Fields : Check */ translated_doctype?: 0 | 1 /** Search Fields : Data */ search_fields?: string /** Default Print Format : Data */ default_print_format?: string /** Default Sort Field : Data */ sort_field?: string /** Default Sort Order : Select */ sort_order?: "ASC" | "DESC" /** Default View : Select */ default_view?: string /** Force Re-route to Default View : Check */ force_re_route_to_default_view?: 0 | 1 /** Show in Module Section : Select */ document_type?: "" | "Document" | "Setup" | "System" | "Other" /** Icon : Data */ icon?: string /** Color : Data */ color?: string /** Show Preview Popup : Check */ show_preview_popup?: 0 | 1 /** Make "name" searchable in Global Search : Check */ show_name_in_global_search?: 0 | 1 /** Default Email Template : Link - Email Template */ default_email_template?: string /** Allow document creation via Email : Check */ email_append_to?: 0 | 1 /** Sender Email Field : Data */ sender_field?: string /** Sender Name Field : Data */ sender_name_field?: string /** Subject Field : Data */ subject_field?: string /** Permissions : Table - DocPerm */ permissions?: DocPerm[] /** Restrict To Domain : Link - Domain */ restrict_to_domain?: string /** User Cannot Search : Check */ read_only?: 0 | 1 /** User Cannot Create : Check */ in_create?: 0 | 1 /** Actions : Table - DocType Action */ actions?: DocTypeAction[] /** Links : Table - DocType Link */ links?: DocTypeLink[] /** States : Table - DocType State */ states?: DocTypeState[] /** Has Web View : Check */ has_web_view?: 0 | 1 /** Allow Guest to View : Check */ allow_guest_to_view?: 0 | 1 /** Index Web Pages for Search : Check */ index_web_pages_for_search?: 0 | 1 /** Route : Data */ route?: string /** Is Published Field : Data */ is_published_field?: string /** Website Search Field : Data */ website_search_field?: string /** Database Engine : Select */ engine?: "InnoDB" | "MyISAM" /** : Data */ migration_hash?: string /** Fields : Table - DocField */ fields?: DocField[] }
2302_79757062/commit
dashboard/src/types/Core/DocType.ts
TypeScript
agpl-3.0
5,796
export interface DocTypeAction{ creation: string name: string modified: string owner: string modified_by: string docstatus: 0 | 1 | 2 parent?: string parentfield?: string parenttype?: string idx?: number /** Label : Data */ label: string /** Action Type : Select */ action_type: "Server Action" | "Route" /** Action / Route : Small Text */ action: string /** Group : Data */ group?: string /** Hidden : Check */ hidden?: 0 | 1 /** Custom : Check */ custom?: 0 | 1 }
2302_79757062/commit
dashboard/src/types/Core/DocTypeAction.ts
TypeScript
agpl-3.0
488
export interface DocTypeLink{ creation: string name: string modified: string owner: string modified_by: string docstatus: 0 | 1 | 2 parent?: string parentfield?: string parenttype?: string idx?: number /** Link DocType : Link - DocType */ link_doctype: string /** Link Fieldname : Data */ link_fieldname: string /** Parent DocType : Link - DocType */ parent_doctype?: string /** Table Fieldname : Data */ table_fieldname?: string /** Group : Data */ group?: string /** Hidden : Check */ hidden?: 0 | 1 /** Is Child Table : Check */ is_child_table?: 0 | 1 /** Custom : Check */ custom?: 0 | 1 }
2302_79757062/commit
dashboard/src/types/Core/DocTypeLink.ts
TypeScript
agpl-3.0
620
export interface DocTypeState{ creation: string name: string modified: string owner: string modified_by: string docstatus: 0 | 1 | 2 parent?: string parentfield?: string parenttype?: string idx?: number /** Title : Data */ title: string /** Color : Select */ color: "Blue" | "Cyan" | "Gray" | "Green" | "Light Blue" | "Orange" | "Pink" | "Purple" | "Red" | "Yellow" /** Custom : Check */ custom?: 0 | 1 }
2302_79757062/commit
dashboard/src/types/Core/DocTypeState.ts
TypeScript
agpl-3.0
421
export interface File{ creation: string name: string modified: string owner: string modified_by: string docstatus: 0 | 1 | 2 parent?: string parentfield?: string parenttype?: string idx?: number /** File Name : Data */ file_name?: string /** File Description : Small Text */ file_description?: string /** Is Private : Check */ is_private?: 0 | 1 /** File Type : Data */ file_type?: string /** Is Home Folder : Check */ is_home_folder?: 0 | 1 /** Is Attachments Folder : Check */ is_attachments_folder?: 0 | 1 /** File Size : Int */ file_size?: number /** File URL : Code */ file_url?: string /** Thumbnail URL : Small Text */ thumbnail_url?: string /** Folder : Link - File */ folder?: string /** Is Folder : Check */ is_folder?: 0 | 1 /** Attached To DocType : Link - DocType */ attached_to_doctype?: string /** Attached To Name : Data */ attached_to_name?: string /** Attached To Field : Data */ attached_to_field?: string /** old_parent : Data */ old_parent?: string /** Content Hash : Data */ content_hash?: string /** Uploaded To Dropbox : Check */ uploaded_to_dropbox?: 0 | 1 /** Uploaded To Google Drive : Check */ uploaded_to_google_drive?: 0 | 1 }
2302_79757062/commit
dashboard/src/types/Core/File.ts
TypeScript
agpl-3.0
1,203
export type TableNodeData = { name: string columns: { id: string name: string format: string }[] } export type PostgresTable = { name: string, id: string, module: string, creation?: string, modified?: string, modified_by?: string, istable?: number, columns: PostgresColumn[], // relationships: PostgresRelationship[] } export type PostgresColumn = { // table_id: string, id: string, name: string, // data_type: string, format: string, options?: string, reqd?: number, oldfieldname?: string, oldfieldtype?: string, read_only?: number, hidden?: number, default?: string, is_custom_field: number, // default_value: string, // is_unique: boolean, // is_nullable: boolean, } export type PostgresRelationship = { id: string, source_table_name: string, source_column_name: string, target_table_name: string, target_column_name: string, }
2302_79757062/commit
dashboard/src/types/Table.ts
TypeScript
agpl-3.0
989
export interface CommitOrganization{ creation: string name: string modified: string owner: string modified_by: string docstatus: 0 | 1 | 2 parent?: string parentfield?: string parenttype?: string idx?: number /** Organization Name : Data */ organization_name: string /** Github Org : Data */ github_org: string /** Image : Attach Image */ image?: string /** About : Data */ about?: string }
2302_79757062/commit
dashboard/src/types/commit/CommitOrganization.ts
TypeScript
agpl-3.0
409
export interface CommitProject{ creation: string name: string modified: string owner: string modified_by: string docstatus: 0 | 1 | 2 parent?: string parentfield?: string parenttype?: string idx?: number /** Organization : Link - Commit Organization */ org: string /** Display Name : Data */ display_name: string /** Github Repo : Data */ repo_name: string /** App Name : Data */ app_name?: string /** Image : Attach Image */ image?: string /** Banner Image : Attach Image */ banner_image?: string /** Path to folder : Data */ path_to_folder?: string /** Description : Data */ description?: string }
2302_79757062/commit
dashboard/src/types/commit/CommitProject.ts
TypeScript
agpl-3.0
626
export interface CommitProjectBranch{ creation: string name: string modified: string owner: string modified_by: string docstatus: 0 | 1 | 2 parent?: string parentfield?: string parenttype?: string idx?: number /** Commit Project : Link - Commit Project */ project: string /** Branch Name : Data */ branch_name: string /** Path to folder : Data */ path_to_folder?: string /** Commit Hash : Data */ commit_hash?: string /** App Name : Data */ app_name?: string /** Last fetched : Datetime */ last_fetched?: string /** Modules : Long Text */ modules?: string /** Module - Doctypes Map : JSON */ module_doctypes_map?: any /** Doctype - Module Map : JSON */ doctype_module_map?: any /** Whitelisted APIs : JSON */ whitelisted_apis?: any frequency?: "Daily" | "Weekly" | "Monthly" }
2302_79757062/commit
dashboard/src/types/commit/CommitProjectBranch.ts
TypeScript
agpl-3.0
809
export interface CommitSettings{ creation: string name: string modified: string owner: string modified_by: string docstatus: 0 | 1 | 2 parent?: string parentfield?: string parenttype?: string idx?: number /** Show System Apps : Check */ show_system_apps?: 0 | 1 }
2302_79757062/commit
dashboard/src/types/commit/CommitSettings.ts
TypeScript
agpl-3.0
276
export interface GithubSettings{ creation: string name: string modified: string owner: string modified_by: string docstatus: 0 | 1 | 2 parent?: string parentfield?: string parenttype?: string idx?: number /** Github App name : Data */ github_app_name?: string /** Client ID : Data */ client_id: string /** Client Secret : Password */ client_secret?: string /** Authorization URI : Small Text */ authorization_uri: string /** Token URI : Data */ token_uri: string /** Redirect URI : Data - This is the Callback URI registered in your Github App. */ redirect_uri?: string /** Scopes : JSON */ scopes?: any }
2302_79757062/commit
dashboard/src/types/commit/GithubSettings.ts
TypeScript
agpl-3.0
630
export const getSystemDefault = (fieldName: string, fallback?: any) => { // @ts-expect-error return window.frappe?.boot?.sysdefaults?.[fieldName] ?? fallback } export const getUserDefaults = (fieldName: string, fallback?: any) => { // @ts-expect-error return window.frappe?.boot?.user?.defaults?.[fieldName] ?? fallback }
2302_79757062/commit
dashboard/src/utils/defaults.ts
TypeScript
agpl-3.0
338
frappe.defaults = { get_user_default: function (key) { let defaults = frappe.boot.user.defaults; let d = defaults[key]; if (!d) { key = key.replace(/ /g, '_').toLowerCase(); d = defaults[key]; } if (Array.isArray(d)) d = d[0]; return d; }, };
2302_79757062/commit
dashboard/src/utils/namespace/defaults.js
JavaScript
agpl-3.0
283
import './namespace'; import './sync'; import './locals'; import './defaults';
2302_79757062/commit
dashboard/src/utils/namespace/index.js
JavaScript
agpl-3.0
79
// frappe.model.sync(window.frappe.boot.docs);
2302_79757062/commit
dashboard/src/utils/namespace/locals.js
JavaScript
agpl-3.0
47
if (!window.frappe) window.frappe = {}; frappe.provide = function (namespace) { // docs: create a namespace // var nsl = namespace.split('.'); var parent = window; for (var i = 0; i < nsl.length; i++) { var n = nsl[i]; if (!parent[n]) { parent[n] = {}; } parent = parent[n]; } return parent; }; frappe.provide('locals'); frappe.provide('frappe.flags'); frappe.provide('frappe.settings'); frappe.provide('locals.DocType'); frappe.provide('frappe.model'); frappe.provide('frappe.defaults');
2302_79757062/commit
dashboard/src/utils/namespace/namespace.js
JavaScript
agpl-3.0
525
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors // MIT License. See license.txt import isPlainObject from 'lodash.isplainobject'; Object.assign(frappe.model, { docinfo: {}, sync: function (r) { /* docs: extract docs, docinfo (attachments, comments, assignments) from incoming request and set in `locals` and `frappe.model.docinfo` */ var isPlain; if (!r.docs && !r.docinfo) r = { docs: r }; isPlain = isPlainObject(r.docs); if (isPlain) r.docs = [r.docs]; if (r.docs) { for (var i = 0, l = r.docs.length; i < l; i++) { var d = r.docs[i]; if (locals[d.doctype] && locals[d.doctype][d.name]) { // update values frappe.model.update_in_locals(d); } else { frappe.model.add_to_locals(d); } d.__last_sync_on = new Date(); } } frappe.model.sync_docinfo(r); return r.docs; }, sync_docinfo: (r) => { // set docinfo (comments, assign, attachments) if (r.docinfo) { const { doctype, name } = r.docinfo; if (!frappe.model.docinfo[doctype]) { frappe.model.docinfo[doctype] = {}; } frappe.model.docinfo[doctype][name] = r.docinfo; // copy values to frappe.boot.user_info Object.assign(frappe.boot.user_info, r.docinfo.user_info); } return r.docs; }, add_to_locals: function (doc) { if (!locals[doc.doctype]) locals[doc.doctype] = {}; if (!doc.name && doc.__islocal) { // get name (local if required) if (!doc.parentfield) frappe.model.clear_doc(doc); doc.name = frappe.model.get_new_name(doc.doctype); if (!doc.parentfield) frappe.provide('frappe.model.docinfo.' + doc.doctype + '.' + doc.name); } locals[doc.doctype][doc.name] = doc; // let meta = frappe.get_meta(doc.doctype); // let is_table = meta ? meta.istable : doc.parentfield; // // add child docs to locals // if (!is_table) { // for (var i in doc) { // var value = doc[i]; // if (isArray(value)) { // for (var x = 0, y = value.length; x < y; x++) { // var d = value[x]; // if (typeof d == "object" && !d.parent) d.parent = doc.name; // frappe.model.add_to_locals(d); // } // } // } // } }, update_in_locals: function (doc) { // update values in the existing local doc instead of replacing let local_doc = locals[doc.doctype][doc.name]; let clear_keys = function (source, target) { Object.keys(target).map((key) => { if (source[key] == undefined) delete target[key]; }); }; for (let fieldname in doc) { let df = frappe.meta.get_field(doc.doctype, fieldname); if (df && frappe.model.table_fields.includes(df.fieldtype)) { // table if (!(doc[fieldname] instanceof Array)) { doc[fieldname] = []; } if (!(local_doc[fieldname] instanceof Array)) { local_doc[fieldname] = []; } // child table, override each row and append new rows if required for (let i = 0; i < doc[fieldname].length; i++) { let d = doc[fieldname][i]; let local_d = local_doc[fieldname][i]; if (local_d) { // deleted and added again if (!locals[d.doctype]) locals[d.doctype] = {}; if (!d.name) { // incoming row is new, find a new name d.name = frappe.model.get_new_name(doc.doctype); } // if incoming row is not registered, register it if (!locals[d.doctype][d.name]) { // detach old key delete locals[d.doctype][local_d.name]; // re-attach with new name locals[d.doctype][d.name] = local_d; } // row exists, just copy the values Object.assign(local_d, d); clear_keys(d, local_d); } else { local_doc[fieldname].push(d); if (!d.parent) d.parent = doc.name; frappe.model.add_to_locals(d); } } // remove extra rows if (local_doc[fieldname].length > doc[fieldname].length) { for ( let i = doc[fieldname].length; i < local_doc[fieldname].length; i++ ) { // clear from local let d = local_doc[fieldname][i]; if (locals[d.doctype] && locals[d.doctype][d.name]) { delete locals[d.doctype][d.name]; } } local_doc[fieldname].length = doc[fieldname].length; } } else { // literal local_doc[fieldname] = doc[fieldname]; } } // clear keys on parent clear_keys(doc, local_doc); }, remove_from_locals: function (doctype, name) { let clear_doc = function (doctype, name) { var doc = locals[doctype] && locals[doctype][name]; if (!doc) return; var parent = null; if (doc.parenttype) { parent = doc.parent; var parenttype = doc.parenttype, parentfield = doc.parentfield; } delete locals[doctype][name]; if (parent) { var parent_doc = locals[parenttype][parent]; var newlist = [], idx = 1; $.each(parent_doc[parentfield], function (i, d) { if (d.name != name) { newlist.push(d); d.idx = idx; idx++; } parent_doc[parentfield] = newlist; }); } }; clear_doc(doctype, name); }, });
2302_79757062/commit
dashboard/src/utils/namespace/sync.js
JavaScript
agpl-3.0
5,688
export const isSystemManager = () => { if (import.meta.env.DEV) { return true } //@ts-expect-error return (window?.frappe?.boot?.user?.roles ?? []).includes('System Manager'); } export const isSystemAppAvailable = () => { if (import.meta.env.DEV) { return true } //@ts-expect-error return (window?.frappe?.boot?.show_system_apps ? true : false) }
2302_79757062/commit
dashboard/src/utils/roles.ts
TypeScript
agpl-3.0
396
/** @type {import('tailwindcss').Config} */ module.exports = { darkMode: ["class"], content: [ './pages/**/*.{ts,tsx}', './components/**/*.{ts,tsx}', './app/**/*.{ts,tsx}', './src/**/*.{ts,tsx}', ], theme: { container: { center: true, padding: "2rem", screens: { "2xl": "1400px", }, }, extend: { colors: { border: "hsl(var(--border))", input: "hsl(var(--input))", ring: "hsl(var(--ring))", background: "hsl(var(--background))", foreground: "hsl(var(--foreground))", primary: { DEFAULT: "hsl(var(--primary))", foreground: "hsl(var(--primary-foreground))", }, secondary: { DEFAULT: "hsl(var(--secondary))", foreground: "hsl(var(--secondary-foreground))", }, destructive: { DEFAULT: "hsl(var(--destructive))", foreground: "hsl(var(--destructive-foreground))", }, muted: { DEFAULT: "hsl(var(--muted))", foreground: "hsl(var(--muted-foreground))", }, accent: { DEFAULT: "hsl(var(--accent))", foreground: "hsl(var(--accent-foreground))", }, popover: { DEFAULT: "hsl(var(--popover))", foreground: "hsl(var(--popover-foreground))", }, card: { DEFAULT: "hsl(var(--card))", foreground: "hsl(var(--card-foreground))", }, }, borderRadius: { lg: "var(--radius)", md: "calc(var(--radius) - 2px)", sm: "calc(var(--radius) - 4px)", }, keyframes: { "accordion-down": { from: { height: 0 }, to: { height: "var(--radix-accordion-content-height)" }, }, "accordion-up": { from: { height: "var(--radix-accordion-content-height)" }, to: { height: 0 }, }, }, animation: { "accordion-down": "accordion-down 0.2s ease-out", "accordion-up": "accordion-up 0.2s ease-out", }, }, }, plugins: [require("tailwindcss-animate")], }
2302_79757062/commit
dashboard/tailwind.config.js
JavaScript
agpl-3.0
2,125
import path from 'path'; import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react' import proxyOptions from './proxyOptions'; // https://vitejs.dev/config/ export default defineConfig({ plugins: [react()], server: { port: 8080, proxy: proxyOptions }, resolve: { alias: { "@": path.resolve(__dirname, "./src"), }, }, build: { outDir: '../commit/public/commit', emptyOutDir: true, target: 'es2015', }, });
2302_79757062/commit
dashboard/vite.config.ts
TypeScript
agpl-3.0
449
from setuptools import setup, find_packages with open("requirements.txt") as f: install_requires = f.read().strip().split("\n") # get version from __version__ variable in commit/__init__.py from commit import __version__ as version setup( name="commit", version=version, description="The Commit Company", author="The Commit Company", author_email="yash.jane@thecommit.company", packages=find_packages(), zip_safe=False, include_package_data=True, install_requires=install_requires )
2302_79757062/commit
setup.py
Python
agpl-3.0
496
__version__ = "1.0.0-dev"
2302_79757062/builder
builder/__init__.py
Python
agpl-3.0
26
import json import os from io import BytesIO from urllib.parse import unquote import frappe import requests from frappe.core.doctype.file.file import get_local_image from frappe.core.doctype.file.utils import delete_file from frappe.integrations.utils import make_post_request from frappe.model.document import Document from frappe.utils.telemetry import POSTHOG_HOST_FIELD, POSTHOG_PROJECT_FIELD from PIL import Image from builder.builder.doctype.builder_page.builder_page import BuilderPageRenderer @frappe.whitelist() def get_blocks(prompt): API_KEY = frappe.conf.openai_api_key if not API_KEY: frappe.throw("OpenAI API Key not set in site config.") messages = [ { "role": "system", "content": "You are a website developer. You respond only with HTML code WITHOUT any EXPLANATION. You use any publicly available images in the webpage. You can use any font from fonts.google.com. Do not use any external css file or font files. DO NOT ADD <style> TAG AT ALL! You should use tailwindcss for styling the page. Use images from pixabay.com or unsplash.com", }, {"role": "user", "content": prompt}, ] response = make_post_request( "https://api.openai.com/v1/chat/completions", headers={"Content-Type": "application/json", "Authorization": f"Bearer {API_KEY}"}, data=json.dumps( { "model": "gpt-3.5-turbo", "messages": messages, } ), ) return response["choices"][0]["message"]["content"] @frappe.whitelist() def get_posthog_settings(): can_record_session = False if start_time := frappe.db.get_default("session_recording_start"): time_difference = ( frappe.utils.now_datetime() - frappe.utils.get_datetime(start_time) ).total_seconds() if time_difference < 86400: # 1 day can_record_session = True return { "posthog_project_id": frappe.conf.get(POSTHOG_PROJECT_FIELD), "posthog_host": frappe.conf.get(POSTHOG_HOST_FIELD), "enable_telemetry": frappe.get_system_settings("enable_telemetry"), "telemetry_site_age": frappe.utils.telemetry.site_age(), "record_session": can_record_session, "posthog_identifier": frappe.local.site, } @frappe.whitelist() def get_page_preview_html(page: str, **kwarg) -> str: # to load preview without publishing frappe.form_dict.update(kwarg) renderer = BuilderPageRenderer(path="") renderer.docname = page renderer.doctype = "Builder Page" frappe.flags.show_preview = True frappe.local.no_cache = 1 renderer.init_context() response = renderer.render() page = frappe.get_cached_doc("Builder Page", page) frappe.enqueue_doc( page.doctype, page.name, "generate_page_preview_image", html=str(response.data, "utf-8"), queue="short", ) return response @frappe.whitelist() def upload_builder_asset(): from frappe.handler import upload_file image_file = upload_file() if image_file.file_url.endswith((".png", ".jpeg", ".jpg")) and frappe.get_cached_value( "Builder Settings", None, "auto_convert_images_to_webp" ): convert_to_webp(file_doc=image_file) return image_file @frappe.whitelist() def convert_to_webp(image_url: str | None = None, file_doc: Document | None = None) -> str: """BETA: Convert image to webp format""" CONVERTIBLE_IMAGE_EXTENSIONS = ["png", "jpeg", "jpg"] def can_convert_image(extn): return extn.lower() in CONVERTIBLE_IMAGE_EXTENSIONS def get_extension(filename): return filename.split(".")[-1].lower() def convert_and_save_image(image, path): image.save(path, "WEBP") return path def update_file_doc_with_webp(file_doc, image, extn): webp_path = file_doc.get_full_path().replace(extn, "webp") convert_and_save_image(image, webp_path) delete_file(file_doc.get_full_path()) file_doc.file_url = f"{file_doc.file_url.replace(extn, 'webp')}" file_doc.save() return file_doc.file_url def create_new_webp_file_doc(file_url, image, extn): files = frappe.get_all("File", filters={"file_url": file_url}, fields=["name"], limit=1) if files: _file = frappe.get_doc("File", files[0].name) webp_path = _file.get_full_path().replace(extn, "webp") convert_and_save_image(image, webp_path) new_file = frappe.copy_doc(_file) new_file.file_name = f"{_file.file_name.replace(extn, 'webp')}" new_file.file_url = f"{_file.file_url.replace(extn, 'webp')}" new_file.save() return new_file.file_url return file_url def handle_image_from_url(image_url): image_url = unquote(image_url) response = requests.get(image_url) image = Image.open(BytesIO(response.content)) filename = image_url.split("/")[-1] extn = get_extension(filename) if can_convert_image(extn): _file = frappe.get_doc( { "doctype": "File", "file_name": f"{filename.replace(extn, 'webp')}", "file_url": f"/files/{filename.replace(extn, 'webp')}", } ) webp_path = _file.get_full_path() convert_and_save_image(image, webp_path) _file.save() return _file.file_url return image_url if not image_url and not file_doc: return "" if file_doc: if file_doc.file_url.startswith("/files"): image, filename, extn = get_local_image(file_doc.file_url) if can_convert_image(extn): return update_file_doc_with_webp(file_doc, image, extn) return file_doc.file_url if image_url.startswith("/files"): image, filename, extn = get_local_image(image_url) if can_convert_image(extn): return create_new_webp_file_doc(image_url, image, extn) return image_url if image_url.startswith("/builder_assets"): image_path = os.path.abspath(frappe.get_app_path("builder", "www", image_url.lstrip("/"))) image_path = image_path.replace("_", "-") image_path = image_path.replace("/builder-assets", "/builder_assets") image = Image.open(image_path) extn = get_extension(image_path) if can_convert_image(extn): webp_path = image_path.replace(extn, "webp") convert_and_save_image(image, webp_path) return image_url.replace(extn, "webp") return image_url if image_url.startswith("http"): return handle_image_from_url(image_url) return image_url def check_app_permission(): if frappe.session.user == "Administrator": return True if frappe.has_permission("Builder Page", ptype="write"): return True return False
2302_79757062/builder
builder/api.py
Python
agpl-3.0
6,163
// Copyright (c) 2024, Frappe Technologies Pvt Ltd and contributors // For license information, please see license.txt // frappe.ui.form.on("Block Template", { // refresh(frm) { // }, // });
2302_79757062/builder
builder/builder/doctype/block_template/block_template.js
JavaScript
agpl-3.0
195
# Copyright (c) 2024, Frappe Technologies Pvt Ltd and contributors # For license information, please see license.txt import os import shutil import frappe from frappe import _ from frappe.model.document import Document from frappe.modules import scrub from frappe.modules.export_file import export_to_files from builder.builder.doctype.builder_page.builder_page import get_template_assets_folder_path class BlockTemplate(Document): def on_update(self): if not self.preview: frappe.throw(_("Preview Image is mandatory")) files = frappe.get_all("File", filters={"file_url": self.preview}, fields=["name"]) if files: _file = frappe.get_doc("File", files[0].name) assets_folder_path = get_template_assets_folder_path(self) shutil.copy(_file.get_full_path(), assets_folder_path) self.preview = f"/builder_assets/{self.name}/{self.preview.split('/')[-1]}" self.db_set("preview", self.preview) export_to_files( record_list=[ [ "Block Template", self.name, "builder_block_template", ], ], record_module="builder", ) def on_trash(self): block_template_folder = os.path.join( frappe.get_app_path("builder"), "builder", "builder_block_template", scrub(self.name) ) shutil.rmtree(block_template_folder, ignore_errors=True) assets_folder_path = get_template_assets_folder_path(self) shutil.rmtree(assets_folder_path, ignore_errors=True)
2302_79757062/builder
builder/builder/doctype/block_template/block_template.py
Python
agpl-3.0
1,407
// Copyright (c) 2023, Frappe Technologies Pvt Ltd and contributors // For license information, please see license.txt frappe.ui.form.on("Builder Client Script", { refresh(frm) { frm.trigger("set_editor_options"); }, script_type(frm) { frm.trigger("set_editor_options"); }, set_editor_options(frm) { if (!frm.get_field("script").editor) { return; } if (frm.doc.script_type == "CSS") { frm.get_field("script").editor.session.setMode("ace/mode/css"); } else if (frm.doc.script_type == "JavaScript") { frm.get_field("script").editor.session.setMode("ace/mode/javascript"); } } });
2302_79757062/builder
builder/builder/doctype/builder_client_script/builder_client_script.js
JavaScript
agpl-3.0
608
# Copyright (c) 2023, Frappe Technologies Pvt Ltd and contributors # For license information, please see license.txt import os import frappe from frappe.model.document import Document from frappe.modules.export_file import export_to_files from frappe.utils import get_files_path class BuilderClientScript(Document): def before_insert(self): if not self.name: self.name = f"{self.script_type}-{frappe.generate_hash(length=5)}" self.update_script_file() def on_update(self): self.update_script_file() self.update_exported_script() def on_trash(self): self.delete_script_file() def update_script_file(self): script_type = self.script_type or "" file_name = self.get_file_name_from_url() file_extension = "js" if script_type == "JavaScript" else "css" if not file_name: file_name = f"{self.name.strip()}-{frappe.generate_hash(length=10)}.{file_extension}" folder_name = "page_scripts" if script_type == "JavaScript" else "page_styles" file_path = get_files_path(f"{folder_name}/{file_name}") os.makedirs(os.path.dirname(file_path), exist_ok=True) with open(file_path, "w") as f: f.write(self.script) public_url = f"/files/{folder_name}/{file_name}?v={frappe.generate_hash(length=10)}" self.db_set("public_url", public_url, commit=True) def delete_script_file(self): script_type = self.script_type or "" folder_name = "page_scripts" if script_type == "JavaScript" else "page_styles" file_name = self.get_file_name_from_url() file_path = get_files_path(f"{folder_name}/{file_name}") if os.path.exists(file_path): os.remove(file_path) def get_file_name_from_url(self): public_url = self.public_url or "" if "?" in public_url: public_url = public_url.split("?")[0] return public_url.split("/")[-1] def update_exported_script(self): if not frappe.conf.developer_mode: return script_path = os.path.join( frappe.get_app_path("builder"), "builder", "builder_client_script", self.name ) if os.path.exists(script_path): export_to_files( record_list=[["Builder Client Script", self.name, "builder_client_script"]], record_module="builder", )
2302_79757062/builder
builder/builder/doctype/builder_client_script/builder_client_script.py
Python
agpl-3.0
2,134
// Copyright (c) 2023, asdf and contributors // For license information, please see license.txt // frappe.ui.form.on("Builder Component", { // refresh(frm) { // }, // });
2302_79757062/builder
builder/builder/doctype/builder_component/builder_component.js
JavaScript
agpl-3.0
175
# Copyright (c) 2023, asdf and contributors # For license information, please see license.txt import os import frappe from frappe.model.document import Document from frappe.modules.export_file import export_to_files from frappe.website.utils import clear_website_cache class BuilderComponent(Document): def before_insert(self): if not self.component_id: self.component_id = frappe.generate_hash(length=16) def on_update(self): self.queue_action("clear_page_cache") self.update_exported_component() def clear_page_cache(self): pages = frappe.get_all("Builder Page", filters={"published": 1}, fields=["name"]) for page in pages: page_doc = frappe.get_cached_doc("Builder Page", page.name) if page_doc.is_component_used(self.component_id): clear_website_cache(page_doc.route) def update_exported_component(self): if not frappe.conf.developer_mode: return component_path = os.path.join( frappe.get_app_path("builder"), "builder", "builder_component", self.name ) if os.path.exists(component_path): export_to_files( record_list=[["Builder Component", self.name, "builder_component"]], record_module="builder", )
2302_79757062/builder
builder/builder/doctype/builder_component/builder_component.py
Python
agpl-3.0
1,169
import frappe def execute(): """Set Component ID""" component_list = frappe.get_all("Builder Component") for component in component_list: component_doc = frappe.get_doc("Builder Component", component) component_doc.component_id = component_doc.name component_doc.db_set("component_id", component_doc.name, update_modified=False)
2302_79757062/builder
builder/builder/doctype/builder_component/patches/set_component_id.py
Python
agpl-3.0
340
// Copyright (c) 2023, asdf and contributors // For license information, please see license.txt frappe.ui.form.on("Builder Page", { refresh(frm) { // only show in developer mode if (frappe.boot.developer_mode || !frm.doc.is_template) { frm.sidebar .add_user_action(__("Open in Builder")) .attr("href", `/${frm.doc.__onload.builder_path}/page/${frm.doc.name}`) .attr("target", "_blank"); } }, onload(frm) { frm.set_df_property("blocks", "wrap", true); frm.set_df_property("draft_blocks", "wrap", true); }, set_meta_tags(frm) { frappe.utils.set_meta_tag(frm.doc.route); }, });
2302_79757062/builder
builder/builder/doctype/builder_page/builder_page.js
JavaScript
agpl-3.0
642
# Copyright (c) 2023, asdf and contributors # For license information, please see license.txt import os import shutil import bs4 as bs import frappe import frappe.utils from frappe.modules import scrub from frappe.modules.export_file import export_to_files from frappe.utils.caching import redis_cache from frappe.utils.jinja import render_template from frappe.utils.safe_exec import is_safe_exec_enabled, safe_exec from frappe.website.page_renderers.document_page import DocumentPage from frappe.website.path_resolver import evaluate_dynamic_routes from frappe.website.path_resolver import resolve_path as original_resolve_path from frappe.website.serve import get_response_content from frappe.website.utils import clear_cache from frappe.website.website_generator import WebsiteGenerator from jinja2.exceptions import TemplateSyntaxError from werkzeug.routing import Rule from builder.hooks import builder_path from builder.html_preview_image import generate_preview from builder.utils import ( camel_case_to_kebab_case, copy_img_to_asset_folder, escape_single_quotes, execute_script, get_builder_page_preview_paths, get_template_assets_folder_path, is_component_used, ) MOBILE_BREAKPOINT = 576 TABLET_BREAKPOINT = 768 DESKTOP_BREAKPOINT = 1024 class BuilderPageRenderer(DocumentPage): def can_render(self): if page := find_page_with_path(self.path): self.doctype = "Builder Page" self.docname = page return True for d in get_web_pages_with_dynamic_routes(): if evaluate_dynamic_routes([Rule(f"/{d.route}", endpoint=d.name)], self.path): self.doctype = "Builder Page" self.docname = d.name return True return False class BuilderPage(WebsiteGenerator): def onload(self): self.set_onload("builder_path", builder_path) website = frappe._dict( template="templates/generators/webpage.html", condition_field="published", page_title_field="page_title", ) def autoname(self): if not self.name: self.name = f"page-{frappe.generate_hash(length=8)}" def before_insert(self): if isinstance(self.blocks, list): self.blocks = frappe.as_json(self.blocks, indent=None) if isinstance(self.draft_blocks, list): self.draft_blocks = frappe.as_json(self.draft_blocks, indent=None) if not self.blocks: self.blocks = "[]" if self.preview: self.flags.skip_preview = True else: self.preview = "/assets/builder/images/fallback.png" if not self.page_title: self.page_title = "My Page" if not self.route: self.route = f"pages/{self.name}" def on_update(self): if ( self.has_value_changed("dynamic_route") or self.has_value_changed("route") or self.has_value_changed("published") ): self.clear_route_cache() if self.has_value_changed("published") and not self.published: # if this is homepage then clear homepage from builder settings if frappe.get_cached_value("Builder Settings", None, "home_page") == self.route: frappe.db.set_value("Builder Settings", None, "home_page", None) if frappe.conf.developer_mode and self.is_template: save_as_template(self) def clear_route_cache(self): get_web_pages_with_dynamic_routes.clear_cache() find_page_with_path.clear_cache() clear_cache(self.route) def on_trash(self): if self.is_template and frappe.conf.developer_mode: page_template_folder = os.path.join( frappe.get_app_path("builder"), "builder", "builder_page_template", scrub(self.name) ) if os.path.exists(page_template_folder): shutil.rmtree(page_template_folder) assets_path = get_template_assets_folder_path(self) if os.path.exists(assets_path): shutil.rmtree(assets_path) def add_comment(self, comment_type="Comment", text=None, comment_email=None, comment_by=None): if comment_type in ["Attachment Removed", "Attachment"]: return super().add_comment( comment_type=comment_type, text=text, comment_email=comment_email, comment_by=comment_by, ) @frappe.whitelist() def publish(self, **kwargs): frappe.form_dict.update(kwargs) self.published = 1 if self.draft_blocks: self.blocks = self.draft_blocks self.draft_blocks = None self.save() frappe.enqueue_doc( self.doctype, self.name, "generate_page_preview_image", queue="short", ) return self.route @frappe.whitelist() def unpublish(self, **kwargs): self.published = 0 self.save() def get_context(self, context): # delete default favicon del context.favicon page_data = self.get_page_data() if page_data.get("title"): context.title = page_data.get("page_title") blocks = self.blocks context.preview = frappe.flags.show_preview if self.dynamic_route or page_data: context.no_cache = 1 if frappe.flags.show_preview and self.draft_blocks: blocks = self.draft_blocks content, style, fonts = get_block_html(blocks) context.fonts = fonts context.content = content context.style = render_template(style, page_data) context.editor_link = f"/{builder_path}/page/{self.name}" if self.dynamic_route and hasattr(frappe.local, "request"): context.base_url = frappe.utils.get_url(frappe.local.request.path or self.route) else: context.base_url = frappe.utils.get_url(self.route) self.set_style_and_script(context) context.update(page_data) self.set_meta_tags(context=context, page_data=page_data) self.set_favicon(context) try: context["content"] = render_template(context.content, context) except TemplateSyntaxError: raise def set_meta_tags(self, context, page_data=None): if not page_data: page_data = {} metatags = { "title": self.page_title or "My Page", "description": self.meta_description or self.page_title, "image": self.meta_image or self.preview, } metatags.update(page_data.get("metatags", {})) context.metatags = metatags def set_favicon(self, context): if not context.get("favicon"): context.favicon = self.favicon if not context.get("favicon"): context.favicon = frappe.get_cached_value("Builder Settings", None, "favicon") def is_component_used(self, component_id): if self.blocks and is_component_used(self.blocks, component_id): return True elif self.draft_blocks and is_component_used(self.draft_blocks, component_id): return True def set_style_and_script(self, context): for script in self.get("client_scripts", []): script_doc = frappe.get_cached_doc("Builder Client Script", script.builder_script) if script_doc.script_type == "JavaScript": context.setdefault("scripts", []).append(script_doc.public_url) else: context.setdefault("styles", []).append(script_doc.public_url) builder_settings = frappe.get_cached_doc("Builder Settings", "Builder Settings") if builder_settings.script: context.setdefault("scripts", []).append(builder_settings.script_public_url) if builder_settings.style: context.setdefault("styles", []).append(builder_settings.style_public_url) @frappe.whitelist() def get_page_data(self, args=None): if args: args = frappe.parse_json(args) frappe.form_dict.update(args) page_data = frappe._dict() if self.page_data_script: _locals = dict(data=frappe._dict()) execute_script(self.page_data_script, _locals, self.name) page_data.update(_locals["data"]) return page_data def generate_page_preview_image(self, html=None): public_path, local_path = get_builder_page_preview_paths(self) generate_preview( html or get_response_content(self.route), local_path, ) self.db_set("preview", public_path, commit=True, update_modified=False) def save_as_template(page_doc: BuilderPage): # move all assets to www/builder_assets/{page_name} if page_doc.draft_blocks: page_doc.publish() if not page_doc.template_name: page_doc.template_name = page_doc.page_title blocks = frappe.parse_json(page_doc.blocks) for block in blocks: copy_img_to_asset_folder(block, page_doc) page_doc.db_set("draft_blocks", None) page_doc.db_set("blocks", frappe.as_json(blocks, indent=None)) page_doc.reload() export_to_files( record_list=[["Builder Page", page_doc.name, "builder_page_template"]], record_module="builder" ) components = set() def get_component(block): if block.get("extendedFromComponent"): component = block.get("extendedFromComponent") components.add(component) # export nested components as well component_doc = frappe.get_cached_doc("Builder Component", component) if component_doc.block: component_block = frappe.parse_json(component_doc.block) get_component(component_block) for child in block.get("children", []): get_component(child) for block in blocks: get_component(block) if components: export_to_files( record_list=[["Builder Component", c, "builder_component"] for c in components], record_module="builder", ) scripts = frappe.get_all( "Builder Page Client Script", filters={"parent": page_doc.name}, fields=["name", "builder_script"], ) if scripts: export_to_files( record_list=[ ["Builder Client Script", s.builder_script, "builder_client_script"] for s in scripts ], record_module="builder", ) def get_block_html(blocks): blocks = frappe.parse_json(blocks) if not isinstance(blocks, list): blocks = [blocks] soup = bs.BeautifulSoup("", "html.parser") style_tag = soup.new_tag("style") font_map = {} def get_html(blocks, soup): html = "" def get_tag(block, soup, data_key=None): block = extend_with_component(block) set_dynamic_content_placeholder(block, data_key) element = block.get("originalElement") or block.get("element") if not element: return "" classes = block.get("classes", []) if element in ( "span", "h1", "p", "b", "h2", "h3", "h4", "h5", "h6", "label", "a", ): classes.insert(0, "__text_block__") # temp fix: since p inside p is illegal if element in ["p", "__raw_html__"]: element = "div" tag = soup.new_tag(element) tag.attrs = block.get("attributes", {}) customAttributes = block.get("customAttributes", {}) if customAttributes: for key, value in customAttributes.items(): tag[key] = value if block.get("baseStyles", {}): style_class = f"fb-{frappe.generate_hash(length=8)}" base_styles = block.get("baseStyles", {}) mobile_styles = block.get("mobileStyles", {}) tablet_styles = block.get("tabletStyles", {}) set_fonts([base_styles, mobile_styles, tablet_styles], font_map) append_style(block.get("baseStyles", {}), style_tag, style_class) plain_styles = {k: v for k, v in block.get("rawStyles", {}).items() if ":" not in k} state_styles = {k: v for k, v in block.get("rawStyles", {}).items() if ":" in k} append_style(plain_styles, style_tag, style_class) append_state_style(state_styles, style_tag, style_class) append_style( block.get("tabletStyles", {}), style_tag, style_class, device="tablet", ) append_style( block.get("mobileStyles", {}), style_tag, style_class, device="mobile", ) classes.insert(0, style_class) tag.attrs["class"] = " ".join(classes) innerContent = block.get("innerHTML") if innerContent: inner_soup = bs.BeautifulSoup(innerContent, "html.parser") set_fonts_from_html(inner_soup, font_map) tag.append(inner_soup) if block.get("isRepeaterBlock") and block.get("children") and block.get("dataKey"): _key = block.get("dataKey").get("key") if data_key: _key = f"{data_key}.{_key}" item_key = f"key_{block.get('blockId')}" tag.append(f"{{% for {item_key} in {_key} %}}") tag.append(get_tag(block.get("children")[0], soup, item_key)) tag.append("{% endfor %}") else: for child in block.get("children", []): if child.get("visibilityCondition"): key = child.get("visibilityCondition") if data_key: key = f"{data_key}.{key}" tag.append(f"{{% if {key} %}}") tag.append(get_tag(child, soup, data_key=data_key)) if child.get("visibilityCondition"): tag.append("{% endif %}") if element == "body": tag.append("{% include 'templates/generators/webpage_scripts.html' %}") return tag for block in blocks: html += str(get_tag(block, soup)) return html, str(style_tag), font_map data = get_html(blocks, soup) return data def get_style(style_obj): return ( "".join( f"{camel_case_to_kebab_case(key)}: {value};" for key, value in style_obj.items() if value is not None and value != "" and not key.startswith("__") ) if style_obj else "" ) def append_style(style_obj, style_tag, style_class, device="desktop"): style = get_style(style_obj) if not style: return style_string = f".{style_class} {{ {style} }}" if device == "mobile": style_string = f"@media only screen and (max-width: {MOBILE_BREAKPOINT}px) {{ {style_string} }}" elif device == "tablet": style_string = f"@media only screen and (max-width: {DESKTOP_BREAKPOINT - 1}px) {{ {style_string} }}" style_tag.append(style_string) def append_state_style(style_obj, style_tag, style_class): for key, value in style_obj.items(): state, property = key.split(":", 1) style_tag.append(f".{style_class}:{state} {{ {property}: {value} }}") def set_fonts(styles, font_map): for style in styles: font = style.get("fontFamily") if font: if font in font_map: if style.get("fontWeight") and style.get("fontWeight") not in font_map[font]["weights"]: font_map[font]["weights"].append(style.get("fontWeight")) font_map[font]["weights"].sort() else: font_map[font] = {"weights": [style.get("fontWeight") or "400"]} def set_fonts_from_html(soup, font_map): # get font-family from inline styles for tag in soup.find_all(style=True): styles = tag.attrs.get("style").split(";") for style in styles: if "font-family" in style: font = style.split(":")[1].strip() if font: font_map[font] = {"weights": ["400"]} def extend_with_component(block): if block.get("extendedFromComponent"): component = frappe.get_cached_value( "Builder Component", block["extendedFromComponent"], ["block", "name"], as_dict=True, ) component_block = frappe.parse_json(component.block if component else "{}") if component_block: extend_block(component_block, block) block = component_block return block def extend_block(block, overridden_block): block["baseStyles"].update(overridden_block["baseStyles"]) block["mobileStyles"].update(overridden_block["mobileStyles"]) block["tabletStyles"].update(overridden_block["tabletStyles"]) block["attributes"].update(overridden_block["attributes"]) if overridden_block.get("visibilityCondition"): block["visibilityCondition"] = overridden_block.get("visibilityCondition") if not block.get("customAttributes"): block["customAttributes"] = {} block["customAttributes"].update(overridden_block.get("customAttributes", {})) if not block.get("rawStyles"): block["rawStyles"] = {} block["rawStyles"].update(overridden_block.get("rawStyles", {})) block["classes"].extend(overridden_block["classes"]) dataKey = overridden_block.get("dataKey", {}) if not block.get("dataKey"): block["dataKey"] = {} if dataKey: block["dataKey"].update({k: v for k, v in dataKey.items() if v is not None}) if overridden_block.get("innerHTML"): block["innerHTML"] = overridden_block["innerHTML"] component_children = block.get("children", []) overridden_children = overridden_block.get("children", []) for overridden_child in overridden_children: component_child = next( ( child for child in component_children if child.get("blockId") in [ overridden_child.get("blockId"), overridden_child.get("referenceBlockId"), ] ), None, ) if component_child: extend_block(component_child, overridden_child) else: component_children.insert(overridden_children.index(overridden_child), overridden_child) def set_dynamic_content_placeholder(block, data_key=False): block_data_key = block.get("dataKey") if block_data_key and block_data_key.get("key"): key = f"{data_key}.{block_data_key.get('key')}" if data_key else block_data_key.get("key") if data_key: # convert a.b to (a or {}).get('b', {}) # to avoid undefined error in jinja keys = key.split(".") key = f"({keys[0]} or {{}})" for k in keys[1:]: key = f"{key}.get('{k}', {{}})" _property = block_data_key.get("property") _type = block_data_key.get("type") if _type == "attribute": block["attributes"][ _property ] = f"{{{{ {key} or '{escape_single_quotes(block['attributes'].get(_property, ''))}' }}}}" elif _type == "style": block["baseStyles"][ _property ] = f"{{{{ {key} or '{escape_single_quotes(block['baseStyles'].get(_property, ''))}' }}}}" elif _type == "key" and not block.get("isRepeaterBlock"): block[_property] = f"{{{{ {key} or '{escape_single_quotes(block.get(_property, ''))}' }}}}" @redis_cache(ttl=60 * 60) def find_page_with_path(route): try: return frappe.db.get_value("Builder Page", dict(route=route, published=1), "name", cache=True) except frappe.DoesNotExistError: pass @redis_cache(ttl=60 * 60) def get_web_pages_with_dynamic_routes() -> dict[str, str]: return frappe.get_all( "Builder Page", fields=["name", "route", "modified"], filters=dict(published=1, dynamic_route=1), update={"doctype": "Builder Page"}, ) def resolve_path(path): if find_page_with_path(path): return path elif evaluate_dynamic_routes( [Rule(f"/{d.route}", endpoint=d.name) for d in get_web_pages_with_dynamic_routes()], path, ): return path return original_resolve_path(path)
2302_79757062/builder
builder/builder/doctype/builder_page/builder_page.py
Python
agpl-3.0
17,624
import frappe def execute(): """Attach Client Script to Builder Page""" for builder_page in frappe.db.sql("""select name, client_script, style from `tabBuilder Page`""", as_dict=True): if builder_page.client_script: script_doc = get_or_create_builder_script("Builder Client Script", builder_page.client_script, "JavaScript") create_builder_page_client_script(builder_page.name, script_doc.name) elif builder_page.style: style_doc = get_or_create_builder_script("Builder Client Script", builder_page.style, "CSS") create_builder_page_client_script(builder_page.name, style_doc.name) def get_or_create_builder_script(doctype, script, script_type): script_name = frappe.db.exists(doctype, {"script": script}) if script_name: return frappe.get_doc(doctype, script_name) else: return frappe.get_doc({ "doctype": doctype, "script_type": script_type, "script": script }).insert(ignore_permissions=True) def create_builder_page_client_script(parent, builder_script, parentfield="client_scripts", parenttype="Builder Page"): frappe.get_doc({ "doctype": "Builder Page Client Script", "parent": parent, "builder_script": builder_script, "parentfield": parentfield, "parenttype": parenttype }).insert(ignore_permissions=True)
2302_79757062/builder
builder/builder/doctype/builder_page/patches/attach_client_script_to_builder_page.py
Python
agpl-3.0
1,265
import frappe from frappe.core.api.file import create_new_folder def execute(): """create upload folder for builder""" create_new_folder("Builder Uploads", "Home")
2302_79757062/builder
builder/builder/doctype/builder_page/patches/create_upload_folder_for_builder.py
Python
agpl-3.0
167
import frappe def execute(): frappe.db.set_value("Builder Settings", None, "auto_convert_images_to_webp", 1, update_modified=False)
2302_79757062/builder
builder/builder/doctype/builder_page/patches/enable_auto_convert_to_webp_by_default.py
Python
agpl-3.0
135
import frappe def execute(): """Properly extend blocks from component""" web_pages = frappe.get_all("Builder Page", fields=["name", "blocks"]) for web_page in web_pages: blocks = frappe.parse_json(web_page.blocks) if blocks: update_blocks(blocks) frappe.db.set_value("Builder Page", web_page.name, "blocks", frappe.as_json(blocks, indent=None), update_modified=False) draft_blocks = frappe.parse_json(web_page.draft_blocks) if draft_blocks: update_blocks(draft_blocks) frappe.db.set_value("Builder Page", web_page.name, "draft_blocks", frappe.as_json(blocks, indent=None), update_modified=False) def update_blocks(blocks): for block in blocks: block["baseStyles"] = convert_dict_keys_to_camel_case(block.get("baseStyles", {})) block["tabletStyles"] = convert_dict_keys_to_camel_case(block.get("tabletStyles", {})) block["mobileStyles"] = convert_dict_keys_to_camel_case(block.get("mobileStyles", {})) if block.get("extendedFromComponent"): try: component = frappe.get_cached_doc("Builder Component", block.get("extendedFromComponent")) component_block = frappe.parse_json(component.get("block")) update_blocks([component_block]) frappe.db.set_value("Builder Component", component.name, "block", frappe.as_json(component_block, indent=None), update_modified=False) extend_block_from_component(block, component.name, component_block.get("children"), component_block) except frappe.DoesNotExistError: frappe.log_error(f"Builder Component {block.get('extendedFromComponent')} not found") if "children" in block: update_blocks(block["children"]) def extend_block_from_component(block, extended_from_component, children, component_block): block["blockId"] = generate_id() block["baseStyles"] = get_dict_difference(component_block["baseStyles"], block["baseStyles"]) block["mobileStyles"] = get_dict_difference(component_block["mobileStyles"], block["mobileStyles"]) block["tabletStyles"] = get_dict_difference(component_block["tabletStyles"], block["tabletStyles"]) block["attributes"] = get_dict_difference(component_block["attributes"], block["attributes"]) if block.get('innerHTML') and block.get('innerHTML') == component_block.get('innerHTML'): del block['innerHTML'] if block.get('element') and block.get('element') == component_block.get('element'): del block['element'] if "children" in block: for index, child in enumerate(block["children"]): child["isChildOfComponent"] = extended_from_component if children and index < len(children): if component_child := children[index]: child["referenceBlockId"] = component_child["blockId"] extend_block_from_component(child, extended_from_component, component_child["children"], component_child) def generate_id(): return frappe.generate_hash("", 10) def get_dict_difference(dict_1, dict_2): dict_1 = convert_dict_keys_to_camel_case(dict_1) dict_2 = convert_dict_keys_to_camel_case(dict_2) return {key: dict_2[key] for key in dict_2 if key not in dict_1 or dict_1[key] != dict_2[key]} def convert_dict_keys_to_camel_case(dict_): sorted_keys = sorted(dict_.keys(), key=lambda x: x.islower()) sorted_dict = {key: dict_[key] for key in sorted_keys} return { kebab_to_camel_case(key): value for key, value in sorted_dict.items() } def kebab_to_camel_case(string): # font-size -> fontSize # height -> height return "".join( word.capitalize() if index > 0 else word for index, word in enumerate(string.split("-")) )
2302_79757062/builder
builder/builder/doctype/builder_page/patches/properly_extend_blocks_from_component.py
Python
agpl-3.0
3,485