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: allow row editing #131

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 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
58 changes: 58 additions & 0 deletions src/lib/server/db/person.ts
Original file line number Diff line number Diff line change
Expand Up @@ -459,3 +459,61 @@ export async function removePersonsFromBuilding(
throw new Error(`Failed to nuke building in database: ${(err as Error).message}`);
}
}



// Updates a person
export async function updatePerson(
db: Database,
id: number,
fnameD: string,
lnameD: string,
department: string,
creator: string
): Promise<{
id: number;
fname: string;
lname: string;
department: string;
}> {
// Assert fname, lname, creator, id and deparment are valid
if (
id === null ||
id === undefined ||
fnameD === null ||
fnameD === undefined ||
fnameD === '' ||
lnameD === null ||
lnameD === undefined ||
lnameD === '' ||
department === null ||
department === undefined ||
department === '' ||
creator === null ||
GrbavaCigla marked this conversation as resolved.
Show resolved Hide resolved
creator === undefined ||
creator === ''
) {
throw new Error('Invalid person data');
}

const fname = capitalizeString(sanitizeString(fnameD));
const lname = capitalizeString(sanitizeString(lnameD));

try {
return await db.transaction(async (tx) => {
GrbavaCigla marked this conversation as resolved.
Show resolved Hide resolved
await tx
.update(person)
.set({fname: fname, lname: lname, department: department})
.where(eq(person.id, id));

return {
id,
fname,
lname,
department,
}
});
} catch (err: unknown) {
throw new Error(`Failed to update person in database: ${(err as Error).message}`);
}
}
34 changes: 33 additions & 1 deletion src/routes/(dashboard)/+page.server.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import { getPersons, togglePersonState } from '$lib/server/db/person';
import { getPersons, togglePersonState, updatePerson } from '$lib/server/db/person';
import { fail, redirect, type Actions } from '@sveltejs/kit';
import type { PageServerLoad } from './$types';
import { invalidateSession } from '$lib/server/db/session';
import { deleteSessionTokenCookie } from '$lib/server/session';
import { superValidate } from 'sveltekit-superforms';
import { zod } from 'sveltekit-superforms/adapters';
import { formSchema } from './schema';

