diff --git a/api/ECNQueue.py b/api/ECNQueue.py index 17d9c5a..96e1078 100644 --- a/api/ECNQueue.py +++ b/api/ECNQueue.py @@ -22,10 +22,6 @@ Attributes: queueDirectory: The directory to load queues from. queuesToIgnore: Queues that will not be loaded when running getQueues() - -Raises: - # TODO: Add description(s) of when a ValueError is raised. - ValueError: [description] """ #------------------------------------------------------------------------------# @@ -62,7 +58,10 @@ #------------------------------------------------------------------------------# def isValidItemName(name: str) -> bool: - """Returns true if file name is a valid item name + """Returns true if file name is a valid item name. + + A file name is true if it contains between 1 and 3 integer numbers allowing for + any integer between 0 and 999. Example: isValidItemName("21") -> true @@ -83,16 +82,23 @@ def isValidItemName(name: str) -> bool: # Classes #------------------------------------------------------------------------------# class Item: - """A single issue. + """A chronological representation of an interaction with a user. Example: # Create an Item (ce100) - >>> item = Item("ce", 100) + >>> item = Item("ce", 100, headersOnly=false) + # Create an Item without parsing its contents (ce100) + >>> item = Item("ce", 100, headersOnly=True) + + Args: + queue (str): The name of the Item's queue. + number (int): The number of the Item. + headersOnly (bool, optional): Whether or not to parse headers only. Defaults to True. Attributes: lastUpdated: An ISO 8601 formatted time string showing the last time the file was updated according to the filesystem. headers: A list of dictionaries containing header keys and values. - content: A list of section dictionaries. + content: A list of section dictionaries (only included if headersOnly is False). isLocked: A boolean showing whether or not a lockfile for the item is present. userEmail: The email address of the person who this item is from. userName: The real name of the person who this item is from. @@ -104,21 +110,22 @@ class Item: department: The most recent department for this item. dateReceived: The date this item was created. jsonData: A JSON serializable representation of the Item. + + Raises: + ValueError: When the number passed to the constructor cannot be parsed. """ - def __init__(self, queue: str, number: int) -> None: + def __init__(self, queue: str, number: int, headersOnly: bool = False) -> None: self.queue = queue try: self.number = int(number) except ValueError: - raise ValueError(" Could not convert \"" + - number + "\" to an integer") - + raise ValueError(f'Could not convert "{number}" to an integer') self.__path = "/".join([queueDirectory, self.queue, str(self.number)]) self.lastUpdated = self.__getLastUpdated() self.__rawItem = self.__getRawItem() self.headers = self.__parseHeaders() - self.content = self.__parseSections() + if not headersOnly: self.content = self.__parseSections() self.isLocked = self.__isLocked() self.userEmail = self.__parseFromData(data="userEmail") self.userName = self.__parseFromData(data="userName") @@ -129,28 +136,12 @@ def __init__(self, queue: str, number: int) -> None: self.priority = self.__getMostRecentHeaderByType("Priority") self.department = self.__getMostRecentHeaderByType("Department") self.building = self.__getMostRecentHeaderByType("Building") - self.dateReceived = self.__getFormattedDate( - self.__getMostRecentHeaderByType("Date")) + self.dateReceived = self.__getFormattedDate(self.__getMostRecentHeaderByType("Date")) + self.jsonData = {} - # TODO: Autopopulate jsonData w/ __dir__() command. Exclude `^_` and `jsonData`. - self.jsonData = { - "queue": self.queue, - "number": self.number, - "lastUpdated": self.lastUpdated, - "headers": self.headers, - "content": self.content, - "isLocked": self.isLocked, - "userEmail": self.userEmail, - "userName": self.userName, - "userAlias": self.userAlias, - "assignedTo": self.assignedTo, - "subject": self.subject, - "status": self.status, - "priority": self.priority, - "department": self.department, - "building": self.building, - "dateReceived": self.dateReceived - } + for attribute in self.__dir__(): + if "_" not in attribute and attribute != "toJson" and attribute != "jsonData": + self.jsonData[attribute] = self.__getattribute__(attribute) def __getLastUpdated(self) -> str: """Returns last modified time of item reported by the filesystem in mm-dd-yy hh:mm am/pm format. @@ -1245,13 +1236,18 @@ def toJson(self) -> dict: def __repr__(self) -> str: return self.queue + str(self.number) -# TODO: Make Queue iterable using __iter__. See: https://thispointer.com/python-how-to-make-a-class-iterable-create-iterator-class-for-it/ class Queue: - """A collection of items. + """A collection of Items. Example: # Create a queue (ce) >>> queue = Queue("ce") + # Create a queue without parsing item contents (ce) + >>> queue = Queue("ce", headersOnly=False) + + Args: + queue (str): The name of the queue. + headersOnly (bool, optional): Whether or not to parse headers only. Defaults to True. Attributes: name: The name of the queue. @@ -1259,10 +1255,12 @@ class Queue: jsonData: A JSON serializable representation of the Queue. """ - def __init__(self, name: str) -> None: + def __init__(self, name: str, headersOnly: bool = True) -> None: self.name = name + self.headersOnly = headersOnly self.__directory = queueDirectory + "/" + self.name + "/" self.items = self.__getItems() + self._index = 0 self.jsonData = { "name": self.name, @@ -1283,7 +1281,7 @@ def __getItems(self) -> list: isFile = True if os.path.isfile(itemPath) else False if isFile and isValidItemName(item): - items.append(Item(self.name, item)) + items.append(Item(self.name, item, headersOnly=self.headersOnly)) return items @@ -1309,6 +1307,13 @@ def __len__(self) -> int: def __repr__(self) -> str: return f'{self.name}_queue' + # Implements the interable interface requirements by passing direct references + # to the item list's interable values. + def __iter__(self) -> list: + return iter(self.items) + def __next__(self) -> int: + return iter(self.items).__next__() + def getValidQueues() -> list: """Returns a list of queues on the filesystem excluding ignored queues. @@ -1359,16 +1364,24 @@ def getQueueCounts() -> list: return sortedQueueInfo - -def loadQueues() -> list: +def loadAllQueues(headersOnly: bool = True) -> list: """Return a list of Queues for each queue. + Example: + # Load all Queues without parsing Item content + >>> loadAllQueues(); + Load all Queues and parsing Item content + >>> loadAllQueues(headersOnly=False) + + Args: + headersOnly (bool, optional): Whether or not to parse headers only. Defaults to True. + Returns: - list: list of Queues for each queue. + list: List of Queues for each queue. """ queues = [] for queue in getValidQueues(): - queues.append(Queue(queue)) + queues.append(Queue(queue, headersOnly=headersOnly)) return queues \ No newline at end of file diff --git a/api/api.py b/api/api.py index 73128f6..d8b0600 100644 --- a/api/api.py +++ b/api/api.py @@ -162,7 +162,6 @@ def get(self, queue: str, number: int) -> tuple: 200 (OK): On success. Example: - /api/ce/100 returns: { "lastUpdated": "07-23-20 10:11 PM", "headers": [...], @@ -187,13 +186,21 @@ def get(self, queue: str, number: int) -> tuple: Returns: tuple: Item as JSON and HTTP response code. """ - return (ECNQueue.Item(queue, number).toJson(), 200) + + headersOnly = True if request.args.get("headersOnly") == "True" else False + return ECNQueue.Item(queue, number, headersOnly=headersOnly).toJson() class Queue(Resource): @jwt_required def get(self, queues: str) -> tuple: """Returns the JSON representation of the queue requested. + Example: + { + "name": ce, + "items": [...] + } + Return Codes: 200 (OK): On success. @@ -203,12 +210,12 @@ def get(self, queues: str) -> tuple: Returns: tuple: Queues as JSON and HTTP response code. """ + headersOnly = False if request.args.get("headersOnly") == "False" else True queues_requested = queues.split("+") queue_list = [] for queue in queues_requested: - queue_list.append(ECNQueue.Queue(queue).toJson()) - + queue_list.append(ECNQueue.Queue(queue, headersOnly=headersOnly).toJson()) return (queue_list, 200) class QueueList(Resource): @@ -235,9 +242,7 @@ def get(self) -> tuple: tuple: Queues and item counts as JSON and HTTP response code. """ return (ECNQueue.getQueueCounts(), 200) - - - + api.add_resource(Login, "/login") api.add_resource(RefreshAccessToken, "/tokens/refresh") api.add_resource(Item, "/api//") diff --git a/src/components/AppView/AppView.js b/src/components/AppView/AppView.js index 75c7c60..abb7e67 100644 --- a/src/components/AppView/AppView.js +++ b/src/components/AppView/AppView.js @@ -11,46 +11,59 @@ import QueueSelector from "../QueueSelector/"; import { useToken } from "../AuthProvider/"; export default function AppView({ setDarkMode }){ - const [activeItem, setActiveItem] = useState({}); + // Create stateful variables. const [sidebarOpen, setSidebarOpen] = useState(false); const [queues, setQueues] = useState([]); const [items, setItems] = useState([]); const [selectedQueues, setSelectedQueues] = useState([]); const [queueSelectorOpen, setQueueSelectorOpen] = useState(false); + const [isLoading, setIsLoading] = useState(false); const access_token = useToken(); + // Get Queues from API. useEffect( _ => { - async function getQueues(){ + (async function getQueues(){ if (access_token === null){ - return undefined + return undefined; } if (queueSelectorOpen){ - return undefined + return undefined; } - if (selectedQueues.length > 0){ - let queuesToLoad = ""; - - for (let selectedQueue of selectedQueues){ - queuesToLoad += `+${selectedQueue.name}`; - } + if (selectedQueues.length === 0){ + setQueues([]) + return undefined; + } - let myHeaders = new Headers(); - myHeaders.append("Authorization", `Bearer ${access_token}`); - let requestOptions = { headers: myHeaders }; + setIsLoading(true); + let queuesToLoad = ""; - const apiResponse = await fetch(`/api/${queuesToLoad}`, requestOptions); - const queueJson = await apiResponse.json(); - setQueues(queueJson); - } else { - setQueues([]) + if (selectedQueues.length === 1){ + queuesToLoad = selectedQueues[0].name; } - } - getQueues(); + else if (selectedQueues.length > 0){ + selectedQueues.forEach( (queue, index) => ( + index === 0 + ? queuesToLoad += queue.name + : queuesToLoad += `+${queue.name}` + )); + } + + let myHeaders = new Headers(); + myHeaders.append("Authorization", `Bearer ${access_token}`); + let requestOptions = { headers: myHeaders }; + + const apiResponse = await fetch(`/api/${queuesToLoad}`, requestOptions); + const queueJson = await apiResponse.json(); + + setQueues(queueJson); + setIsLoading(false) + })(); }, [selectedQueues, access_token, queueSelectorOpen]); + // Populate items array. useEffect( _ => { let tempItems = []; for (let queue of queues){ @@ -94,7 +107,6 @@ export default function AppView({ setDarkMode }){ return( - - + - {items.length === 0 ? null : { - const item = items.find((item) => { - return item.queue === match.params.queue && item.number === Number(match.params.number); - }); - - if (item === undefined) { - return ( - - ); - } - - setActiveItem(item); - - return ( - <> - - - - ); - } - } + render={({ match }) => ( + <> + + + + )} /> } diff --git a/src/components/ItemBodyView/ItemBodyView.js b/src/components/ItemBodyView/ItemBodyView.js index 08a57f9..950f7ca 100644 --- a/src/components/ItemBodyView/ItemBodyView.js +++ b/src/components/ItemBodyView/ItemBodyView.js @@ -7,9 +7,9 @@ import Assignment from "../Assignment/"; import TimelineActionCard from "../TimelineActionCard/"; import MessageView from "../MessageView/"; import ParseError from "../ParseError/"; -import { objectIsEmpty } from "../../utilities"; +import TimelineSkeleton from "../TimelineSkeleton/"; -export default function ItemBodyView({ item }) { +export default function ItemBodyView({ sections, loading }) { const useStyles = makeStyles(() => ({ "Timeline-root": { @@ -30,6 +30,11 @@ export default function ItemBodyView({ item }) { })); const classes = useStyles(); + /** + * Returns a section type specific timeline item. + * @param {Object} section The + * @returns {Node} A section type specific timeline item. + */ const generateTimelineItem = (section) => { switch (section.type) { case "directory_information": @@ -53,30 +58,48 @@ export default function ItemBodyView({ item }) { }; }; + const TimelineItemTemplate = ({ children }) => ( + + + + + + + {children} + + + ); + return ( - {objectIsEmpty(item) ? "" : item.content.map((section) => ( - - - - - - - {generateTimelineItem(section)} - - - ))} + { loading + ? ( // Generate 3 placeholders. + [...Array(3).keys()].map( (_, index) => ( + + + + )) + ) + : ( // Generate timeline. + sections.map((section) => ( + + {generateTimelineItem(section)} + + )) + ) + } ); }; ItemBodyView.propTypes = { - /** The item to diplay. */ - "item": PropTypes.object.isRequired -}; \ No newline at end of file + /** Section of an item to display. */ + "sections": PropTypes.array, + /** If true, shows loading placeholder. */ + "loading": PropTypes.bool +}; + +ItemBodyView.defaultProps = { + "sections": [], + "loading": false +} \ No newline at end of file diff --git a/src/components/ItemBodyView/ItemBodyView.md b/src/components/ItemBodyView/ItemBodyView.md index 6a741ea..f92f979 100644 --- a/src/components/ItemBodyView/ItemBodyView.md +++ b/src/components/ItemBodyView/ItemBodyView.md @@ -8,15 +8,16 @@ The ItemBodyView displays the seven actions possible in an item: - **Reply To User:** a message sent from an ECN employee to a user. - **Reply To ECN:** a message sent from the user to ECN that has been merged into an existing item. -```jsx -import ItemBodyView from "./ItemBodyView"; +## Default View +![ItemBodyView_Loaded](/ItemBodyView_Loaded.png) -const demoItem = {"queue": "ce", "number": 100, "lastUpdated": "09-28-20 01:26 PM", "headers": [{"type": "Merged-Time", "content": "Tue, 23 Jun 2020 13:31:53 -0400"}, {"type": "Merged-By", "content": "campb303"}, {"type": "QTime", "content": "1"}, {"type": "QTime-Updated-Time", "content": "Tue, 23 Jun 2020 13:28:50 EDT"}, {"type": "QTime-Updated-By", "content": "campb303"}, {"type": "Time", "content": "1"}, {"type": "Time-Updated-Time", "content": "Tue, 23 Jun 2020 13:28:50 EDT"}, {"type": "Time-Updated-By", "content": "campb303"}, {"type": "Replied-Time", "content": "Tue, 23 Jun 2020 13:28:48 -0400"}, {"type": "Replied-By", "content": "campb303"}, {"type": "Edited-Time", "content": "Tue, 23 Jun 2020 13:27:56 -0400"}, {"type": "Edited-By", "content": "campb303"}, {"type": "QAssigned-To", "content": "campb303"}, {"type": "QAssigned-To-Updated-Time", "content": "Tue, 23 Jun 2020 13:27:00 EDT"}, {"type": "QAssigned-To-Updated-By", "content": "campb303"}, {"type": "Assigned-To", "content": "campb303"}, {"type": "Assigned-To-Updated-Time", "content": "Tue, 23 Jun 2020 13:27:00 EDT"}, {"type": "Assigned-To-Updated-By", "content": "campb303"}, {"type": "QStatus", "content": "Dont Delete"}, {"type": "QStatus-Updated-Time", "content": "Tue, 23 Jun 2020 13:26:55 EDT"}, {"type": "QStatus-Updated-By", "content": "campb303"}, {"type": "Status", "content": "Dont Delete"}, {"type": "Status-Updated-Time", "content": "Tue, 23 Jun 2020 13:26:55 EDT"}, {"type": "Status-Updated-By", "content": "campb303"}, {"type": "Date", "content": "Tue, 23 Jun 2020 13:25:51 -0400"}, {"type": "From", "content": "Justin Campbell "}, {"type": "Message-ID", "content": "<911CE050-3240-4980-91DD-9C3EBB8DBCF8@purdue.edu>"}, {"type": "Subject", "content": "Beepboop"}, {"type": "To", "content": "cesite@ecn.purdue.edu"}, {"type": "Content-Type", "content": "text/plain; charset=\"utf-8\""}, {"type": "X-ECN-Queue-Original-Path", "content": "/home/pier/e/queue/Attachments/inbox/2020-06-23/208-original.txt"}, {"type": "X-ECN-Queue-Original-URL", "content": "https://engineering.purdue.edu/webqueue/Attachments/inbox/2020-06-23/208-original.txt"}], "content": [{"type": "directory_information", "Name": "Heyi Feng", "Login": "feng293", "Computer": "civil4147pc2.ecn", "Location": "HAMP 4147", "Email": "feng293@purdue.edu", "Phone": "5039154835", "Office": "", "UNIX Dir": "None", "Zero Dir": "U=\\\\myhome.itap.purdue.edu\\myhome\\%username%", "User ECNDB": "http://eng.purdue.edu/jump/2e29495", "Host ECNDB": "http://eng.purdue.edu/jump/2eccc3f", "Subject": "Upgrade system and Abaqus"}, {"type": "assignment", "datetime": "2020-06-23T13:27:00-0400", "by": "campb303", "to": "campb303"}, {"type": "initial_message", "datetime": "2020-06-23T13:25:51-0400", "from_name": "Justin Campbell", "user_email": "campb303@purdue.edu", "to": [{"name": "", "email": "cesite@ecn.purdue.edu"}], "cc": [], "content": ["Testtest\n"]}, {"type": "status", "datetime": "2020-06-23T13:26:55", "by": "campb303", "content": ["Dont Delete\n"]}, {"type": "edit", "datetime": "2020-06-23T13:27:56", "by": "campb303", "content": ["This be an edit my boy\n"]}, {"type": "reply_to_user", "datetime": "2020-06-23T13:28:18", "by": "campb303", "content": ["This be a reply my son\n", "\n", "Justin\n", "ECN\n"]}, {"type": "reply_from_user", "datetime": "2020-06-23T13:30:45-0400", "from_name": "Justin Campbell", "from_email": "campb303@purdue.edu", "cc": [], "content": ["X-ECN-Queue-Original-Path: /home/pier/e/queue/Attachments/inbox/2020-06-23/212-original.txt\n", "X-ECN-Queue-Original-URL: https://engineering.purdue.edu/webqueue/Attachments/inbox/2020-06-23/212-original.txt\n", "\n", "Huzzah!\n"]}], "isLocked": "ce 100 is locked by knewell using qvi", "userEmail": "campb303@purdue.edu", "userName": "Justin Campbell", "userAlias": "campb303", "assignedTo": "campb303", "subject": "Beepboop", "status": "Dont Delete", "priority": "", "department": "", "building": "", "dateReceived": "2020-06-23T13:25:51-0400"}; -
- -
+```jsx static + ``` +## Loading View +![ItemBodyView_Loaded](/ItemBodyView_Loading.gif) + ```jsx static - + ``` \ No newline at end of file diff --git a/src/components/ItemMetadataView/ItemMetadataView.js b/src/components/ItemMetadataView/ItemMetadataView.js index 05f6357..6c4e4aa 100644 --- a/src/components/ItemMetadataView/ItemMetadataView.js +++ b/src/components/ItemMetadataView/ItemMetadataView.js @@ -33,11 +33,6 @@ export default function ItemMetadataView({item}){ {item.subject} - - - Status, assignments, priority, refile, archive and delete controls coming soon to a theater near you. - - ); } diff --git a/src/components/ItemProvider/ItemProvider.js b/src/components/ItemProvider/ItemProvider.js new file mode 100644 index 0000000..b3d15e3 --- /dev/null +++ b/src/components/ItemProvider/ItemProvider.js @@ -0,0 +1,21 @@ +import React, { useState, createContext, useContext, useEffect } from "react"; + +const ItemContext = createContext(); +const ItemSetterContext = createContext(); + +export const useItem = () => useContext(ItemContext); +export const useItemSetter = () => useContext(ItemSetterContext); + + + +export default function ItemProvider({ children }) { + const [item, setItem] = useState( {} ); + + return ( + + + {children} + + + ); +}; \ No newline at end of file diff --git a/src/components/ItemProvider/ItemProvider.md b/src/components/ItemProvider/ItemProvider.md new file mode 100644 index 0000000..4653d82 --- /dev/null +++ b/src/components/ItemProvider/ItemProvider.md @@ -0,0 +1,41 @@ +Utility component that uses [React Contexts](https://reactjs.org/docs/context.html) [React Stateful Variables](https://reactjs.org/docs/hooks-state.html) to provide global access to the active item object. + +Two functions are exported: + +Function | Descrioption +- | - +`useItem` | Returns a reference to the state variable holding the current Item. Defaults to `false`. +`useItemSetter` | Returns a reference to the state variable update function. + +For an in depth explanation of this pattern, see [this GitHub comment](https://github.itap.purdue.edu/ECN/webqueue2/issues/15#issuecomment-341). + + +## Usage +```jsx static +// App + + + +``` + +```jsx static +// SomeComponent +import { useEffect } from "react"; +import { useItem, useItemSetter } from "ItemProvider"; + +const activeItem = useItem(); +const setActiveItem = useItemSetter(); + +useEffect( + let item = someFuncToGetItem(); + setActiveItem(item); +); + +return( + { + item + ?

