Skip to content

Commit

Permalink
checklists ui
Browse files Browse the repository at this point in the history
  • Loading branch information
seanmorley15 committed Aug 6, 2024
1 parent d5f93c5 commit 18ef919
Show file tree
Hide file tree
Showing 6 changed files with 405 additions and 12 deletions.
52 changes: 46 additions & 6 deletions backend/server/adventures/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ class Meta:
fields = [
'id', 'user_id', 'name', 'is_checked', 'checklist', 'created_at', 'updated_at'
]
read_only_fields = ['id', 'created_at', 'updated_at', 'user_id']
read_only_fields = ['id', 'created_at', 'updated_at', 'user_id', 'checklist']

def validate(self, data):
# Check if the checklist is public and the checklist item is not
Expand All @@ -123,13 +123,56 @@ def create(self, validated_data):


class ChecklistSerializer(serializers.ModelSerializer):
items = ChecklistItemSerializer(many=True, read_only=True, source='checklistitem_set')
items = ChecklistItemSerializer(many=True, source='checklistitem_set')
class Meta:
model = Checklist
fields = [
'id', 'user_id', 'name', 'date', 'is_public', 'collection', 'created_at', 'updated_at', 'items'
]
read_only_fields = ['id', 'created_at', 'updated_at', 'user_id']

def create(self, validated_data):
items_data = validated_data.pop('checklistitem_set')
checklist = Checklist.objects.create(**validated_data)
for item_data in items_data:
ChecklistItem.objects.create(checklist=checklist, **item_data)
return checklist

def update(self, instance, validated_data):
items_data = validated_data.pop('checklistitem_set', [])

# Update Checklist fields
for attr, value in validated_data.items():
setattr(instance, attr, value)
instance.save()

# Get current items
current_items = instance.checklistitem_set.all()
current_item_ids = set(current_items.values_list('id', flat=True))

# Update or create items
updated_item_ids = set()
for item_data in items_data:
item_id = item_data.get('id')
if item_id:
if item_id in current_item_ids:
item = current_items.get(id=item_id)
for attr, value in item_data.items():
setattr(item, attr, value)
item.save()
updated_item_ids.add(item_id)
else:
# If ID is provided but doesn't exist, create new item
ChecklistItem.objects.create(checklist=instance, **item_data)
else:
# If no ID is provided, create new item
ChecklistItem.objects.create(checklist=instance, **item_data)

# Delete items that are not in the updated data
items_to_delete = current_item_ids - updated_item_ids
instance.checklistitem_set.filter(id__in=items_to_delete).delete()

return instance

def validate(self, data):
# Check if the collection is public and the checklist is not
Expand All @@ -149,10 +192,7 @@ def validate(self, data):

return data

def create(self, validated_data):
# Set the user_id to the current user
validated_data['user_id'] = self.context['request'].user
return super().create(validated_data)



