Skip to content

Commit

Permalink
feat: Add viewport meta tag to improve page layout
Browse files Browse the repository at this point in the history
  • Loading branch information
bramses committed Aug 18, 2024
1 parent 73e0ba4 commit 44cdc60
Show file tree
Hide file tree
Showing 4 changed files with 120 additions and 16 deletions.
31 changes: 27 additions & 4 deletions src/app/[locale]/(auth)/dashboard/garden/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,27 @@ import { useState } from 'react';
import Calendar from 'react-calendar';

import Entry from '@/components/Entry';
import { getCache, invalidateCache, setCache } from '@/helpers/cache';

const GardenDaily = () => {
const [entries, setEntries] = useState<any[]>([]);
const [selectedDay, setSelectedDay] = useState('');
const [loading, setLoading] = useState(false);
const cache = getCache();

const fetchByID = async (id: string) => {
const cachedAlias = cache.aliases[id];
if (cachedAlias) {
// console.log('Returning cached alias:', cachedAlias);
return { data: cachedAlias };
}

const cachedParent = cache.parents[id];
if (cachedParent) {
// console.log('Returning cached parent:', cachedParent);
return { data: cachedParent };
}

try {
const response = await fetch('/api/fetch', {
method: 'POST',
Expand All @@ -22,6 +36,18 @@ const GardenDaily = () => {
}),
});
const data = await response.json();
const entry = data.data;
// parse metadata
const metadata = JSON.parse(entry.metadata);

// cache the entry
if (metadata.parent_id) {
cache.aliases[id] = entry;
} else {
cache.parents[id] = entry;
}

setCache(cache);

return data;
} catch (error) {
Expand Down Expand Up @@ -153,10 +179,8 @@ const GardenDaily = () => {
// TODO: extract these into helper logic for better reusability bw here and SearchBox component
const handleAliasAdd = async (data: any) => {
// get id of the selected alias
console.log('Selected alias:', data);
// fetch the entry by id
const parentEntry = await fetchByID(data.id);
console.log('Parent entry:', parentEntry);
let parentAliases = [];
try {
parentAliases = JSON.parse(parentEntry.data.metadata).alias_ids;
Expand All @@ -169,14 +193,13 @@ const GardenDaily = () => {
};
const aliasRes = await addEntry(data.alias, newMetadata);
const aliasId = aliasRes.respData.id;
console.log('Added alias:', aliasRes);
// update the original entry's metadata with the new alias id in the alias_ids array
const updatedMetadata = {
...data.metadata,
alias_ids: parentAliases ? [parentAliases, aliasId].flat() : [aliasId],
};
console.log('Updated metadata:', updatedMetadata);
await updateEntry(parentId, data.data, updatedMetadata);
invalidateCache(parentId, false);
return aliasRes;
} catch (err) {
console.error('Error parsing parent metadata:', err);
Expand Down
6 changes: 6 additions & 0 deletions src/app/[locale]/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,12 @@ export default function RootLayout(props: {

return (
<html lang={props.params.locale}>
<head>
<meta
name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1"
/>
</head>
<body>
<NextIntlClientProvider
locale={props.params.locale}
Expand Down
54 changes: 42 additions & 12 deletions src/components/SearchBox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,29 @@

import { useState } from 'react';

import { getCache, invalidateCache, setCache } from '@/helpers/cache';

import Entries from './Entries';

const SearchBox = () => {
const [searchResults, setSearchResults] = useState<any[]>([]);
const [textAreaValue, setTextAreaValue] = useState('');
const [showLoading, setShowLoading] = useState(false);
const cache = getCache();

const fetchByID = async (id: string) => {
const cachedAlias = cache.aliases[id];
if (cachedAlias) {
// console.log('Returning cached alias:', cachedAlias);
return { data: cachedAlias };
}

const cachedParent = cache.parents[id];
if (cachedParent) {
// console.log('Returning cached parent:', cachedParent);
return { data: cachedParent };
}

try {
const response = await fetch('/api/fetch', {
method: 'POST',
Expand All @@ -24,6 +39,18 @@ const SearchBox = () => {
});
const data = await response.json();

const entry = data.data;
// parse metadata
const metadata = JSON.parse(entry.metadata);
// cache the entry
if (metadata.parent_id) {
cache.aliases[id] = entry;
} else {
cache.parents[id] = entry;
}

setCache(cache);

return data;
} catch (error) {
console.error('Error fetching entry by ID:', error);
Expand Down Expand Up @@ -141,10 +168,14 @@ const SearchBox = () => {
// Fetch parent entry by parent_id
const parentEntryRes = await fetchByID(entry.metadata.parent_id);
const parentEntry = parentEntryRes.data;
console.log('Parent entry:', parentEntry);

// Parse parent metadata
const parentMetadataJSON = JSON.parse(parentEntry.metadata);
let parentMetadataJSON = parentEntry.metadata;
try {
parentMetadataJSON = JSON.parse(parentEntry.metadata);
} catch (err) {
console.error('Error parsing parent metadata:', err);
}
parentEntry.metadata = parentMetadataJSON;

// Find the index of the current entry in the parent's alias_ids
Expand All @@ -153,12 +184,12 @@ const SearchBox = () => {
const aliasIds = parentMetadataJSON.alias_ids.map(Number);

if (aliasIds.includes(Number(entry.id))) {
console.log('aliasIds:', aliasIds);
console.log('entry.id:', entry.id);
console.log(
'aliasIds.indexOf(Number(entry.id)):',
aliasIds.indexOf(Number(entry.id)),
);
// console.log('aliasIds:', aliasIds);
// console.log('entry.id:', entry.id);
// console.log(
// 'aliasIds.indexOf(Number(entry.id)):',
// aliasIds.indexOf(Number(entry.id)),
// );
selectedIndex = aliasIds.indexOf(Number(entry.id));
}
}
Expand Down Expand Up @@ -251,10 +282,8 @@ const SearchBox = () => {

const handleAliasAdd = async (data: any) => {
// get id of the selected alias
console.log('Selected alias:', data);
// fetch the entry by id
const parentEntry = await fetchByID(data.id);
console.log('Parent entry:', parentEntry);
let parentAliases = [];
try {
parentAliases = JSON.parse(parentEntry.data.metadata).alias_ids;
Expand All @@ -267,14 +296,15 @@ const SearchBox = () => {
};
const aliasRes = await addEntry(data.alias, newMetadata);
const aliasId = aliasRes.respData.id;
console.log('Added alias:', aliasRes);
// update the original entry's metadata with the new alias id in the alias_ids array
const updatedMetadata = {
...data.metadata,
alias_ids: parentAliases ? [parentAliases, aliasId].flat() : [aliasId],
};
console.log('Updated metadata:', updatedMetadata);
await updateEntry(parentId, data.data, updatedMetadata);
// invalidate the cache at id for the parent entry
invalidateCache(parentId, false);

return aliasRes;
} catch (err) {
console.error('Error parsing parent metadata:', err);
Expand Down
45 changes: 45 additions & 0 deletions src/helpers/cache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
const CACHE_KEY = 'entryCache';
const CACHE_EXPIRATION = 24 * 60 * 60 * 1000; // 24 hours in milliseconds

export const getCache = () => {
if (typeof window === 'undefined' || typeof localStorage === 'undefined') {
return { aliases: {}, parents: {} }; // Check for client-side and localStorage
}
const cache = localStorage.getItem(CACHE_KEY);
if (cache) {
const parsedCache = JSON.parse(cache);
if (Date.now() - parsedCache.timestamp < CACHE_EXPIRATION) {
return parsedCache.data;
}
}
return { aliases: {}, parents: {} };
};

export const setCache = (data: any) => {
if (typeof window === 'undefined' || typeof localStorage === 'undefined')
return; // Check for client-side and localStorage
const cache = {
timestamp: Date.now(),
data,
};
localStorage.setItem(CACHE_KEY, JSON.stringify(cache));
};

export const appendCache = (id: string, entry: any, isAlias: boolean) => {
const cache = getCache();
if (isAlias) {
cache.aliases[id] = entry;
} else {
cache.parents[id] = entry;
}
setCache(cache);
};

export const invalidateCache = (id: string, isAlias: boolean) => {
const cache = getCache();
if (isAlias) {
delete cache.aliases[id];
} else {
delete cache.parents[id];
}
};

0 comments on commit 44cdc60

Please sign in to comment.