{`${activeItem.queue} ${activeItem.number} was last updated ${activeItem.lastUpdated}.`}

+ :

No item is currently loaded.

+ } +); +``` \ No newline at end of file diff --git a/src/components/ItemProvider/index.js b/src/components/ItemProvider/index.js new file mode 100644 index 0000000..3186bd3 --- /dev/null +++ b/src/components/ItemProvider/index.js @@ -0,0 +1 @@ +export {default, useItem, useItemSetter } from "./ItemProvider"; \ No newline at end of file diff --git a/src/components/ItemTable/ItemTable.js b/src/components/ItemTable/ItemTable.js index 497296d..424d55e 100644 --- a/src/components/ItemTable/ItemTable.js +++ b/src/components/ItemTable/ItemTable.js @@ -1,19 +1,25 @@ import React, { useState } from "react"; import PropTypes from "prop-types"; import { useTable, useFilters, useFlexLayout, useSortBy } from "react-table"; -import { Table, TableBody, TableCell, TableHead, TableRow, TableContainer, Paper, Grid, ButtonGroup, IconButton, makeStyles, useTheme } from "@material-ui/core"; +import { Table, TableBody, TableCell, TableHead, TableRow, TableContainer, Box, Grid, ButtonGroup, IconButton, makeStyles, useTheme } from "@material-ui/core"; import { useHistory } from "react-router-dom"; import RelativeTime from "react-relative-time"; import ItemTableFilter from "../ItemTableFilter/" import { ArrowDownward, ArrowUpward } from "@material-ui/icons"; import ItemTableCell from "../ItemTableCell"; import LastUpdatedCell from "../LastUpdatedCell/"; +import jester from "./loading-annimation.gif"; -export default function ItemTable({ data, rowCanBeSelected }) { +export default function ItemTable({ data, rowCanBeSelected, loading }) { const [selectedRow, setSelectedRow] = useState({ queue: null, number: null }); const theme = useTheme(); const useStyles = makeStyles({ + loadingAnnimation: { + display: "flex", + justifyContent: "center", + width: "100%" + }, hoverBackgroundColor: { "&:hover": { // The !important is placed here to enforce CSS specificity. @@ -44,7 +50,7 @@ export default function ItemTable({ data, rowCanBeSelected }) { () => [ { Header: 'Queue', accessor: 'queue', }, { Header: 'Item #', accessor: 'number' }, - { Header: 'From', accessor: 'userAlias'}, + { Header: 'From', accessor: 'userAlias' }, { Header: 'Assigned To', accessor: 'assignedTo' }, { Header: 'Subject', accessor: 'subject' }, { Header: 'Status', accessor: 'status', }, @@ -53,7 +59,7 @@ export default function ItemTable({ data, rowCanBeSelected }) { { Header: 'Department', accessor: 'department' }, { Header: 'Building', accessor: 'building' }, { Header: 'Date Received', accessor: 'dateReceived', sortInverted: true, Cell: ({ value }) => }, - + ], []); const tableInstance = useTable( { @@ -84,121 +90,128 @@ export default function ItemTable({ data, rowCanBeSelected }) { const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow, } = tableInstance; return ( - - - - {headerGroups.map(headerGroup => ( - - {headerGroup.headers.map(column => ( - - - - - {column.render("Filter")} - - - - { - const isSortedAsc = column.isSorted && !column.isSortedDesc; - isSortedAsc ? column.clearSortBy() : column.toggleSortBy(false) - })} - > - - - { - const isSortedDesc = column.isSorted && column.isSortedDesc; - isSortedDesc ? column.clearSortBy() : column.toggleSortBy(true) - })} - > - - - + loading + ? ( + + Items are loading. + + ) + : ( + +
+ + {headerGroups.map(headerGroup => ( + + {headerGroup.headers.map(column => ( + + + + {column.render("Filter")} + + + + { + const isSortedAsc = column.isSorted && !column.isSortedDesc; + isSortedAsc ? column.clearSortBy() : column.toggleSortBy(false) + })} + > + + + { + const isSortedDesc = column.isSorted && column.isSortedDesc; + isSortedDesc ? column.clearSortBy() : column.toggleSortBy(true) + })} + > + + + + - - - - ))} - - ))} - - - {rows.map((row) => { - prepareRow(row); - let isSelected = selectedRow.queue === row.original.queue && selectedRow.number === row.original.number - return ( - { - history.push(`/${row.original.queue}/${row.original.number}`); - setSelectedRow({ queue: row.original.queue, number: row.original.number }); - }} - // This functionality should be achieved by using the selected prop and - // overriding the selected class but this applied the secondary color at 0.08% opacity. - // Overridding the root class is a workaround. - classes={{ - root: (isSelected && rowCanBeSelected) ? classes.rowSelected : classes.bandedRows, - hover: classes.hoverBackgroundColor - }} - {...row.getRowProps()} - > - {row.cells.map(cell => ( - cell.render(_ => { - switch (cell.column.id) { - case "dateReceived": - return ( - - - - ); - case "lastUpdated": - return ( - - ); - default: - return ( - - {cell.value} - - ); - } - }) - ))}; + + ))} - ); - })} - -
-
+ ))} + + + {rows.map((row) => { + prepareRow(row); + let isSelected = selectedRow.queue === row.original.queue && selectedRow.number === row.original.number + return ( + { + history.push(`/${row.original.queue}/${row.original.number}`); + setSelectedRow({ queue: row.original.queue, number: row.original.number }); + }} + // This functionality should be achieved by using the selected prop and + // overriding the selected class but this applied the secondary color at 0.08% opacity. + // Overridding the root class is a workaround. + classes={{ + root: (isSelected && rowCanBeSelected) ? classes.rowSelected : classes.bandedRows, + hover: classes.hoverBackgroundColor + }} + {...row.getRowProps()} + > + {row.cells.map(cell => ( + cell.render(_ => { + switch (cell.column.id) { + case "dateReceived": + return ( + + + + ); + case "lastUpdated": + return ( + + ); + default: + return ( + + {cell.value} + + ); + } + }) + ))} + + ); + })} + + + + ) ); }; ItemTable.propTypes = { /** Array of items from all active queues to display in table. */ "items": PropTypes.array, - /** State variable indicating if rows can be selected. When false, all rows are deselected. */ - "rowCanBeSelected": PropTypes.bool + /** If true, rows can be selected. */ + "rowCanBeSelected": PropTypes.bool, + /** If true, ItemTable displays loading screen. */ + "loading": PropTypes.bool }; ItemTable.defaultProps = { - /** The items to display in the table. */ "items": [], - /** A state variable determining whether a row can be selected or not. */ - "rowCanBeSelected": true + "rowCanBeSelected": true, + "loading": false }; diff --git a/src/components/ItemTable/loading-annimation.gif b/src/components/ItemTable/loading-annimation.gif new file mode 100644 index 0000000..c657308 Binary files /dev/null and b/src/components/ItemTable/loading-annimation.gif differ diff --git a/src/components/ItemTableCell/ItemTableCell.js b/src/components/ItemTableCell/ItemTableCell.js index cf13a74..38bacee 100644 --- a/src/components/ItemTableCell/ItemTableCell.js +++ b/src/components/ItemTableCell/ItemTableCell.js @@ -26,7 +26,11 @@ export default function ItemTableCell({ children, TableCellProps }) { ItemTableCell.propTypes = { /** Child object passed to display cell data. */ - "children": PropTypes.object, + "children": PropTypes.oneOfType([ + PropTypes.string, + PropTypes.number, + PropTypes.element + ]), /** Props applied to the TableCell component. */ "TableCellProps": PropTypes.object }; diff --git a/src/components/ItemTableFilter/ItemTableFilter.js b/src/components/ItemTableFilter/ItemTableFilter.js index c3ef252..2c61967 100644 --- a/src/components/ItemTableFilter/ItemTableFilter.js +++ b/src/components/ItemTableFilter/ItemTableFilter.js @@ -24,7 +24,6 @@ export default function ItemTableFilter({ label, onChange }) { > {label} diff --git a/src/components/ItemView/ItemView.js b/src/components/ItemView/ItemView.js index 8bd7eda..ce6e65e 100644 --- a/src/components/ItemView/ItemView.js +++ b/src/components/ItemView/ItemView.js @@ -1,15 +1,58 @@ -import React, { useState } from 'react'; +import React, { useState, useEffect } from 'react'; import PropTypes from "prop-types"; -import { Paper, AppBar, Tab, makeStyles, useTheme } from '@material-ui/core'; +import { Paper, AppBar, Tab, makeStyles, useTheme, Box, Typography } from '@material-ui/core'; // Import these tab components from @material-ui/lab instead of @material-ui/core for automatic a11y props // See: https://material-ui.com/components/tabs/#experimental-api import { TabContext, TabList, TabPanel } from '@material-ui/lab'; -import ItemMetadataView from "../ItemMetadataView/" +import ItemMetadataView from "../ItemMetadataView" import ItemBodyView from "../ItemBodyView"; import ItemHeaderView from "../ItemHeaderView"; +import { useItem, useItemSetter } from "../ItemProvider"; +import { useToken } from "../AuthProvider/"; -export default function ItemView({ activeItem }){ +export default function ItemView() { + let { queue, number } = {queue: "test", number: 1}; + // Set stateful variables const [activeTab, setActiveTab] = useState('Conversation'); + const [isLoading, setIsLoading] = useState(false); + const [error, setError] = useState(false); + + // Set contextual variables + const activeItem = useItem(); + const setActiveItem = useItemSetter(); + const access_token = useToken(); + + // Get full Item from API + useEffect(_ => { + (async _ => { + if (access_token === null) { + return undefined; + } + + if (activeItem.queue === queue && activeItem.number == number) { + return undefined; + } + + setIsLoading(true); + + let myHeaders = new Headers(); + myHeaders.append("Authorization", `Bearer ${access_token}`); + let requestOptions = { headers: myHeaders }; + + const apiResponse = await fetch(`/api/${queue}/${number}`, requestOptions); + + if (!apiResponse.ok) { + console.error(`Fetching item ${queue}${number}. Got code ${apiResponse.status} (${apiResponse.statusText})`); + setError(true); + return undefined; + } + + const itemJson = await apiResponse.json(); + + setActiveItem(itemJson); + setIsLoading(false) + })(); + }, [access_token, activeItem, setActiveItem, queue, number]); const theme = useTheme(); const useStyles = makeStyles({ @@ -21,6 +64,13 @@ export default function ItemView({ activeItem }){ }, "tabPanelPadding": { padding: `${theme.spacing(2)}px ${theme.spacing(2)}px` + }, + errorContainer: { + display: "flex", + flexDirection: "column", + alignItems: "center", + justifyContent: "center", + marginTop: theme.spacing(6) } }); const classes = useStyles(); @@ -29,28 +79,48 @@ export default function ItemView({ activeItem }){ setActiveTab(newValue); }; - return( - - - - - - - - - - - - - - - - + return ( + + {error ? ( + + + 4☹4 + + + Something went wrong. + + + {`Item ${queue}${number} could not be found.`} + + + ) : ( + <> + + + + + + + + + + + + + + + + + + + )} ); }; ItemView.propTypes = { - /** The item to be viewed. */ - "activeItem": PropTypes.object.isRequired + /** The queue of the item to load. */ + "queue": PropTypes.string.isRequired, + /** The number of the item to load. */ + "number": PropTypes.number.isRequired }; \ No newline at end of file diff --git a/src/components/ItemView/ItemView.md b/src/components/ItemView/ItemView.md index a9e1ef0..61eee38 100644 --- a/src/components/ItemView/ItemView.md +++ b/src/components/ItemView/ItemView.md @@ -1,13 +1,5 @@ The ItemView is the primary view for an item. It displays the messages and actions in a timeline view. -```jsx -import React, { useState } from "react"; - -const demoItem = {"queue": "ce", "number": 100, "lastUpdated": "07-23-20 10:11 PM", "headers": [{"type": "Merged-Time", "content": "Tue, 23 Jun 2020 13:31:53 -0400"}, {"type": "Merged-By", "content": "campb303"}, {"type": "QTime", "content": "1"}, {"type": "QTime-Updated-Time", "content": "Tue, 23 Jun 2020 13:28:50 EDT"}, {"type": "QTime-Updated-By", "content": "campb303"}, {"type": "Time", "content": "1"}, {"type": "Time-Updated-Time", "content": "Tue, 23 Jun 2020 13:28:50 EDT"}, {"type": "Time-Updated-By", "content": "campb303"}, {"type": "Replied-Time", "content": "Tue, 23 Jun 2020 13:28:48 -0400"}, {"type": "Replied-By", "content": "campb303"}, {"type": "Edited-Time", "content": "Tue, 23 Jun 2020 13:27:56 -0400"}, {"type": "Edited-By", "content": "campb303"}, {"type": "QAssigned-To", "content": "campb303"}, {"type": "QAssigned-To-Updated-Time", "content": "Tue, 23 Jun 2020 13:27:00 EDT"}, {"type": "QAssigned-To-Updated-By", "content": "campb303"}, {"type": "Assigned-To", "content": "campb303"}, {"type": "Assigned-To-Updated-Time", "content": "Tue, 23 Jun 2020 13:27:00 EDT"}, {"type": "Assigned-To-Updated-By", "content": "campb303"}, {"type": "QStatus", "content": "Dont Delete"}, {"type": "QStatus-Updated-Time", "content": "Tue, 23 Jun 2020 13:26:55 EDT"}, {"type": "QStatus-Updated-By", "content": "campb303"}, {"type": "Status", "content": "Dont Delete"}, {"type": "Status-Updated-Time", "content": "Tue, 23 Jun 2020 13:26:55 EDT"}, {"type": "Status-Updated-By", "content": "campb303"}, {"type": "Date", "content": "Tue, 23 Jun 2020 13:25:51 -0400"}, {"type": "From", "content": "Justin Campbell "}, {"type": "Message-ID", "content": "<911CE050-3240-4980-91DD-9C3EBB8DBCF8@purdue.edu>"}, {"type": "Subject", "content": "Beepboop"}, {"type": "To", "content": "cesite@ecn.purdue.edu"}, {"type": "Content-Type", "content": "text/plain; charset=\"utf-8\""}, {"type": "X-ECN-Queue-Original-Path", "content": "/home/pier/e/queue/Attachments/inbox/2020-06-23/208-original.txt"}], "content": ["Testtest\n", "\n", "*** Status updated by: campb303 at: 6/23/2020 13:26:55 ***\n", "Dont Delete\n", "*** Edited by: campb303 at: 06/23/20 13:27:56 ***\n", "\n", "This be an edit my boy\n", "\n", "\n", "\n", "*** Replied by: campb303 at: 06/23/20 13:28:18 ***\n", "\n", "This be a reply my son\n", "\n", "Justin\n", "ECN\n", "\n", "=== Additional information supplied by user ===\n", "\n", "Subject: Re: Beepboop\n", "From: Justin Campbell \n", "Date: Tue, 23 Jun 2020 13:30:45 -0400\n", "X-ECN-Queue-Original-Path: /home/pier/e/queue/Attachments/inbox/2020-06-23/212-original.txt\n", "X-ECN-Queue-Original-URL: https://engineering.purdue.edu/webqueue/Attachments/inbox/2020-06-23/212-original.txt\n", "\n", "Huzzah!\n", "\n", "===============================================\n"], "isLocked": "ce 100 is locked by knewell using qvi", "userEmail": "campb303@purdue.edu", "userName": "Justin Campbell", "userAlias": "campb303", "assignedTo": "campb303", "subject": "Beepboop", "status": "Dont Delete", "priority": "", "department": "", "building": "", "dateReceived": "Tue, 23 Jun 2020 13:25:51 -0400"}; - - -``` - ```jsx static - + ``` \ No newline at end of file diff --git a/src/components/TimelineSkeleton/TimelineSkeleton.js b/src/components/TimelineSkeleton/TimelineSkeleton.js new file mode 100644 index 0000000..6c2d15d --- /dev/null +++ b/src/components/TimelineSkeleton/TimelineSkeleton.js @@ -0,0 +1,34 @@ +import React from "react"; +import { Paper, Typography, makeStyles, useTheme } from '@material-ui/core'; +import { Skeleton } from '@material-ui/lab'; + +export default function TimelineSkeleton(){ + + const theme = useTheme(); + const useStyles = makeStyles({ + "Paper-root": { + overflow: "hidden" + }, + "padding": { + padding: theme.spacing(1) + } + + }); + const classes = useStyles(); + + return( + +
+ + + +
+
+ { + // Generate 2 placeholders. + [...Array(2).keys()].map( (_, index) => ) + } +
+
+ ); +} \ No newline at end of file diff --git a/src/components/TimelineSkeleton/TimelineSkeleton.md b/src/components/TimelineSkeleton/TimelineSkeleton.md new file mode 100644 index 0000000..c13a7fe --- /dev/null +++ b/src/components/TimelineSkeleton/TimelineSkeleton.md @@ -0,0 +1,17 @@ +Renders a skeleton UI to indicate loading of a timeline item. + +```jsx +import { ThemeProvider } from "@material-ui/core/styles"; +import webqueue2Theme from "../../theme"; +import TimelineActionCard from "./TimelineSkeleton"; + +const theme = webqueue2Theme(false); + + + + +``` + +```jsx static + +``` \ No newline at end of file diff --git a/src/components/TimelineSkeleton/index.js b/src/components/TimelineSkeleton/index.js new file mode 100644 index 0000000..0d8e1b3 --- /dev/null +++ b/src/components/TimelineSkeleton/index.js @@ -0,0 +1 @@ +export { default } from "./TimelineSkeleton"; \ No newline at end of file diff --git a/src/index.js b/src/index.js index 799ad12..86dc439 100644 --- a/src/index.js +++ b/src/index.js @@ -7,6 +7,8 @@ import { CssBaseline } from '@material-ui/core'; import { BrowserRouter as Router } from 'react-router-dom'; import { CookiesProvider } from "react-cookie"; import AuthProvider from "./components/AuthProvider/"; +import ItemProvider from "./components/ItemProvider/"; + export const history = createBrowserHistory({ basename: process.env.PUBLIC_URL @@ -17,9 +19,11 @@ ReactDOM.render( - - - + + + + + , diff --git a/styleguidist/assetsDir/ItemBodyView_Loaded.png b/styleguidist/assetsDir/ItemBodyView_Loaded.png new file mode 100644 index 0000000..b99e9f5 Binary files /dev/null and b/styleguidist/assetsDir/ItemBodyView_Loaded.png differ diff --git a/styleguidist/assetsDir/ItemBodyView_Loading.gif b/styleguidist/assetsDir/ItemBodyView_Loading.gif new file mode 100644 index 0000000..3329413 Binary files /dev/null and b/styleguidist/assetsDir/ItemBodyView_Loading.gif differ diff --git a/styleguidist/styleguide.config.js b/styleguidist/styleguide.config.js index de44a92..12e4a94 100644 --- a/styleguidist/styleguide.config.js +++ b/styleguidist/styleguide.config.js @@ -6,6 +6,15 @@ const path = require('path') module.exports = { + + /** + * Static assets folder. Accessible as / in the style guide dev server. + * @type {string | array} + * @example "/" + * @default undefined + */ + assetsDir: "assetsDir", + /** * The title that appears at the top of the navigation bar. * @type {string} @@ -119,7 +128,7 @@ module.exports = { */ getComponentPathLine(componentPath) { const name = path.basename(componentPath, '.js') - return `import ${name} from './components/${name}/';` + return `import ${name} from '../components/${name}/';` }, /**