Skip to content

Commit

Permalink
feat: connect db with toolkit and fix errors
Browse files Browse the repository at this point in the history
  • Loading branch information
gurtatiLND committed Dec 4, 2024
1 parent f2abe5b commit f44b827
Show file tree
Hide file tree
Showing 10 changed files with 154 additions and 50 deletions.
3 changes: 2 additions & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
{
"extends": ["next/core-web-vitals", "next/typescript"]
"extends": ["next/core-web-vitals", "next/typescript"],
"rules": {"@next/next/no-img-element": "off"}
}
1 change: 1 addition & 0 deletions next.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export default async (phase: any) => {
const withSerwist = serwist({
swSrc: "src/app/sw.ts",
swDest: "public/sw.js",
maximumFileSizeToCacheInBytes: 5000000,
});
return withSerwist(baseConfig);
}
Expand Down
2 changes: 1 addition & 1 deletion src/app/addTool/components/AddToolDescription.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export default function AddDescription() {
<p className="text-white">Description</p>
<input
type="text"
value={formState.name}
value={formState.description}
onChange={(e) =>
setFormState((prev) => ({
...prev,
Expand Down
40 changes: 17 additions & 23 deletions src/app/addTool/components/AddToolImageUrl.tsx
Original file line number Diff line number Diff line change
@@ -1,35 +1,29 @@
import { useToolkitForm } from "@/context/ToolkitFormContext";
import * as Icons from "@heroicons/react/24/outline";
// import * as Icons from "@heroicons/react/24/outline";

export default function AddImageUrl() {
const { setFormState } = useToolkitForm();
const { formState, setFormState } = useToolkitForm();

const iconList = Object.entries(Icons).map(([name]) => name);

const selectIcon = (iconName: string) => {
setFormState((prev) => ({
const handleUrlChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setFormState(prev => ({
...prev,
imageUrl: iconName,
imageUrl: e.target.value
}));
};

return (
<div>
<p className="text-white">Icon</p>
<div className="grid grid-cols-4 gap-2 max-h-40 overflow-y-auto">
{iconList.map((iconName) => {
const IconComponent = Icons[iconName as keyof typeof Icons];
return (
<button
key={iconName}
onClick={() => selectIcon(iconName)}
className="p-2 hover:bg-twd-secondary-purple rounded"
>
<IconComponent className="h-6 w-6 text-white" />
</button>
);
})}
</div>
<label htmlFor="imageUrl"
className="text-white"
>Image URL</label>

<input
type="url"
id="imageUrl"
value={formState.imageUrl}
onChange={handleUrlChange}
className="w-full p-2 rounded bg-twd-background text-white border border-gray-700"
/>
</div>
);
}
}
1 change: 1 addition & 0 deletions src/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export const metadata: Metadata = {
template: APP_TITLE_TEMPLATE,
},
description: APP_DESCRIPTION,
manifest: "/manifest.json",
appleWebApp: {
capable: true,
statusBarStyle: "default",
Expand Down
26 changes: 12 additions & 14 deletions src/app/toolkit/components/CheckBox.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"use client";
import { useState, useEffect } from "react";
import DatabaseManager from "@/lib/db/DatabaseManager";
import {
DndContext,
closestCenter,
Expand Down Expand Up @@ -32,27 +33,24 @@ export default function CheckBox() {
const isEmpty = data.length === 0;

useEffect(() => {
console.log('useeffect');
console.log('Fetching toolkit items...');
const fetchData = async () => {
try {

const db = await rxdbInit();

const itemsCollection = db.toolkit_items;

const items = await itemsCollection.find().exec();
console.log(items);

setData(items.map((doc) => doc.toJSON()));

const items = await DatabaseManager.getFromDb("toolkit_items");
if (items) {
console.log("Fetched toolkit items:", items);
setData(items.map((doc) => doc.toJSON())); // Convert RxDocument to plain JSON
} else {
console.log("No items found in toolkit_items collection.");
}
} catch (error) {
console.error("Error fetching tasks from database:", error);
console.error("Error fetching toolkit items from database:", error);
}
};
fetchData();
}, [isEmpty]);

// Toggle checkbox state
// have to be fixed - Toggle checkbox state
const handleToggle = (id: string) => {
setData((prevData) =>
prevData.map((item) =>
Expand All @@ -61,7 +59,7 @@ export default function CheckBox() {
);
};

// Delete an item
// have to be fixed - Delete an item
const handleDelete = (id: string) => {
setData((prevData) => prevData.filter((item) => item.id !== id));
};
Expand Down
23 changes: 17 additions & 6 deletions src/app/toolkit/components/SortableItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,16 @@ interface SortableItemProps {
handleDelete: (id: string) => void;
}

const isValidUrl = (url: string | undefined): boolean => {
if (!url) return false; // Explicitly return false if URL is undefined or empty
try {
new URL(url); // Valid URL creation
return true; // Explicitly return true for valid URLs
} catch {
return false; // Explicitly return false for invalid URLs
}
};

export default function SortableItem({
item,
handleToggle,
Expand Down Expand Up @@ -49,10 +59,7 @@ export default function SortableItem({
<input
type="checkbox"
checked={item.checked}
onChange={() => {
console.log("Checkbox clicked for ID:", item.id);
handleToggle(item.id);
}}
onChange={() => handleToggle(item.id)}
className="h-5 w-5 border-white bg-twd-background text-twd-background rounded focus:ring focus:ring-blue-300"
/>
<p
Expand All @@ -67,11 +74,15 @@ export default function SortableItem({
{/* Second Row: Image, Link, and Delete Button */}
<div className="flex items-center justify-between mt-2 pl-8 w-full">
{/* Display the image */}
<img
{isValidUrl(item.imageUrl) ? (
<img
src={item.imageUrl}
alt={item.name}
className="h-10 w-10 object-cover"
/>
/>
) : (
<span className="text-gray-400">No Image</span>
)}
<a
href={item.infoUrl}
target="_blank"
Expand Down
2 changes: 1 addition & 1 deletion src/app/toolkit/components/ToolkitHeader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const headerClasses = `
</div>


<div className="relative w-16 h-16 sm:w-12 sm:h-12">
<div className="w-16 h-16 sm:w-12 sm:h-12">
<ImageComponent
src="/icons/image_toolkit.png"
alt="Logo"
Expand Down
94 changes: 91 additions & 3 deletions src/lib/db/DatabaseManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,53 @@ import { v4 as uuidv4 } from "uuid";

addRxPlugin(RxDBDevModePlugin);

const toolkitSeedData = [
{
id: uuidv4(),
name: "Listen to my favourite music",
category: ["Replace", "Barrier"],
checked: false,
infoUrl: "https://google.com/music",
imageUrl: "https://daily.jstor.org/wp-content/uploads/2023/01/good_times_with_bad_music_1050x700.jpg",
timestamp: new Date().toISOString(),
},
{
id: uuidv4(),
name: "Watch TV",
category: ["Distract"],
checked: false,
infoUrl: "https://google.com/tv",
imageUrl: "https://daily.jstor.org/wp-content/uploads/2023/01/good_times_with_bad_music_1050x700.jpg",
timestamp: new Date().toISOString(),
},
{
id: uuidv4(),
name: "Call a friend",
category: ["Distract", "Change status"],
checked: false,
infoUrl: "https://example.com/call",
imageUrl: "https://daily.jstor.org/wp-content/uploads/2023/01/good_times_with_bad_music_1050x700.jpg",
timestamp: new Date().toISOString(),
},
{
id: uuidv4(),
name: "See a friend",
category: ["Distract", "Change status"],
checked: false,
infoUrl: "https://example.com/call",
imageUrl: "https://daily.jstor.org/wp-content/uploads/2023/01/good_times_with_bad_music_1050x700.jpg",
timestamp: new Date().toISOString(),
},
];

class DatabaseManager {
dbInstance: RxDatabase | null = null;

async initialiseDatabase() {
if (!this.dbInstance) {
this.dbInstance = await createRxDatabase({
name: "database",
ignoreDuplicate: true,
storage: getRxStorageDexie(),
});

Expand All @@ -32,12 +72,26 @@ class DatabaseManager {

async getFromDb(collection: string) {
const db = await this.initialiseDatabase();
// if (db) {
// const myCollection = await db[collection].find().exec();
// console.log(myCollection);
// return myCollection;
// } else {
// console.log("failed: get data from this collection");
// return null;
// }
if (db) {
const myCollection = await db[collection].find().exec();
console.log(myCollection);
const collectionExists = db[collection];
if (!collectionExists) {
console.error(`Collection '${collection}' does not exist`);
return null;
}

const myCollection = await collectionExists.find().exec();
console.log(`Data from collection '${collection}':`, myCollection);
return myCollection;
} else {
console.log("Database initialisation failed");
console.error("Failed to get data from database");
return null;
}
}
Expand Down Expand Up @@ -74,6 +128,40 @@ class DatabaseManager {
console.error("Error adding document to database:", error);
}
}

async insertToDb() {
try {
const db = await this.initialiseDatabase();

if (!db) {
console.error("Database initialisation failed");
return;
}

const toolkitCollection = db.toolkit_items;

if (!toolkitCollection) {
console.error("Toolkit items collection does not exist");
return;
}

console.log("Checking if toolkit_items collection is already seeded...");

const existingDocuments = await toolkitCollection.find().exec();

if (existingDocuments.length > 0) {
console.log("Toolkit items collection is already seeded. Skipping seeding process.");
return;
}

console.log("Seeding toolkit_items collection with initial data...");
const insertedDocs = await toolkitCollection.bulkInsert(toolkitSeedData);

console.log("Seed data successfully inserted:", insertedDocs);
} catch (error) {
console.error("Error seeding the database:", error);
}
}
}

// eslint-disable-next-line import/no-anonymous-default-export
Expand Down
12 changes: 11 additions & 1 deletion src/ui/shared/Image.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,17 @@ function ImageComponent({
className?: string;
}) {
return (
<div className={`${className}`}>
// <div className={`${className}`}>
<div
className={`relative ${className} ${
rounded ? "rounded-full overflow-hidden" : ""
}`}
style={{
position: "relative", // Ensure valid position
width: "100%", // Ensure the parent container has width
height: "100%", // Ensure the parent container has height
}}
>
<Image
src={src}
alt={alt}
Expand Down

0 comments on commit f44b827

Please sign in to comment.