export const load: PageServerLoad = async ({ locals }) => {
const { database } = locals;
Expand Down Expand Up @@ -45,6 +48,35 @@ export const actions: Actions = {
});
}
},
edit: async ({ locals, request }) => {
const { database } = locals;
const form = await superValidate(request, zod(formSchema));
if (!form.valid) {
return fail(400, {
form,
message: 'Invalid form inputs'
});
}

if (locals.session === null || locals.user === null) {
return fail(401, {
form,
message: 'Invalid session'
});
}

try {
const { id, fname, lname, department } = form.data;
const creator = locals.user.username;

await updatePerson(database, id, fname, lname, department, creator);
} catch (err: unknown) {
console.debug(`Failed to edit: ${(err as Error).message}`);
return fail(400, {
message: 'Failed to edit'
});
}
},
togglestate: async ({ locals, request }) => {
const { database } = locals;
try {
Expand Down
24 changes: 17 additions & 7 deletions src/routes/(dashboard)/columns.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { renderComponent } from '$lib/components/ui/data-table';
import type { Person, PersonType } from '$lib/types/person';
import type { Person } from '$lib/types/person';
import type { ColumnDef } from '@tanstack/table-core';
import DataTableActions from './data-table-actions.svelte';

Expand All @@ -10,19 +10,28 @@ export const columns: ColumnDef<Person>[] = [
},
{
accessorKey: 'fname',
header: 'First name'
header: 'First name',
meta: {
editable: true,
}
},
{
accessorKey: 'lname',
header: 'Last name'
header: 'Last name',
meta: {
editable: true,
}
},
{
accessorKey: 'identifier',
header: 'Identifier'
},
{
accessorKey: 'department',
header: 'Department'
header: 'Department',
meta: {
editable: true,
}
},
{
accessorKey: 'building',
Expand All @@ -34,11 +43,12 @@ export const columns: ColumnDef<Person>[] = [
},
{
id: 'actions',
header: 'Toggle State',
cell: ({ row }) => {
header: 'Actions',
cell: ({ row, table }) => {
return renderComponent(DataTableActions, {
id: row.original.id,
type: row.original.type
type: row.original.type,
table,
});
},
enableSorting: false
Expand Down
51 changes: 42 additions & 9 deletions src/routes/(dashboard)/data-table-actions.svelte
Original file line number Diff line number Diff line change
@@ -1,17 +1,50 @@
<script lang="ts">
import { ArrowLeftRight } from 'lucide-svelte';
import { ArrowLeftRight, Pencil, Check } from 'lucide-svelte';
import { enhance } from '$app/forms';
import Button from '$lib/components/ui/button/button.svelte';
import { Input } from '$lib/components/ui/input';
import { searchStore } from '$lib/stores/search.svelte';
import type { Table } from '@tanstack/table-core';
import type { Person } from '$lib/types/person';
import { fly } from 'svelte/transition';

let { id, type }: { id: number; type: string } = $props();
let { id, type, table }: { id: number; type: string; table: Table<Person> } = $props();

function onEditButtonClick() {
table.options?.meta?.setEditStatus(id, true);
}

function isSaveButton(): boolean {
return table.options !== null ? table.options.meta?.getEditStatus(id) === true : false;
}
</script>

<form method="POST" action="?/togglestate" class="w-full" use:enhance>
<Input type="hidden" name="q" value={searchStore.query} />
<Input type="hidden" name="type" value={type} />
<Button variant="outline" type="submit" name="id" value={id} class="w-full">
<ArrowLeftRight /> <span class="hidden sm:block">Toggle State</span>
</Button>
</form>
<div class="flex gap-2">
<form method="POST" action="?/togglestate" class="w-full" use:enhance>
<Input type="hidden" name="q" value={searchStore.query} />
<Input type="hidden" name="type" value={type} />
<Button variant="outline" type="submit" name="id" value={id} class="w-full">
<ArrowLeftRight /> <span class="hidden sm:block">Toggle State</span>
</Button>
</form>
{#if table}
GrbavaCigla marked this conversation as resolved.
Show resolved Hide resolved
{#if isSaveButton()}
<form method="POST" action="?/edit" class="w-full" use:enhance in:fly>
{#each table._getColumnDefs() as def }
{#if def.meta?.editable === true}
<Input type="hidden" name={def.accessorKey} value="" />
{/if}
{/each}
<Button variant="default" class="w-full" type="submit" name="id" value={id} >
<Check /> <span class="hidden sm:block">Save</span>
</Button>
</form>
{:else}
<div class="w-full" in:fly>
<Button variant="outline" onclick={onEditButtonClick} class="w-full">
<Pencil /> <span class="hidden sm:block">Edit</span>
</Button>
</div>
{/if}
{/if}
</div>
18 changes: 18 additions & 0 deletions src/routes/(dashboard)/data-table-editable.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<script lang="ts">
import { Input } from '$lib/components/ui/input';
import type { Person } from '$lib/types/person';
import type { Table } from '@tanstack/table-core';

let {
id,
value,
enabled = false,
table
}: { id: number; value: string; enabled?: boolean; table: Table<Person> } = $props();
</script>

{#if enabled && table.options !== null && table.options.meta?.getEditStatus(id)}
<Input {value} class="field-sizing-content w-min" />
{:else}
{value}
{/if}
31 changes: 29 additions & 2 deletions src/routes/(dashboard)/data-table.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,16 @@
type PaginationState,
type SortingState
} from '@tanstack/table-core';
import { createSvelteTable, FlexRender } from '$lib/components/ui/data-table/index.js';
import {
createSvelteTable,
FlexRender,
renderComponent
} from '$lib/components/ui/data-table/index.js';
import * as Table from '$lib/components/ui/table/index.js';
import Button from '$lib/components/ui/button/button.svelte';
import type { Person } from '$lib/types/person';
import { SvelteSet } from 'svelte/reactivity';
import DataTableEditable from './data-table-editable.svelte';

type DataTableProps<Person> = {
columns: ColumnDef<Person>[];
Expand All @@ -21,6 +27,7 @@

let pagination = $state<PaginationState>({ pageIndex: 0, pageSize: 10 });
let sorting = $state<SortingState>([]);
let editables = new SvelteSet();

const table = createSvelteTable({
get data() {
Expand All @@ -33,6 +40,9 @@
},
get sorting() {
return sorting;
},
get editables() {
return editables;
}
},
onPaginationChange: (updater) => {
Expand All @@ -51,7 +61,24 @@
},
getCoreRowModel: getCoreRowModel(),
getPaginationRowModel: getPaginationRowModel(),
getSortedRowModel: getSortedRowModel()
getSortedRowModel: getSortedRowModel(),
meta: {
setEditStatus: (id: number, status: boolean) => {
status ? editables.add(id) : editables.delete(id);
},
getEditStatus: (id: number) => {
return editables.has(id);
}
},
defaultColumn: {
cell: ({ row, table, column: { columnDef }, cell }) =>
renderComponent(DataTableEditable, {
id: row.original.id,
value: cell.getValue() as string,
enabled: columnDef.meta?.editable,
table: table
})
}
});
</script>

Expand Down
11 changes: 11 additions & 0 deletions src/routes/(dashboard)/schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { z } from 'zod';
import { indexRegExp, indexRegExpMsg, nameRegExp, nameRegExpMsg } from '$lib/utils/regexp';

export const formSchema = z.object({
id: z.number(),
fname: z.string().min(2).max(50).regex(nameRegExp, nameRegExpMsg),
lname: z.string().min(2).max(50).regex(nameRegExp, nameRegExpMsg),
department: z.string(),
});

export type FormSchema = typeof formSchema;
14 changes: 14 additions & 0 deletions src/table.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import '@tanstack/table-core';

declare module '@tanstack/table-core' {
interface TableState {
editables?: SvelteSet;
}
interface ColumnMeta<TData extends RowData, TValue> {
editable?: boolean
}
interface TableMeta<TData extends RowData> {
setEditStatus: (id: number, status: boolean) => void,
getEditStatus: (id: number) => boolean,
}
}
13 changes: 13 additions & 0 deletions tailwind.config.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,22 @@
import { fontFamily } from 'tailwindcss/defaultTheme';
import type { Config } from 'tailwindcss';
import plugin from "tailwindcss/plugin";

const config: Config = {
darkMode: ['class'],
content: ['./src/**/*.{html,js,svelte,ts}'],
plugins: [
// Workaround until tailwind adds this new CSS feature
// Also this CSS feature isn't supported on Firefox and I didn't want to use JS
// https://github.com/tailwindlabs/tailwindcss/discussions/13812
plugin(({ addUtilities }) => {
addUtilities({
".field-sizing-content": {
"field-sizing": "content",
},
});
}),
],
safelist: ['dark'],
theme: {
container: {
Expand Down
Loading