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

re-created branch for integration of app router system into forestgeo… #137

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all 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
3 changes: 3 additions & 0 deletions forestgeo_approuter/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": "next/core-web-vitals"
}
38 changes: 38 additions & 0 deletions forestgeo_approuter/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js
package-lock.json

# testing
/coverage

# next.js
/.next/
/out/
.vscode/
.idea/

# production
/build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# local env files
.env*.local

# vercel
.vercel

# typescript
*.tsbuildinfo
next-env.d.ts
21 changes: 21 additions & 0 deletions forestgeo_approuter/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 Next UI

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
83 changes: 83 additions & 0 deletions forestgeo_approuter/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
# The ForestGEO Data Entry App

A cloud-native web application built to accelerate the pace of research for the Smithsonian
Institution's Forest Global Earth Observatory (ForestGEO). ForestGEO is a global forest research
network, unparalleled in size and scope, comprised of ecologists and research sites dedicated to
advancing long-term study of the world's forests. The ForestGEO app aims to empower researchers with
an efficient means of recording, validating, and publishing forest health data.
Learn more about ForestGEO [at their website](https://www.forestgeo.si.edu/).

This application was built using Next.js 13 (app directory) and NextUI (v2).

### Technical documentation:
Please see the documentation [here](https://github.com/ForestGeoHack/ForestGEO/wiki/ForestGEO-App-Specification)

## Project Structure
- `prev_app/`: previous iteration of the ForestGEO app, which uses the
Next.js v12 Pages router system. You can step into this directory to run the previous iteration
of the application
- `app/`: the primary routing structure and setup for the primary application
- `components/`: requisite react components that are used within the
application and icon information
- `config/`: fonts information and general site information -- endpoint names, plot names, plot
interface, etc.
- `styles/`: tailwindcss formatting files and dropzone/validation table custom formatting files
- `types/`: additional set up for SVG formatting

### Running the project
1. Before running the project, you must create an `.env.local` file in the overhead directory
with the following values:
- `AZURE_AD_CLIENT_ID`
- `AZURE_AD_CLIENT_SECRET`
- `AZURE_AD_TENANT_ID`
- `NEXTAUTH_SECRET`
- `NEXTAUTH_URL`
- all `AZURE_` values must be created/populated from Azure's App Registration portal
2. Once `.env.local` is made, run `npm install` from the overhead directory to install dependencies
3. Run `npm run build` to compile/optimize the application for running
4. Run `npm run dev` to create a dev instance of the application locally on your machine
5. Navigate to `http://localhost:3000` to access the application

---
### Understanding Next.JS Dynamic Routing
Next.js's dynamic routing setup allows for built-in endpoint data processing. By using this,
passing data from a component or root layout to a page/endpoint is simplified (rather than using
useCallback or a React function). As a brief reminder, remember that when using
Next.js 13, writing something like `app/example/page.tsx` will generate a route pointing to `...
/example` instead of `.../example/page`, and nesting successive folders will create a route with
those folders: `app/example1/example2/example3/page.tsx` has the route `...
/example1/example2/example3/`.

For a better explanation of how this works, please observe the
browse endpoint: `app/(endpoints)/browse/[plotKey]/[plotNum]/page.tsx`<br />
In order from left to right, please note the following points of interest:
- `(endpoints)`: wrapping a folder in parentheses allows for better organization w/o using the
wrapped folder name in the path. For example, accessing the Browse page locally does not
require adding `/endpoints/` to the URL
- `[plotKey]`: this is the first required variable when accessing this endpoint -- you
will have to add some string `plotKey` to the end of the URL: `.../browse/[your plot key]` in
order to successfully view the page.
- wrapping a folder in `[]` will designate that folder as a **required** dynamic parameter
- wrapping in `[...folderName]` designates `folderName` as a catch-all route. All
following values after `folderName` (i.e., `.../a/b` will return `folderName = [a, b]` )
- wrapping in `[[...folderName]]` designates `folderName` as an *optional* catch-all route. As
expected, all values for/after `folderName` will be returned as part of the dynamic route,
but `undefined` will also be returned if no value is entered at all (instead of a 404 error)
- `[plotNum]`: second required variable when accessing this endpoint - your resulting endpoint
will look like (example) `http://localhost:3000/browse/plotKey/plotNum`.
---
### Release Notes (v0.1.0):
- endpoints have been added and routed to require a plot key/number combination for access
- initial state has been converted to new `Plot {key: 'none', num: 0}` instead of `''`
- MUI JoyUI has been partially implemented as a replacement for MaterialUI. However, due to time
limitations, MaterialUI has still been incorporated into converted sections from ForestGeoHack
- The current plan is to solely implement either NextUI or ChakraUI instead of either of these options, and future updates will include this information.
- `SelectPlotProps` has been removed and replaced with NextJS dynamic routing (each endpoint will
dynamically retrieve plot information). Endpoints have been updated to reflect dynamic param-based retrieval
- The navigation bar has been updated to use useEffect to push live endpoint updates when the
plot is changed (if you are at an endpoint and the plot is changed, the page will be reloaded to reflect that)
- New components/moved-over information:
- `Dropzone` --> css code has been udpated to be dark theme-friendly
- `FileList` --> moved over
- `Loginlogout` --> created component, login/logout process has been relegated to avatar icon dropdown menu
- `Plotselection` --> partially created from SelectPlot, changed to utilize dynamic routing/selection instead of requiring a new dropdown in each page
Original file line number Diff line number Diff line change
@@ -0,0 +1,229 @@
"use client";
import React, {useCallback, Dispatch, SetStateAction, useState, useEffect} from 'react';
import {
Table,
TableHeader,
TableBody,
TableColumn,
TableRow,
TableCell,
CircularProgress,
Button,
} from '@nextui-org/react';
import {DownloadIcon, DeleteIcon, EditIcon} from "@/components/icons";
import {fileColumns, Plot} from "@/config/site";
import Grid from '@mui/joy/Grid';
import Box from '@mui/joy/Box';
import {Typography} from "@mui/joy";
import {useSession} from "next-auth/react";
import {title} from "@/components/primitives";

// @todo: look into using an ID other than plot name.
// @todo: react router URL params to pass in the ID for Browse.
// https://reactrouter.com/en/main/start/tutorial#url-params-in-loaders

/**
* Keyed by csv filename, valued by date and user that uploaded it.
*/
interface PlotRows {
[fileName: string]: {
date: string;
user: string;
};
}

interface BrowsePureProps {
plot: Plot;
setPlot: Dispatch<SetStateAction<Plot>>;
error?: Error;
/** True when plot data has finished loading. */
isLoaded: boolean;
/** All the rows of data for the plot. */
plotRows?: PlotRows;
}
export default function Page({ params }: { params: { plotKey: string, plotNum: string } }) {
const {data: session} = useSession();
let localPlot: Plot = {
key: (params.plotKey === 'none') ? '' : params.plotKey,
num: parseInt(params!.plotNum)
};
const [currentPlot, setCurrentPlot] = useState(localPlot);
// @TODO - implement remove and download files

const [error, setError] = useState<Error>();
const [isLoaded, setIsLoaded] = useState(false);
const [plotRows, setRows] = useState<PlotRows>();

const getListOfFiles = useCallback(async () => {
if (currentPlot && currentPlot.key !== undefined) {
let response = null;
try {
response = await fetch('/api/download?plot=' + currentPlot.key, {
method: 'Get',
});

if (!response.ok) {
console.error('response.statusText', response.statusText);
setError(new Error('API response not ok'));
}
} catch (e) {
console.error(e);
setError(new Error('API response not ok'));
}

if (response) {
const data = await response.json();
setRows(data);
setIsLoaded(true);
}
} else {
console.log('Plot is undefined');
setError(new Error('No plot'));
}
}, [currentPlot]);

useEffect(() => {
getListOfFiles();
}, [getListOfFiles]);

useEffect(() => {
setCurrentPlot(currentPlot);
setIsLoaded(true);
setError(undefined);
}, [currentPlot, setCurrentPlot, error, isLoaded]);

if ((!currentPlot || !currentPlot.key) || (currentPlot.key === 'none' || currentPlot.num === 0)) {
return (
<>
<h1 className={title()}>Please select a plot to continue.</h1>
</>
);
} else if (!session) {
return (
<>
<h1 className={title()}>You must be logged in to use this feature.</h1>
</>
);
} else {
return (
<BrowsePure
plot={currentPlot}
setPlot={setCurrentPlot}
error={error}
plotRows={plotRows}
isLoaded={isLoaded}
/>
);
}
}

/**
* A container for layout.
*/
function Container({ children }: { children?: React.ReactNode }) {
return (
<Grid
container
direction="column"
sx={{
marginTop: 20,
justifyContent: 'center',
alignItems: 'center',
}}
>
<Box
sx={{
fontWeight: 'bold',
fontSize: 35,
marginBottom: 30,
}}
>
{children}
</Box>
</Grid>
);
}

/**
* Allows selecting from a list of plots, then shows the data for that plot.
*/
function BrowsePure({error, isLoaded, plotRows, plot}: BrowsePureProps) {
if (!plot.key) {
return (
<Container>
<Typography level="h2" mt={2}>
Please select plot
</Typography>
</Container>
);
} else if (error) {
return (
<Container>
<Typography level="h2" mt={2}>
Error while loading data.
</Typography>
<Typography mt={2} mb={2}>
Perhaps try reloading the page. If it still doesn&apos;t work, please again
a bit later.
</Typography>
</Container>
);
} else if (!isLoaded || !plotRows) {
return (
<Container>
<Typography level="h2" mt={2}>
Loading Files...
</Typography>
<CircularProgress value={60} size={"lg"}></CircularProgress>
</Container>
);
} else {
return (
<>
<Typography level="h2" mt={2}>
Files for `${plot.key}`
</Typography>
<Grid
container
direction="row"
sx={{
marginTop: 10,
justifyContent: 'center',
alignItems: 'center',
}}
>
<Table aria-label="simple table"
className={"max-h-fit max-w-fit border-solid border-emerald-400 rounded-sm "}>
<TableHeader>
<TableHeader className={"font-bold"} columns={fileColumns}>
{(column) => <TableColumn key={column.key}>{column.label}</TableColumn>}
</TableHeader>
</TableHeader>
<TableBody>
{Object.keys(plotRows).map((fileName) => {
return (
<TableRow key={fileName}>
<TableCell>{fileName}</TableCell>
<TableCell>{plotRows[fileName].date}</TableCell>
<TableCell>{plotRows[fileName].user}</TableCell>
<TableCell align={"center"}>
<Button>
<DownloadIcon />
</Button>
<Button>
<EditIcon />
</Button>
<Button onClick={() => console.log('trying to delete file')}>
<DeleteIcon />
</Button>
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</Grid>
</>
);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
"use client";
import * as React from "react";
import {subtitle, title} from "@/components/primitives";

export default function Page({ params }: { params: { plotKey: string, plotNum: string } }) {
return (
<>
<h1 className={title()}>Welcome to &nbsp;</h1>
<br />
<h1 className={title({color: "violet"})}>ForestGEO&nbsp;</h1>
<br/>
<h2 className={subtitle({class: "mt-4"})}>
A data entry and validation system for your convenience.
</h2>
<p>You have selected {params.plotKey ? params.plotKey : "nothing"}</p>
</>
);
}
Loading