Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: export more params and format #112

Closed
wants to merge 16 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
316 changes: 273 additions & 43 deletions src/components/gui/export/export-result-button.tsx
Original file line number Diff line number Diff line change
@@ -1,77 +1,307 @@
import { Button, buttonVariants } from "../../ui/button";
import { Popover, PopoverContent, PopoverTrigger } from "../../ui/popover";
import {
Select,
SelectContent,
SelectItem,
SelectSeparator,
SelectTrigger,
SelectValue,
} from "../../ui/select";
import OptimizeTableState from "../table-optimized/OptimizeTableState";
import { useCallback, useState } from "react";
import type OptimizeTableState from "../table-optimized/OptimizeTableState";
import { type ChangeEvent, useCallback, useState } from "react";
import { getFormatHandlers } from "@/components/lib/export-helper";
import {
Dialog,
DialogTrigger,
DialogContent,
DialogTitle,
DialogFooter,
} from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { cn } from "@/lib/utils";
import { Input } from "@/components/ui/input";
import { toast } from "sonner";

export default function ExportResultButton({
data,
}: {
data: OptimizeTableState;
}) {
const [format, setFormat] = useState<string | null>(null);
const [format, setFormat] = useState<string>("sql");

//do we want to make them something like this or just string?
// is we use the as const , where should i move it to?

const OutputTargetType = {
File: "file",
Clipboard: "clipboard",
} as const;

type OutputTargetType =
(typeof OutputTargetType)[keyof typeof OutputTargetType];

const ExportSelectionType = {
Complete: "complete",
Selected: "selected",
} as const;

type ExportSelectionType =
(typeof ExportSelectionType)[keyof typeof ExportSelectionType];

const [exportSelection, setExportSelection] = useState<ExportSelectionType>(
ExportSelectionType.Complete
);

const [outputTarget, setOutputTarget] = useState<OutputTargetType>(
OutputTargetType.File
);

const [tableName, setTableName] = useState<string>("UnknownTable");

const [cellTextLimit, setCellTextLimit] = useState<number | undefined>(50);

const [batchSize, setBatchSize] = useState<number | undefined>(1);

const onExportClicked = useCallback(() => {
if (!format) return;

let content = "";
const headers = data.getHeaders().map((header) => header.name);
const records = data
.getAllRows()
const records = (
exportSelection === ExportSelectionType.Complete
? data.getAllRows()
: data.getSelectedRows()
) // i need more instruction on how to do this getSelectedRows
.map((row) => headers.map((header) => row.raw[header]));

const tableName = "UnknownTable"; //TODO: replace with actual table name

const formatHandlers = getFormatHandlers(records, headers, tableName);
const exportTableName = tableName.trim() || "UnknownTable";
const formatHandlers = getFormatHandlers(
records,
headers,
exportTableName,
cellTextLimit ?? 50,
batchSize ?? 1
);

const handler = formatHandlers[format];
if (handler) {
content = handler();
if (!handler) return;

const content = handler();

//should we move this to a seperate function by now?
if (outputTarget === OutputTargetType.File) {
const blob = new Blob([content], { type: "text/plain;charset=utf-8" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = `export.${format}`;
a.click();
URL.revokeObjectURL(url);
} else {
navigator.clipboard
.writeText(content)
.then(() => toast.success("Content copied to clipboard"))
.catch((err) => {
toast.error("Failed to copy content to clipboard");
console.error("Failed to copy content: ", err);
});
}
}, [
format,
data,
exportSelection,
ExportSelectionType.Complete,
tableName,
cellTextLimit,
batchSize,
outputTarget,
OutputTargetType.File,
]);

const handleCellTextLimitChange = (e: ChangeEvent<HTMLInputElement>) => {
const value = e.target.value;

if (value === "") {
setCellTextLimit(undefined);
return;
}

const blob = new Blob([content], { type: "text/plain;charset=utf-8" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = `export.${format}`;
a.click();
URL.revokeObjectURL(url);
}, [format, data]);
const parsedValue = Number.parseInt(value, 10);
setCellTextLimit(Number.isNaN(parsedValue) ? undefined : parsedValue);
};

const handleBatchSizeChange = (e: ChangeEvent<HTMLInputElement>) => {
const value = e.target.value;

if (value === "") {
setBatchSize(undefined);
return;
}

const parsedValue = Number.parseInt(value, 10);
if (!Number.isNaN(parsedValue) && parsedValue > 0) {
setBatchSize(parsedValue);
}
};

return (
<Popover>
<PopoverTrigger>
<Dialog open>
<DialogTrigger>
<div className={buttonVariants({ variant: "ghost", size: "sm" })}>
Export
</div>
</PopoverTrigger>
<PopoverContent className="p-0">
<div className="p-4">
<div className="mb-2 font-bold">Export</div>
<Select onValueChange={setFormat}>
<SelectTrigger>
<SelectValue placeholder="Select export format" />
</SelectTrigger>
<SelectContent>
<SelectItem value="csv">CSV</SelectItem>
<SelectItem value="json">JSON</SelectItem>
<SelectItem value="sql">SQL</SelectItem>
</SelectContent>
</Select>
</div>
<div className="p-2 pt-0 px-4">
<Button size="sm" onClick={onExportClicked}>
Export
</Button>
</DialogTrigger>
<DialogContent className="p-0">
<DialogTitle className="p-4">Export</DialogTitle>

<div className="flex flex-col gap-4">
<div className="px-4 flex flex-col gap-4">
<Label>Output Format</Label>
<Select onValueChange={setFormat} value={format}>
<SelectTrigger>
<SelectValue placeholder="Select export format" />
</SelectTrigger>
<SelectContent>
<SelectItem value="sql">SQL</SelectItem>
<SelectItem value="csv">CSV</SelectItem>
<SelectItem value="json">JSON</SelectItem>
<SelectSeparator />
<SelectItem value="markdown">Markdown Table</SelectItem>
<SelectItem value="ascii">Ascii Table</SelectItem>
</SelectContent>
</Select>

<div className="flex gap-2">
<div
className={cn(
buttonVariants({
variant:
exportSelection === ExportSelectionType.Complete
? "default"
: "outline",
}),
"h-auto items-start cursor-pointer"
)}
onClick={() => setExportSelection(ExportSelectionType.Complete)}
>
<div>
<div>Complete</div>
<div className="text-xs">{data.getAllRows().length} rows</div>
</div>
</div>

<div
className={cn(
buttonVariants({
variant:
exportSelection === ExportSelectionType.Selected
? "default"
: "outline",
}),
"h-auto items-start cursor-pointer"
)}
onClick={() => setExportSelection(ExportSelectionType.Selected)}
>
<div>
<div>Selected</div>
<div className="text-xs">
{data.getSelectedRows().length} rows
</div>
</div>
</div>
</div>
</div>

{format === "sql" && (
<div className="px-4 flex flex-col gap-2 border-t pt-3">
<Label>Additional Parameters</Label>

<div className="flex gap-2 mt-2">
<div className="flex flex-col gap-1 flex-grow">
<span className="text-xs">Table Name</span>
<Input
value={tableName}
onChange={(e) => setTableName(e.target.value)}
placeholder="UnknownTable"
/>
</div>
<div className="flex flex-col gap-1">
<span className="text-xs">Batch Size</span>
<Input
type="number"
value={batchSize ?? ""}
onChange={handleBatchSizeChange}
placeholder="1"
/>
</div>
</div>
</div>
)}

{format === "markdown" && (
<div className="px-4 flex flex-col gap-2 border-t pt-3">
<Label>Additional Parameters</Label>

<div className="flex gap-2 mt-2">
<div className="flex flex-col gap-1 flex-grow">
<span className="text-xs">Cell Text Limit</span>
<Input
type="number"
placeholder="50"
value={cellTextLimit ?? ""}
onChange={handleCellTextLimitChange}
/>
</div>
</div>
</div>
)}

{format === "ascii" && (
<div className="px-4 flex flex-col gap-2 border-t pt-3">
<Label>Additional Parameters</Label>

<div className="flex gap-2 mt-2">
<div className="flex flex-col gap-1 flex-grow">
<span className="text-xs">Cell Text Limit</span>
<Input
type="number"
placeholder="50"
value={cellTextLimit ?? ""}
onChange={handleCellTextLimitChange}
/>
</div>
</div>
</div>
)}

<div className="px-4 flex flex-col gap-4 border-t pt-3">
<Label>Output Target</Label>
<div className="flex gap-2">
<Button
variant={
outputTarget === OutputTargetType.File ? "default" : "outline"
}
onClick={() => setOutputTarget(OutputTargetType.File)}
>
File
</Button>
<Button
variant={
outputTarget === OutputTargetType.Clipboard
? "default"
: "outline"
}
onClick={() => setOutputTarget(OutputTargetType.Clipboard)}
>
Clipboard
</Button>
</div>
</div>
</div>
</PopoverContent>
</Popover>

<DialogFooter className="p-4 border-t">
<Button onClick={onExportClicked}>Export</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
4 changes: 4 additions & 0 deletions src/components/gui/table-optimized/OptimizeTableState.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -481,6 +481,10 @@ export default class OptimizeTableState {
return Array.from(this.selectedRows.values());
}

getSelectedRows(): OptimizeTableRowValue[] {
return this.data.filter((row, index) => this.selectedRows.has(index));
}

selectRow(y: number, toggle?: boolean) {
if (toggle) {
if (this.selectedRows.has(y)) {
Expand Down
4 changes: 3 additions & 1 deletion src/components/gui/table-result/context-menu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export default function useTableResultContextMenu({
}) {
const { openEditor } = useFullEditor();
const { extensions } = useConfig();
const batchSize: number = 1;

return useCallback(
({
Expand Down Expand Up @@ -207,7 +208,8 @@ export default function useTableResultContextMenu({
exportRowsToSqlInsert(
tableName ?? "UnknownTable",
headers,
state.getSelectedRowsArray()
state.getSelectedRowsArray(),
batchSize
)
);
}
Expand Down
Loading
Loading