class CollectionSerializer(serializers.ModelSerializer):
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/lib/components/ChecklistCard.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
export let checklist: Checklist;
export let user: User | null = null;
function editNote() {
function editChecklist() {
dispatch('edit', checklist);
}
Expand Down Expand Up @@ -51,7 +51,7 @@
<!-- <button class="btn btn-neutral mb-2" on:click={() => goto(`/notes/${note.id}`)}
><Launch class="w-6 h-6" />Open Details</button
> -->
<button class="btn btn-neutral mb-2" on:click={editNote}>
<button class="btn btn-neutral mb-2" on:click={editChecklist}>
<Launch class="w-6 h-6" />Open
</button>
{#if checklist.user_id == user?.pk}
Expand Down
263 changes: 263 additions & 0 deletions frontend/src/lib/components/ChecklistModal.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,263 @@
<script lang="ts">
import { isValidUrl } from '$lib';
import type { Collection, Checklist, User, ChecklistItem } from '$lib/types';
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
import { onMount } from 'svelte';
let modal: HTMLDialogElement;
export let checklist: Checklist | null = null;
export let collection: Collection;
export let user: User | null = null;
let items: ChecklistItem[] = [];
items = checklist?.items || [];
let warning: string | null = '';
let newStatus: boolean = false;
let newItem: string = '';
function addItem() {
if (newItem.trim() == '') {
warning = 'Item cannot be empty';
return;
}
if (newChecklist.items.find((item) => item.name.trim() == newItem)) {
warning = 'Item already exists';
return;
}
items = [
...items,
{
name: newItem,
is_checked: newStatus,
id: 0,
user_id: 0,
checklist: 0,
created_at: '',
updated_at: ''
}
];
if (checklist) {
newChecklist.items = items;
}
newItem = '';
newStatus = false;
warning = '';
}
let newChecklist = {
name: checklist?.name || '',
date: checklist?.date || undefined || null,
items: checklist?.items || [],
collection: collection.id,
is_public: collection.is_public
};
let initialName: string = checklist?.name || '';
onMount(() => {
modal = document.getElementById('my_modal_1') as HTMLDialogElement;
if (modal) {
modal.showModal();
}
});
function close() {
dispatch('close');
}
function removeItem(i: number) {
items = items.filter((_, index) => index !== i);
newChecklist.items = items;
}
function handleKeydown(event: KeyboardEvent) {
if (event.key === 'Escape') {
dispatch('close');
}
}
async function save() {
// handles empty date
if (newChecklist.date == '') {
newChecklist.date = null;
}
if (checklist && checklist.id) {
console.log('newNote', newChecklist);
const res = await fetch(`/api/checklists/${checklist.id}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(newChecklist)
});
if (res.ok) {
let data = await res.json();
if (data) {
dispatch('save', data);
}
} else {
console.error('Failed to save checklist');
}
} else {
console.log('newNote', newChecklist);
const res = await fetch(`/api/checklists/`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(newChecklist)
});
if (res.ok) {
let data = await res.json();
if (data) {
dispatch('create', data);
}
} else {
let data = await res.json();
console.error('Failed to save checklist', data);
console.error('Failed to save checklist');
}
}
}
</script>

<dialog id="my_modal_1" class="modal">
<!-- svelte-ignore a11y-no-noninteractive-element-interactions -->
<!-- svelte-ignore a11y-no-noninteractive-tabindex -->
<div class="modal-box" role="dialog" on:keydown={handleKeydown} tabindex="0">
<h3 class="font-bold text-lg">Checklist Editor</h3>
{#if initialName}
<p class="font-semibold text-md mb-2">Editing note {initialName}</p>
{/if}

{#if (checklist && user?.pk == checklist?.user_id) || !checklist}
<form on:submit|preventDefault>
<div class="form-control mb-2">
<label for="name">Name</label>
<input
type="text"
id="name"
class="input input-bordered w-full max-w-xs"
bind:value={newChecklist.name}
/>
</div>
<div class="form-control mb-2">
<label for="content">Date</label>
<input
type="date"
id="date"
name="date"
min={collection.start_date || ''}
max={collection.end_date || ''}
bind:value={newChecklist.date}
class="input input-bordered w-full max-w-xs mt-1"
/>
</div>
<!-- <div class="form-control mb-2">
<label for="content">New Item</label>
<div class="form-control">
<input type="checkbox" bind:checked={newStatus} class="checkbox" />
</div>
<input
type="text"
id="new_item"
name="new_item"
bind:value={newItem}
class="input input-bordered w-full max-w-xs mt-1"
/>
<button class="btn btn-primary mt-1" on:click={addItem}>Add Item</button>
</div> -->
<div class="form-control mb-2 flex flex-row">
<input type="checkbox" bind:checked={newStatus} class="checkbox mt-4 mr-2" />
<input
type="text"
id="new_item"
placeholder="New Item"
name="new_item"
bind:value={newItem}
class="input input-bordered w-full max-w-xs mt-1"
/>
<button
type="button"
class="btn btn-sm btn-primary absolute right-0 mt-2.5 mr-4"
on:click={addItem}
>
Add
</button>
</div>
{#if items.length > 0}
<div class="divider"></div>
<h2 class=" text-xl font-semibold mb-4 -mt-3">Items</h2>
{/if}

{#each items as item, i}
<div class="form-control mb-2 flex flex-row">
<input type="checkbox" bind:checked={item.is_checked} class="checkbox mt-4 mr-2" />
<input
type="text"
id="item_{i}"
name="item_{i}"
bind:value={item.name}
class="input input-bordered w-full max-w-xs mt-1"
/>
<button
type="button"
class="btn btn-sm btn-error absolute right-0 mt-2.5 mr-4"
on:click={() => removeItem(i)}
>
Remove
</button>
</div>
{/each}

{#if warning}
<div role="alert" class="alert alert-error">
<svg
xmlns="http://www.w3.org/2000/svg"
class="h-6 w-6 shrink-0 stroke-current"
fill="none"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"
/>
</svg>
<span>{warning}</span>
</div>
{/if}

<button class="btn btn-primary mr-1" on:click={save}>Save</button>
<button class="btn btn-neutral" on:click={close}>Close</button>

{#if collection.is_public}
<div role="alert" class="alert mt-4">
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
class="h-6 w-6 shrink-0 stroke-current"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
></path>
</svg>
<span>This checklist is public because it is in a public collection.</span>
</div>
{/if}
</form>
{:else}
<!-- view only form -->
{/if}
</div>
</dialog>
2 changes: 1 addition & 1 deletion frontend/src/lib/components/NoteCard.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
</div>
<div class="badge badge-neutral">Note</div>
{#if note.links && note.links.length > 0}
<p>{note.links.length} links</p>
<p>{note.links.length} {note.links.length > 1 ? 'Links' : 'Link'}</p>
{/if}
{#if note.date && note.date !== ''}
<div class="inline-flex items-center">
Expand Down
Loading

0 comments on commit 18ef919

Please sign in to comment.