Skip to content

Commit

Permalink
Improve preview table (#58)
Browse files Browse the repository at this point in the history
* Fixed preview table caching and only show 10 model elements if there are more available.

* Add do you want to save dialog to TemplateForm
  • Loading branch information
wolflu05 authored Sep 15, 2023
1 parent 0541fcf commit 55267c5
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 8 deletions.
22 changes: 19 additions & 3 deletions inventree_bulk_plugin/frontend/src/components/PreviewTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { URLS, fetchAPI } from "../utils/api";
import { customModelProcessors } from "../utils/customModelProcessors";
import { BulkGenerateInfo, FieldDefinition, FieldType, TemplateModel } from "../utils/types";

const MODEL_LIMIT = 10;
interface PreviewTableProps {
template: TemplateModel;
height?: number;
Expand Down Expand Up @@ -75,8 +76,23 @@ export const PreviewTable = ({ template, height, parentId, bulkGenerateInfo }: P
return `${renderModelData("", modelName, f, {})} <span>(${f.pk})</span>`;
};

const count = field.count;
if (fieldDefinition.allow_multiple && field.results) field = field.results;
if (fieldDefinition.allow_multiple && Array.isArray(field)) {
return `<li>${field.map(renderOne).join("</li><li>")}</li>`;
// render ... if there are more fields available
let hasMore = false;
let extraText = "";
if (count === undefined) {
hasMore = count > field.length;
extraText = `${count - field.length} more elements`;
} else if (field.length >= MODEL_LIMIT) {
field.pop(); // remove one element so that the ... is real
hasMore = true;
extraText = `at least one more element`;
}

const renderedElements = `<li>${field.map(renderOne).join("</li><li>")}</li>`;
return `${renderedElements}${hasMore ? `<li>... ${extraText}</li>` : ""}`;
}
return renderOne(field);
})();
Expand All @@ -99,7 +115,6 @@ export const PreviewTable = ({ template, height, parentId, bulkGenerateInfo }: P
}
cache[cacheKey].push(handleSuccess);
} else {
const cacheKey = `~get-api-${JSON.stringify(value)}`;
let urlPath = `${value}/`;
let filters = { ...fieldDefinition.model.limit_choices_to };

Expand All @@ -112,7 +127,8 @@ export const PreviewTable = ({ template, height, parentId, bulkGenerateInfo }: P
if ("name" in filters) filters.search = filters.name;
}

const url = `${fieldDefinition.model.api_url}/${urlPath}`.replace("//", "/");
const url = `${fieldDefinition.model.api_url}/${urlPath}?limit=${MODEL_LIMIT}`.replace("//", "/");
const cacheKey = `~get-api-${url}-${JSON.stringify(value)}`;

if (!cache[cacheKey]) {
cache[cacheKey] = [];
Expand Down
40 changes: 35 additions & 5 deletions inventree_bulk_plugin/frontend/src/components/TemplateForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ export const TemplateForm = ({
}, [loadTemplate]);

const saveOrUpdate = useCallback(async () => {
if (!template) return;
if (!template) return false;

const res = await fetchAPI(URLS.templates({ id: isCreate ? null : template.id }), {
method: isCreate ? "POST" : "PUT",
Expand All @@ -125,13 +125,14 @@ export const TemplateForm = ({
const data = await res.json();

if (!res.ok) {
return showNotification({
showNotification({
type: "danger",
message: `An error occurred. ${Object.entries(data as Record<string, string[]>)
.map(([key, v]) => `${key}: ${v.join(", ")}`)
.join(", ")}`,
autoHide: false,
});
return false;
}

if (isCreate) {
Expand All @@ -143,6 +144,7 @@ export const TemplateForm = ({
}

setInitialTemplate(structuredClone(template));
return true;
}, [isCreate, showNotification, template]);

const handleReset = useCallback(() => setTemplate(structuredClone(initialTemplate)), [initialTemplate]);
Expand Down Expand Up @@ -211,6 +213,8 @@ export const TemplateForm = ({
);
}, [showNotification, template?.name, template?.template, template?.template_type]);

const [showSaveTemplateDialog, setShowSaveTemplateDialog] = useState(false);

return (
<div>
<h5>
Expand Down Expand Up @@ -248,9 +252,8 @@ export const TemplateForm = ({

<div class="d-flex mt-2" style="gap: 5px">
<button
class={`btn ${hasChanged && !isCreate ? "btn-outline-secondary" : "btn-outline-primary"}`}
onClick={handleBack}
disabled={hasChanged && !isCreate}
class={`btn btn-outline-primary`}
onClick={() => (hasChanged ? setShowSaveTemplateDialog(true) : handleBack())}
>
Back
</button>
Expand Down Expand Up @@ -315,6 +318,33 @@ export const TemplateForm = ({
Are you sure you want to bulk generate{" "}
{bulkGenerateInfoDict[template?.template_type || ""]?.name || template?.template_type}s here?
</Dialog>

<Dialog
title="Save the template"
show={showSaveTemplateDialog}
onClose={() => setShowSaveTemplateDialog(false)}
actions={[
{
label: "Don't save",
type: "outline-danger",
onClick: handleBack,
},
{
label: "Save",
type: "primary",
onClick: () => {
saveOrUpdate().then((r) => {
setShowSaveTemplateDialog(false);
if (r === true) {
handleBack();
}
});
},
},
]}
>
Do you want to save the template?
</Dialog>
</div>
);
};

0 comments on commit 55267c5

Please sign in to comment.