Skip to content

Commit

Permalink
Improve libraries table row actions management
Browse files Browse the repository at this point in the history
  • Loading branch information
nas-tabchiche committed Apr 29, 2024
1 parent a52a555 commit 0e4dd16
Show file tree
Hide file tree
Showing 6 changed files with 54 additions and 121 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
}
</script>

{#if !library.is_imported}
{#if Object.hasOwn(library, 'is_imported') && !library.is_imported}
{#if loading.form && loading.library === library.urn}
<div class="flex items-center cursor-progress" role="status">
<svg
Expand Down
15 changes: 7 additions & 8 deletions frontend/src/lib/components/ModelTable/ModelTable.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,6 @@
export let deleteForm: SuperValidated<AnyZodObject> | undefined = undefined;
export let URLModel: urlModel | undefined = undefined;
$: model = URLModel ? URL_MODEL_MAP[URLModel] : undefined;
const user = $page.data.user;
Expand Down Expand Up @@ -127,12 +126,11 @@
});
$: field_component_map = FIELD_COMPONENT_MAP[URLModel] ?? {};
// const field_component_map = FIELD_MAP;
const tagMap = FIELD_COLORED_TAG_MAP[URLModel] ?? {};
const taggedKeys = new Set(Object.keys(tagMap));
// tagged_keys tag_map[key][value]
$: model = source.meta.urlmodel ? URL_MODEL_MAP[source.meta.urlmodel] : URL_MODEL_MAP[URLModel];
$: source, handler.setRows(data);
</script>

Expand Down Expand Up @@ -264,16 +262,17 @@
<slot name="actions" meta={row.meta}>
{#if row.meta[identifierField]}
{@const actionsComponent = field_component_map['actions']}
{@const actionsURLModel = source.meta.urlmodel ?? URLModel}
<TableRowActions
deleteForm={!row.meta.builtin ? deleteForm : undefined}
model={URL_MODEL_MAP[URLModel]}
{URLModel}
detailURL={`/${URLModel}/${row.meta[identifierField]}`}
editURL={!(row.meta.builtin || row.meta.urn) ? `/${URLModel}/${row.meta[identifierField]}/edit?next=${$page.url.pathname}` : undefined}
{model}
URLModel={actionsURLModel}
detailURL={`/${actionsURLModel}/${row.meta[identifierField]}`}
editURL={!(row.meta.builtin || row.meta.urn) ? `/${actionsURLModel}/${row.meta[identifierField]}/edit?next=${$page.url.pathname}` : undefined}
{row}
hasBody={$$slots.actionsBody}
{identifierField}
preventDelete={(row.meta.builtin || (row.meta.urn ?? false)) && !(row.meta.allowDeleteLibrary ?? false)}
preventDelete={(row.meta.builtin) || (row.meta.reference_count) || !(row.meta.allowDeleteLibrary ?? false)}
>
<svelte:fragment slot="head">
{#if $$slots.actionsHead}
Expand Down
18 changes: 11 additions & 7 deletions frontend/src/lib/utils/crud.ts
Original file line number Diff line number Diff line change
Expand Up @@ -404,15 +404,15 @@ export const URL_MODEL_MAP: ModelMap = {
{ field: 'compliance_assessment', urlModel: 'compliance-assessments' }
]
},
"stored-libraries": {
'stored-libraries': {
name: 'storedlibrary',
localName: 'imported library',
localNamePlural: 'imported libraries',
localFrGender: 'f',
verboseName: 'Imported Library',
verboseNamePlural: 'Imported Libraries'
},
"loaded-libraries": {
'loaded-libraries': {
name: 'loadedlibrary',
localName: 'imported library',
localNamePlural: 'imported libraries',
Expand All @@ -426,14 +426,18 @@ export const FIELD_COMPONENT_MAP = {
evidences: {
attachment: EvidenceFilePreview
},
"stored-libraries": {
libraries: {
locale: LanguageDisplay,
actions: LibraryActions
},
"loaded-libraries": {
locale: LanguageDisplay
// actions: LibraryActions
},
// "stored-libraries": {
// locale: LanguageDisplay,
// actions: LibraryActions
// },
// "loaded-libraries": {
// locale: LanguageDisplay
// // actions: LibraryActions
// },
'user-groups': {
localization_dict: UserGroupNameDisplay
}
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/lib/utils/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export const URL_MODEL = [
'frameworks',
'requirements',
'requirement-assessments',
// 'libraries'
'libraries'
] as const;

export type urlModel = (typeof URL_MODEL)[number];
Expand Down
122 changes: 26 additions & 96 deletions frontend/src/routes/(app)/libraries/+page.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,139 +9,69 @@ import { z } from 'zod';
import { zod } from 'sveltekit-superforms/adapters';
import { tableSourceMapper } from '@skeletonlabs/skeleton';
import { listViewFields } from '$lib/utils/table';
import type { Library, urlModel } from '$lib/utils/types';
import type { Library } from '$lib/utils/types';
import * as m from '$paraglide/messages';
import { localItems } from '$lib/utils/locales';
import { languageTag } from '$paraglide/runtime';


// ----------------------------------------------------------- //


export const load = (async ({ fetch }) => {
const stored_libraries_endpoint = `${BASE_API_URL}/stored-libraries/`;
const loaded_libaries_endpoint = `${BASE_API_URL}/loaded-libraries/`;

const [stored_libraries_res,loaded_libaries_res] = await Promise.all([fetch(stored_libraries_endpoint),fetch(loaded_libaries_endpoint)]);
const [stored_libraries_res, loaded_libaries_res] = await Promise.all([
fetch(stored_libraries_endpoint),
fetch(loaded_libaries_endpoint)
]);

const storedLibraries = await stored_libraries_res.json().then((res) => res.results);
const loadedLibraries = await loaded_libaries_res.json().then((res) => res.results);

const prepareRow = (row) => {
const prepareRow = (row: Record<string, any>) => {
row.overview = [
`Provider: ${row.provider}`,
`Packager: ${row.packager}`,
...Object.entries(row.objects_meta).map(([key,value]) => `${key}: ${value}`)
...Object.entries(row.objects_meta).map(([key, value]) => `${key}: ${value}`)
];
row.allowDeleteLibrary = row.allowDeleteLibrary = row.reference_count && row.reference_count > 0 ? false : true;
}
row.allowDeleteLibrary = row.allowDeleteLibrary =
row.reference_count && row.reference_count > 0 ? false : true;
};

storedLibraries.forEach(prepareRow);
loadedLibraries.forEach(prepareRow);

// const headData: Record<string, string>

const makeHeadData = (modelName: string) => {
return listViewFields['stored-libraries'].body.reduce(
(obj, key, index) => {
obj[key] = listViewFields['stored-libraries'].head[index];
return obj;
},
{}
);
}

const makeBodyData = (libraries,modelName: string) => tableSourceMapper(libraries, listViewFields[modelName].body);

const makeLibrariesTable = (libraries: Library[],modelName: string) => {
return {
head: makeHeadData(modelName),
body: makeBodyData(libraries,modelName),
meta: libraries
};
};

const storedLibrariesTable = makeLibrariesTable(storedLibraries,'stored-libraries');
const loadedLibrariesTable = makeLibrariesTable(loadedLibraries,'loaded-libraries');

const schema = z.object({ id: z.string() });
const deleteForm = await superValidate(zod(schema));

return { storedLibrariesTable, loadedLibrariesTable, deleteForm }
}) satisfies PageServerLoad;


type libraryURLModel = 'stored-libraries' | 'loaded-libraries';



const old_load = (async ({ fetch }) => {
const endpoint = `${BASE_API_URL}/libraries/`;

const res = await fetch(endpoint);
const libraries: Library[] = await res.json().then((res) => res.results);

function countObjects(library: Library) {
const result: { [key: string]: any } = new Object();
for (const [key, value] of Object.entries(library.objects)) {
if (Array.isArray(value)) {
const str = key.charAt(0).toUpperCase() + key.slice(1).replace('_', ' ');
result[str] = value.length;
} else {
for (const [key2, value2] of Object.entries(value)) {
if (key2 === 'requirements') {
const str = key2.charAt(0).toUpperCase() + key2.slice(1);
result[str] = value2.length;
}
}
}
}
return result;
}

libraries.forEach((row) => {
row.overview = [
`Provider: ${row.provider}`,
`Packager: ${row.packager}`,
...Object.entries(countObjects(row)).map(([key, value]) => `${key}: ${value}`)
];
row.allowDeleteLibrary = row.reference_count && row.reference_count > 0 ? false : true;
});

const headData: Record<string, string> = listViewFields['libraries' as urlModel].body.reduce(
(obj, key, index) => {
obj[key] = listViewFields['libraries' as urlModel].head[index];
const makeHeadData = (URLModel: libraryURLModel) => {
return listViewFields[URLModel].body.reduce((obj, key, index) => {
obj[key] = listViewFields[URLModel].head[index];
return obj;
},
{}
);
}, {});
};

const bodyData = (libraries) =>
tableSourceMapper(libraries, listViewFields['libraries' as urlModel].body);
const makeBodyData = (libraries: Library[], URLModel: libraryURLModel) =>
tableSourceMapper(libraries, listViewFields[URLModel].body);

const librariesTable: TableSource = (libraries: Library[]) => {
const makeLibrariesTable = (libraries: Library[], URLModel: libraryURLModel) => {
return {
head: headData,
body: bodyData(libraries),
meta: libraries
head: makeHeadData(URLModel),
body: makeBodyData(libraries, URLModel),
meta: { urlmodel: URLModel, ...libraries }
};
};

const defaultLibrariesTable = librariesTable(
libraries.filter((lib) => !lib.id && lib.packager === 'intuitem')
);

const importedLibrariesTable = librariesTable(libraries.filter((lib) => lib.id));
const storedLibrariesTable = makeLibrariesTable(storedLibraries, 'stored-libraries');
const loadedLibrariesTable = makeLibrariesTable(loadedLibraries, 'loaded-libraries');

const schema = z.object({ id: z.string() });
const deleteForm = await superValidate(zod(schema));

return { libraries, defaultLibrariesTable, importedLibrariesTable, deleteForm };
return { storedLibrariesTable, loadedLibrariesTable, deleteForm };
}) satisfies PageServerLoad;


// ----------------------------------------------------------- //


export const actions: Actions = {
upload: async (event) => {
const formData = await event.request.formData();
Expand Down Expand Up @@ -179,7 +109,7 @@ export const actions: Actions = {
const schema = z.object({ id: z.string().regex(URN_REGEX) });
const deleteForm = await superValidate(formData, zod(schema));

const URLModel = formData.get("urlmodel");
const URLModel = formData.get('urlmodel');

const id = deleteForm.data.id;
const endpoint = `${BASE_API_URL}/${URLModel}/${id}/`;
Expand Down
16 changes: 8 additions & 8 deletions frontend/src/routes/(app)/libraries/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@
</script>

<div class="card bg-white shadow">
<TabGroup> <!-- data.loadedLibrariesTable.body.length > 0 -->
<TabGroup>
<!-- data.loadedLibrariesTable.body.length > 0 -->
{#if data.loadedLibrariesTable.body.length > 0}
<Tab bind:group={tabSet} value={0}>{m.librariesStore()}</Tab>
<Tab bind:group={tabSet} value={1}>{m.importedLibraries()}</Tab>
Expand All @@ -26,26 +27,25 @@
{m.currentlyNoImportedLibraries()}.
</div>
{/if}
<svelte:fragment slot="panel"> <!-- storedlibraries -->
<svelte:fragment slot="panel">
<!-- storedlibraries -->
{#if tabSet === 0}
<ModelTable
source={data.storedLibrariesTable}
URLModel="stored-libraries"
LocalURLModel="libraries"
URLModel="libraries"
identifierField="urn"
pagination={false}
deleteForm={data.deleteForm}
/>
{/if}
{#if tabSet === 1} <!-- loadedlibraries -->
{#if tabSet === 1}
<!-- loadedlibraries -->
<ModelTable
source={data.loadedLibrariesTable}
URLModel="loaded-libraries"
LocalURLModel="libraries"
URLModel="libraries"
identifierField="urn"
pagination={false}
deleteForm={data.deleteForm}
detailQueryParameter="loaded"
/>
{/if}
</svelte:fragment>
Expand Down

0 comments on commit 0e4dd16

Please sign in to comment.