1
0
Fork 0
mirror of https://github.com/pawelmalak/flame.git synced 2025-07-22 21:09:36 +02:00

Compare commits

..

No commits in common. "master" and "v2.0" have entirely different histories.
master ... v2.0

161 changed files with 12246 additions and 31674 deletions

View file

@ -1 +0,0 @@
docker build -t flame:dev -f .docker/Dockerfile .

View file

@ -1,2 +0,0 @@
docker build -t pawelmalak/flame -t "pawelmalak/flame:$1" -f .docker/Dockerfile . \
&& docker push pawelmalak/flame && docker push "pawelmalak/flame:$1"

View file

@ -1,6 +0,0 @@
docker buildx build \
--platform linux/arm/v7,linux/arm64,linux/amd64 \
-f .docker/Dockerfile.multiarch \
-t pawelmalak/flame:multiarch \
-t "pawelmalak/flame:multiarch$1" \
--push .

View file

@ -1,4 +1,4 @@
FROM node:16 as builder FROM node:14 as builder
WORKDIR /app WORKDIR /app
@ -16,7 +16,7 @@ RUN mkdir -p ./public ./data \
&& mv ./client/build/* ./public \ && mv ./client/build/* ./public \
&& rm -rf ./client && rm -rf ./client
FROM node:16-alpine FROM node:14-alpine
COPY --from=builder /app /app COPY --from=builder /app /app
@ -27,4 +27,4 @@ EXPOSE 5005
ENV NODE_ENV=production ENV NODE_ENV=production
ENV PASSWORD=flame_password ENV PASSWORD=flame_password
CMD ["sh", "-c", "chown -R node /app/data && node server.js"] CMD ["node", "server.js"]

View file

@ -1,10 +1,10 @@
FROM node:16-alpine3.11 as builder FROM node:14-alpine3.11 as builder
WORKDIR /app WORKDIR /app
COPY package*.json ./ COPY package*.json ./
RUN apk --no-cache --virtual build-dependencies add python python3 make g++ \ RUN apk --no-cache --virtual build-dependencies add python make g++ \
&& npm install --production && npm install --production
COPY . . COPY . .
@ -17,7 +17,7 @@ RUN mkdir -p ./public ./data \
&& mv ./client/build/* ./public \ && mv ./client/build/* ./public \
&& rm -rf ./client && rm -rf ./client
FROM node:16-alpine3.11 FROM node:14-alpine3.11
COPY --from=builder /app /app COPY --from=builder /app /app
@ -28,4 +28,4 @@ EXPOSE 5005
ENV NODE_ENV=production ENV NODE_ENV=production
ENV PASSWORD=flame_password ENV PASSWORD=flame_password
CMD ["sh", "-c", "chown -R node /app/data && node server.js"] CMD ["node", "server.js"]

View file

@ -1,22 +1,12 @@
version: '3.6' version: '3'
services: services:
flame: flame:
image: pawelmalak/flame image: pawelmalak/flame
container_name: flame container_name: flame
volumes: volumes:
- /path/to/host/data:/app/data - /path/to/data:/app/data
# - /var/run/docker.sock:/var/run/docker.sock # optional but required for Docker integration
ports: ports:
- 5005:5005 - 5005:5005
# secrets:
# - password # optional but required for (1)
environment: environment:
- PASSWORD=flame_password - PASSWORD=flame_password
# - PASSWORD_FILE=/run/secrets/password # optional but required for (1)
restart: unless-stopped restart: unless-stopped
# optional but required for Docker secrets (1)
# secrets:
# password:
# file: /path/to/secrets/password

View file

@ -2,5 +2,4 @@ node_modules
.github .github
public public
k8s k8s
skaffold.yaml skaffold.yaml
data

2
.env
View file

@ -1,5 +1,5 @@
PORT=5005 PORT=5005
NODE_ENV=development NODE_ENV=development
VERSION=2.3.1 VERSION=2.0.0
PASSWORD=flame_password PASSWORD=flame_password
SECRET=e02eb43d69953658c6d07311d6313f2d4467672cb881f96b29368ba1f3f4da4b SECRET=e02eb43d69953658c6d07311d6313f2d4467672cb881f96b29368ba1f3f4da4b

View file

@ -1,27 +0,0 @@
---
name: Bug report
about: Create a bug report
title: "[BUG] "
labels: ''
assignees: ''
---
**Deployment details:**
- App version [e.g. v1.7.4]:
- Platform [e.g. amd64, arm64, arm/v7]:
- Docker image tag [e.g. latest, multiarch]:
---
**Bug description:**
A clear and concise description of what the bug is.
---
**Steps to reproduce:**
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'

3
.gitignore vendored
View file

@ -1,4 +1,5 @@
node_modules node_modules
data data
public public
!client/public !client/public
build.sh

View file

@ -1,2 +1 @@
*.md *.md
docker-compose.yml

View file

@ -1,54 +1,3 @@
### v2.3.1 (2023-07-23)
- Fixed bug where "Open search results in the same tab" setting was not respected if "Local search" was set as primary search provider ([#270](https://github.com/pawelmalak/flame/issues/270))
- Fixed bug where search bar had rounded input field on iOS ([#394](https://github.com/pawelmalak/flame/issues/394))
- Updated link to Material Design Icons reference page ([#414](https://github.com/pawelmalak/flame/issues/414))
- Fixed bug where color inputs in theme creator/editor were too small ([#429](https://github.com/pawelmalak/flame/issues/429))
- Changed input labels in settings for more consistent naming ([#430](https://github.com/pawelmalak/flame/issues/430))
### v2.3.0 (2022-03-25)
- Added custom theme editor ([#246](https://github.com/pawelmalak/flame/issues/246))
- Added option to set secondary search provider ([#295](https://github.com/pawelmalak/flame/issues/295))
- Fixed bug where pressing Enter with empty search bar would redirect to search results ([#325](https://github.com/pawelmalak/flame/issues/325))
- Fixed bug where user could create empty app or bookmark which was causing page to go blank ([#332](https://github.com/pawelmalak/flame/issues/332))
- Added new theme: Mint
### v2.2.2 (2022-03-21)
- Added option to get user location directly from the app ([#287](https://github.com/pawelmalak/flame/issues/287))
- Fixed bug with local search not working when using prefix ([#289](https://github.com/pawelmalak/flame/issues/289))
- Fixed bug with app description not updating when using custom icon ([#310](https://github.com/pawelmalak/flame/issues/310))
- Changed permissions to some files and directories created by Flame
- Changed some of the settings tabs
### v2.2.1 (2022-01-08)
- Local search will now include app descriptions ([#266](https://github.com/pawelmalak/flame/issues/266))
- Fixed bug with unsupported characters in local search [#279](https://github.com/pawelmalak/flame/issues/279))
- Background tasks optimization ([#283](https://github.com/pawelmalak/flame/issues/283))
### v2.2.0 (2021-12-17)
- Added option to set custom description for apps ([#201](https://github.com/pawelmalak/flame/issues/201))
- Fixed fatal error while deploying Flame to cluster ([#242](https://github.com/pawelmalak/flame/issues/242))
### v2.1.1 (2021-12-02)
- Added support for Docker secrets ([#189](https://github.com/pawelmalak/flame/issues/189))
- Changed some messages and buttons to make it easier to open bookmarks editor ([#239](https://github.com/pawelmalak/flame/issues/239))
### v2.1.0 (2021-11-26)
- Added option to set custom order for bookmarks ([#43](https://github.com/pawelmalak/flame/issues/43)) and ([#187](https://github.com/pawelmalak/flame/issues/187))
- Added support for .ico files for custom icons ([#209](https://github.com/pawelmalak/flame/issues/209))
- Empty apps and categories sections will now be hidden from guests ([#210](https://github.com/pawelmalak/flame/issues/210))
- Fixed bug with fahrenheit degrees being displayed as float ([#221](https://github.com/pawelmalak/flame/issues/221))
- Fixed bug with alphabetical order not working for bookmarks until the page was refreshed ([#224](https://github.com/pawelmalak/flame/issues/224))
- Added option to change visibilty of apps, categories and bookmarks directly from table view
- Password input will now autofocus when visiting /settings/app
### v2.0.1 (2021-11-19)
- Added option to display humidity in the weather widget ([#136](https://github.com/pawelmalak/flame/issues/136))
- Added option to set default theme for all new users ([#165](https://github.com/pawelmalak/flame/issues/165))
- Added option to hide header greetings and date separately ([#200](https://github.com/pawelmalak/flame/issues/200))
- Fixed bug with broken basic auth ([#202](https://github.com/pawelmalak/flame/issues/202))
- Fixed bug with parsing visibility value for apps and bookmarks when custom icon was used ([#203](https://github.com/pawelmalak/flame/issues/203))
- Fixed bug with custom icons not working with apps when "pin by default" was disabled
### v2.0.0 (2021-11-15) ### v2.0.0 (2021-11-15)
- Added authentication system: - Added authentication system:
- Only logged in user can access settings ([#33](https://github.com/pawelmalak/flame/issues/33)) - Only logged in user can access settings ([#33](https://github.com/pawelmalak/flame/issues/33))

View file

@ -11,7 +11,7 @@ Flame is self-hosted startpage for your server. Its design is inspired (heavily)
- 📌 Pin your favourite items to the homescreen for quick and easy access - 📌 Pin your favourite items to the homescreen for quick and easy access
- 🔍 Integrated search bar with local filtering, 11 web search providers and ability to add your own - 🔍 Integrated search bar with local filtering, 11 web search providers and ability to add your own
- 🔑 Authentication system to protect your settings, apps and bookmarks - 🔑 Authentication system to protect your settings, apps and bookmarks
- 🔨 Dozens of options to customize Flame interface to your needs, including support for custom CSS, 15 built-in color themes and custom theme builder - 🔨 Dozens of option to customize Flame interface to your needs, including support for custom CSS and 15 built-in color themes
- ☀️ Weather widget with current temperature, cloud coverage and animated weather status - ☀️ Weather widget with current temperature, cloud coverage and animated weather status
- 🐳 Docker integration to automatically pick and add apps based on their labels - 🐳 Docker integration to automatically pick and add apps based on their labels
@ -35,7 +35,7 @@ docker pull pawelmalak/flame:2.0.0
```sh ```sh
# run container # run container
docker run -p 5005:5005 -v /path/to/data:/app/data -e PASSWORD=flame_password pawelmalak/flame docker run -p 5005:5005 -v /path/to/data:/app/data -e PASSWORD=flame_password flame
``` ```
#### Building images #### Building images
@ -55,42 +55,19 @@ docker buildx build \
#### Docker-Compose #### Docker-Compose
```yaml ```yaml
version: '3.6' version: '2.1'
services: services:
flame: flame:
image: pawelmalak/flame image: pawelmalak/flame:latest
container_name: flame container_name: flame
volumes: volumes:
- /path/to/host/data:/app/data - <host_dir>:/app/data
- /var/run/docker.sock:/var/run/docker.sock # optional but required for Docker integration - /var/run/docker.sock:/var/run/docker.sock # optional but required for Docker integration feature
ports: ports:
- 5005:5005 - 5005:5005
secrets:
- password # optional but required for (1)
environment: environment:
- PASSWORD=flame_password - PASSWORD=flame_password
- PASSWORD_FILE=/run/secrets/password # optional but required for (1)
restart: unless-stopped restart: unless-stopped
# optional but required for Docker secrets (1)
secrets:
password:
file: /path/to/secrets/password
```
##### Docker Secrets
All environment variables can be overwritten by appending `_FILE` to the variable value. For example, you can use `PASSWORD_FILE` to pass through a docker secret instead of `PASSWORD`. If both `PASSWORD` and `PASSWORD_FILE` are set, the docker secret will take precedent.
```bash
# ./secrets/flame_password
my_custom_secret_password_123
# ./docker-compose.yml
secrets:
password:
file: ./secrets/flame_password
``` ```
#### Skaffold #### Skaffold
@ -235,7 +212,7 @@ metadata:
- Backup your `db.sqlite` before running script! - Backup your `db.sqlite` before running script!
- Known Issues: - Known Issues:
- generated icons are sometimes incorrect - generated icons are sometimes incorrect
```bash ```bash
pip3 install Pillow, beautifulsoup4 pip3 install Pillow, beautifulsoup4

1
api.js
View file

@ -22,7 +22,6 @@ api.use('/api/categories', require('./routes/category'));
api.use('/api/bookmarks', require('./routes/bookmark')); api.use('/api/bookmarks', require('./routes/bookmark'));
api.use('/api/queries', require('./routes/queries')); api.use('/api/queries', require('./routes/queries'));
api.use('/api/auth', require('./routes/auth')); api.use('/api/auth', require('./routes/auth'));
api.use('/api/themes', require('./routes/themes'));
// Custom error handler // Custom error handler
api.use(errorHandler); api.use(errorHandler);

View file

@ -1 +1 @@
REACT_APP_VERSION=2.3.1 REACT_APP_VERSION=2.0.0

33910
client/package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -11,6 +11,7 @@
"@types/jest": "^27.0.2", "@types/jest": "^27.0.2",
"@types/node": "^16.11.6", "@types/node": "^16.11.6",
"@types/react": "^17.0.34", "@types/react": "^17.0.34",
"@types/react-autosuggest": "^10.1.5",
"@types/react-beautiful-dnd": "^13.1.2", "@types/react-beautiful-dnd": "^13.1.2",
"@types/react-dom": "^17.0.11", "@types/react-dom": "^17.0.11",
"@types/react-redux": "^7.1.20", "@types/react-redux": "^7.1.20",
@ -20,11 +21,12 @@
"http-proxy-middleware": "^2.0.1", "http-proxy-middleware": "^2.0.1",
"jwt-decode": "^3.1.2", "jwt-decode": "^3.1.2",
"react": "^17.0.2", "react": "^17.0.2",
"react-autosuggest": "^10.1.0",
"react-beautiful-dnd": "^13.1.0", "react-beautiful-dnd": "^13.1.0",
"react-dom": "^17.0.2", "react-dom": "^17.0.2",
"react-redux": "^7.2.6", "react-redux": "^7.2.6",
"react-router-dom": "^5.2.0", "react-router-dom": "^5.2.0",
"react-scripts": "^5.0.1", "react-scripts": "4.0.3",
"redux": "^4.1.2", "redux": "^4.1.2",
"redux-devtools-extension": "^2.13.9", "redux-devtools-extension": "^2.13.9",
"redux-thunk": "^2.4.0", "redux-thunk": "^2.4.0",

View file

@ -1,16 +1,10 @@
import { useEffect } from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom'; import { BrowserRouter, Route, Switch } from 'react-router-dom';
import 'external-svg-loader';
// Redux
import { useDispatch, useSelector } from 'react-redux';
import { bindActionCreators } from 'redux';
import { autoLogin, getConfig } from './store/action-creators'; import { autoLogin, getConfig } from './store/action-creators';
import { actionCreators, store } from './store'; import { actionCreators, store } from './store';
import { State } from './store/reducers'; import 'external-svg-loader';
// Utils // Utils
import { checkVersion, decodeToken, parsePABToTheme } from './utility'; import { checkVersion, decodeToken } from './utility';
// Routes // Routes
import { Home } from './components/Home/Home'; import { Home } from './components/Home/Home';
@ -18,6 +12,9 @@ import { Apps } from './components/Apps/Apps';
import { Settings } from './components/Settings/Settings'; import { Settings } from './components/Settings/Settings';
import { Bookmarks } from './components/Bookmarks/Bookmarks'; import { Bookmarks } from './components/Bookmarks/Bookmarks';
import { NotificationCenter } from './components/NotificationCenter/NotificationCenter'; import { NotificationCenter } from './components/NotificationCenter/NotificationCenter';
import { useDispatch } from 'react-redux';
import { bindActionCreators } from 'redux';
import { useEffect } from 'react';
// Get config // Get config
store.dispatch<any>(getConfig()); store.dispatch<any>(getConfig());
@ -28,10 +25,8 @@ if (localStorage.token) {
} }
export const App = (): JSX.Element => { export const App = (): JSX.Element => {
const { config, loading } = useSelector((state: State) => state.config);
const dispath = useDispatch(); const dispath = useDispatch();
const { fetchQueries, setTheme, logout, createNotification, fetchThemes } = const { fetchQueries, setTheme, logout, createNotification } =
bindActionCreators(actionCreators, dispath); bindActionCreators(actionCreators, dispath);
useEffect(() => { useEffect(() => {
@ -51,12 +46,9 @@ export const App = (): JSX.Element => {
} }
}, 1000); }, 1000);
// load themes // set theme
fetchThemes();
// set user theme if present
if (localStorage.theme) { if (localStorage.theme) {
setTheme(parsePABToTheme(localStorage.theme)); setTheme(localStorage.theme);
} }
// check for updated // check for updated
@ -68,13 +60,6 @@ export const App = (): JSX.Element => {
return () => window.clearInterval(tokenIsValid); return () => window.clearInterval(tokenIsValid);
}, []); }, []);
// If there is no user theme, set the default one
useEffect(() => {
if (!loading && !localStorage.theme) {
setTheme(parsePABToTheme(config.defaultTheme), false);
}
}, [loading]);
return ( return (
<> <>
<BrowserRouter> <BrowserRouter>

View file

@ -1,12 +0,0 @@
.TableActions {
display: flex;
align-items: center;
}
.TableAction {
width: 22px;
}
.TableAction:hover {
cursor: pointer;
}

View file

@ -1,81 +0,0 @@
import { Icon } from '../UI';
import classes from './TableActions.module.css';
interface Entity {
id: number;
name: string;
isPinned?: boolean;
isPublic: boolean;
}
interface Props {
entity: Entity;
deleteHandler: (id: number, name: string) => void;
updateHandler: (id: number) => void;
pinHanlder?: (id: number) => void;
changeVisibilty: (id: number) => void;
showPin?: boolean;
}
export const TableActions = (props: Props): JSX.Element => {
const {
entity,
deleteHandler,
updateHandler,
pinHanlder,
changeVisibilty,
showPin = true,
} = props;
const _pinHandler = pinHanlder || function () {};
return (
<td className={classes.TableActions}>
{/* DELETE */}
<div
className={classes.TableAction}
onClick={() => deleteHandler(entity.id, entity.name)}
tabIndex={0}
>
<Icon icon="mdiDelete" />
</div>
{/* UPDATE */}
<div
className={classes.TableAction}
onClick={() => updateHandler(entity.id)}
tabIndex={0}
>
<Icon icon="mdiPencil" />
</div>
{/* PIN */}
{showPin && (
<div
className={classes.TableAction}
onClick={() => _pinHandler(entity.id)}
tabIndex={0}
>
{entity.isPinned ? (
<Icon icon="mdiPinOff" color="var(--color-accent)" />
) : (
<Icon icon="mdiPin" />
)}
</div>
)}
{/* VISIBILITY */}
<div
className={classes.TableAction}
onClick={() => changeVisibilty(entity.id)}
tabIndex={0}
>
{entity.isPublic ? (
<Icon icon="mdiEyeOff" color="var(--color-accent)" />
) : (
<Icon icon="mdiEye" />
)}
</div>
</td>
);
};

View file

@ -8,15 +8,16 @@ import { State } from '../../../store/reducers';
interface Props { interface Props {
app: App; app: App;
pinHandler?: Function;
} }
export const AppCard = ({ app }: Props): JSX.Element => { export const AppCard = (props: Props): JSX.Element => {
const { config } = useSelector((state: State) => state.config); const { config } = useSelector((state: State) => state.config);
const [displayUrl, redirectUrl] = urlParser(app.url); const [displayUrl, redirectUrl] = urlParser(props.app.url);
let iconEl: JSX.Element; let iconEl: JSX.Element;
const { icon } = app; const { icon } = props.app;
if (isImage(icon)) { if (isImage(icon)) {
const source = isUrl(icon) ? icon : `/uploads/${icon}`; const source = isUrl(icon) ? icon : `/uploads/${icon}`;
@ -24,7 +25,7 @@ export const AppCard = ({ app }: Props): JSX.Element => {
iconEl = ( iconEl = (
<img <img
src={source} src={source}
alt={`${app.name} icon`} alt={`${props.app.name} icon`}
className={classes.CustomIcon} className={classes.CustomIcon}
/> />
); );
@ -53,8 +54,8 @@ export const AppCard = ({ app }: Props): JSX.Element => {
> >
<div className={classes.AppCardIcon}>{iconEl}</div> <div className={classes.AppCardIcon}>{iconEl}</div>
<div className={classes.AppCardDetails}> <div className={classes.AppCardDetails}>
<h5>{app.name}</h5> <h5>{props.app.name}</h5>
<span>{!app.description.length ? displayUrl : app.description}</span> <span>{displayUrl}</span>
</div> </div>
</a> </a>
); );

View file

@ -1,6 +1,6 @@
import { useState, useEffect, ChangeEvent, SyntheticEvent } from 'react'; import { useState, useEffect, ChangeEvent, SyntheticEvent } from 'react';
import { useDispatch, useSelector } from 'react-redux'; import { useDispatch } from 'react-redux';
import { NewApp } from '../../../interfaces'; import { App, NewApp } from '../../../interfaces';
import classes from './AppForm.module.css'; import classes from './AppForm.module.css';
@ -8,32 +8,29 @@ import { ModalForm, InputGroup, Button } from '../../UI';
import { inputHandler, newAppTemplate } from '../../../utility'; import { inputHandler, newAppTemplate } from '../../../utility';
import { bindActionCreators } from 'redux'; import { bindActionCreators } from 'redux';
import { actionCreators } from '../../../store'; import { actionCreators } from '../../../store';
import { State } from '../../../store/reducers';
interface Props { interface Props {
modalHandler: () => void; modalHandler: () => void;
app?: App;
} }
export const AppForm = ({ modalHandler }: Props): JSX.Element => { export const AppForm = ({ app, modalHandler }: Props): JSX.Element => {
const { appInUpdate } = useSelector((state: State) => state.apps);
const dispatch = useDispatch(); const dispatch = useDispatch();
const { addApp, updateApp, setEditApp, createNotification } = const { addApp, updateApp } = bindActionCreators(actionCreators, dispatch);
bindActionCreators(actionCreators, dispatch);
const [useCustomIcon, toggleUseCustomIcon] = useState<boolean>(false); const [useCustomIcon, toggleUseCustomIcon] = useState<boolean>(false);
const [customIcon, setCustomIcon] = useState<File | null>(null); const [customIcon, setCustomIcon] = useState<File | null>(null);
const [formData, setFormData] = useState<NewApp>(newAppTemplate); const [formData, setFormData] = useState<NewApp>(newAppTemplate);
useEffect(() => { useEffect(() => {
if (appInUpdate) { if (app) {
setFormData({ setFormData({
...appInUpdate, ...app,
}); });
} else { } else {
setFormData(newAppTemplate); setFormData(newAppTemplate);
} }
}, [appInUpdate]); }, [app]);
const inputChangeHandler = ( const inputChangeHandler = (
e: ChangeEvent<HTMLInputElement | HTMLSelectElement>, e: ChangeEvent<HTMLInputElement | HTMLSelectElement>,
@ -56,33 +53,20 @@ export const AppForm = ({ modalHandler }: Props): JSX.Element => {
const formSubmitHandler = (e: SyntheticEvent<HTMLFormElement>): void => { const formSubmitHandler = (e: SyntheticEvent<HTMLFormElement>): void => {
e.preventDefault(); e.preventDefault();
for (let field of ['name', 'url', 'icon'] as const) {
if (/^ +$/.test(formData[field])) {
createNotification({
title: 'Error',
message: `Field cannot be empty: ${field}`,
});
return;
}
}
const createFormData = (): FormData => { const createFormData = (): FormData => {
const data = new FormData(); const data = new FormData();
if (customIcon) { if (customIcon) {
data.append('icon', customIcon); data.append('icon', customIcon);
} }
data.append('name', formData.name); data.append('name', formData.name);
data.append('description', formData.description);
data.append('url', formData.url); data.append('url', formData.url);
data.append('isPublic', `${formData.isPublic ? 1 : 0}`); data.append('isPublic', `${formData.isPublic}`);
return data; return data;
}; };
if (!appInUpdate) { if (!app) {
if (customIcon) { if (customIcon) {
const data = createFormData(); const data = createFormData();
addApp(data); addApp(data);
@ -92,22 +76,21 @@ export const AppForm = ({ modalHandler }: Props): JSX.Element => {
} else { } else {
if (customIcon) { if (customIcon) {
const data = createFormData(); const data = createFormData();
updateApp(appInUpdate.id, data); updateApp(app.id, data);
} else { } else {
updateApp(appInUpdate.id, formData); updateApp(app.id, formData);
modalHandler(); modalHandler();
} }
} }
setFormData(newAppTemplate); setFormData(newAppTemplate);
setEditApp(null);
}; };
return ( return (
<ModalForm modalHandler={modalHandler} formHandler={formSubmitHandler}> <ModalForm modalHandler={modalHandler} formHandler={formSubmitHandler}>
{/* NAME */} {/* NAME */}
<InputGroup> <InputGroup>
<label htmlFor="name">App name</label> <label htmlFor="name">App Name</label>
<input <input
type="text" type="text"
name="name" name="name"
@ -133,27 +116,11 @@ export const AppForm = ({ modalHandler }: Props): JSX.Element => {
/> />
</InputGroup> </InputGroup>
{/* DESCRIPTION */}
<InputGroup>
<label htmlFor="description">App description</label>
<input
type="text"
name="description"
id="description"
placeholder="My self-hosted app"
value={formData.description}
onChange={(e) => inputChangeHandler(e)}
/>
<span>
Optional - If description is not set, app URL will be displayed
</span>
</InputGroup>
{/* ICON */} {/* ICON */}
{!useCustomIcon ? ( {!useCustomIcon ? (
// use mdi icon // use mdi icon
<InputGroup> <InputGroup>
<label htmlFor="icon">App icon</label> <label htmlFor="icon">App Icon</label>
<input <input
type="text" type="text"
name="icon" name="icon"
@ -165,7 +132,7 @@ export const AppForm = ({ modalHandler }: Props): JSX.Element => {
/> />
<span> <span>
Use icon name from MDI or pass a valid URL. Use icon name from MDI or pass a valid URL.
<a href="https://pictogrammers.com/library/mdi/" target="blank"> <a href="https://materialdesignicons.com/" target="blank">
{' '} {' '}
Click here for reference Click here for reference
</a> </a>
@ -187,7 +154,7 @@ export const AppForm = ({ modalHandler }: Props): JSX.Element => {
id="icon" id="icon"
required required
onChange={(e) => fileChangeHandler(e)} onChange={(e) => fileChangeHandler(e)}
accept=".jpg,.jpeg,.png,.svg,.ico" accept=".jpg,.jpeg,.png,.svg"
/> />
<span <span
onClick={() => { onClick={() => {
@ -215,7 +182,7 @@ export const AppForm = ({ modalHandler }: Props): JSX.Element => {
</select> </select>
</InputGroup> </InputGroup>
{!appInUpdate ? ( {!app ? (
<Button>Add new application</Button> <Button>Add new application</Button>
) : ( ) : (
<Button>Update application</Button> <Button>Update application</Button>

View file

@ -20,3 +20,21 @@
grid-template-columns: repeat(4, 1fr); grid-template-columns: repeat(4, 1fr);
} }
} }
.GridMessage {
color: var(--color-primary);
}
.GridMessage a {
color: var(--color-accent);
font-weight: 600;
}
.AppsMessage {
color: var(--color-primary);
}
.AppsMessage a {
color: var(--color-accent);
font-weight: 600;
}

View file

@ -3,7 +3,6 @@ import { Link } from 'react-router-dom';
import { App } from '../../../interfaces/App'; import { App } from '../../../interfaces/App';
import { AppCard } from '../AppCard/AppCard'; import { AppCard } from '../AppCard/AppCard';
import { Message } from '../../UI';
interface Props { interface Props {
apps: App[]; apps: App[];
@ -14,32 +13,36 @@ interface Props {
export const AppGrid = (props: Props): JSX.Element => { export const AppGrid = (props: Props): JSX.Element => {
let apps: JSX.Element; let apps: JSX.Element;
if (props.searching || props.apps.length) { if (props.apps.length > 0) {
if (!props.apps.length) { apps = (
apps = <Message>No apps match your search criteria</Message>; <div className={classes.AppGrid}>
} else { {props.apps.map((app: App): JSX.Element => {
apps = ( return <AppCard key={app.id} app={app} />;
<div className={classes.AppGrid}> })}
{props.apps.map((app: App): JSX.Element => { </div>
return <AppCard key={app.id} app={app} />; );
})}
</div>
);
}
} else { } else {
if (props.totalApps) { if (props.totalApps) {
apps = ( if (props.searching) {
<Message> apps = (
There are no pinned applications. You can pin them from the{' '} <p className={classes.AppsMessage}>
<Link to="/applications">/applications</Link> menu No apps match your search criteria
</Message> </p>
); );
} else {
apps = (
<p className={classes.AppsMessage}>
There are no pinned applications. You can pin them from the{' '}
<Link to="/applications">/applications</Link> menu
</p>
);
}
} else { } else {
apps = ( apps = (
<Message> <p className={classes.AppsMessage}>
You don't have any applications. You can add a new one from{' '} You don't have any applications. You can add a new one from{' '}
<Link to="/applications">/applications</Link> menu <Link to="/applications">/applications</Link> menu
</Message> </p>
); );
} }
} }

View file

@ -1,13 +1,17 @@
.message { .TableActions {
color: var(--color-primary); display: flex;
align-items: center;
} }
.message a { .TableAction {
color: var(--color-accent); width: 22px;
font-weight: 600;
} }
.messageCenter { .TableAction:hover {
cursor: pointer;
}
.Message {
width: 100%; width: 100%;
display: flex; display: flex;
justify-content: center; justify-content: center;
@ -16,11 +20,10 @@
margin-bottom: 20px; margin-bottom: 20px;
} }
.messageCenter a, .Message a {
.messageCenter span {
color: var(--color-accent); color: var(--color-accent);
} }
.messageCenter a:hover { .Message a:hover {
cursor: pointer; cursor: pointer;
} }

View file

@ -1,4 +1,4 @@
import { Fragment, useState, useEffect } from 'react'; import { Fragment, KeyboardEvent, useState, useEffect } from 'react';
import { import {
DragDropContext, DragDropContext,
Droppable, Droppable,
@ -9,19 +9,21 @@ import { Link } from 'react-router-dom';
// Redux // Redux
import { useDispatch, useSelector } from 'react-redux'; import { useDispatch, useSelector } from 'react-redux';
import { State } from '../../../store/reducers';
import { bindActionCreators } from 'redux';
import { actionCreators } from '../../../store';
// Typescript // Typescript
import { App } from '../../../interfaces'; import { App } from '../../../interfaces';
// Other // CSS
import { Message, Table } from '../../UI'; import classes from './AppTable.module.css';
import { TableActions } from '../../Actions/TableActions';
// UI
import { Icon, Table } from '../../UI';
import { State } from '../../../store/reducers';
import { bindActionCreators } from 'redux';
import { actionCreators } from '../../../store';
interface Props { interface Props {
openFormForUpdating: (app: App) => void; updateAppHandler: (app: App) => void;
} }
export const AppTable = (props: Props): JSX.Element => { export const AppTable = (props: Props): JSX.Element => {
@ -31,18 +33,49 @@ export const AppTable = (props: Props): JSX.Element => {
} = useSelector((state: State) => state); } = useSelector((state: State) => state);
const dispatch = useDispatch(); const dispatch = useDispatch();
const { pinApp, deleteApp, reorderApps, createNotification, updateApp } = const { pinApp, deleteApp, reorderApps, updateConfig, createNotification } =
bindActionCreators(actionCreators, dispatch); bindActionCreators(actionCreators, dispatch);
const [localApps, setLocalApps] = useState<App[]>([]); const [localApps, setLocalApps] = useState<App[]>([]);
const [isCustomOrder, setIsCustomOrder] = useState<boolean>(false);
// Copy apps array // Copy apps array
useEffect(() => { useEffect(() => {
setLocalApps([...apps]); setLocalApps([...apps]);
}, [apps]); }, [apps]);
// Check ordering
useEffect(() => {
const order = config.useOrdering;
if (order === 'orderId') {
setIsCustomOrder(true);
}
}, []);
const deleteAppHandler = (app: App): void => {
const proceed = window.confirm(
`Are you sure you want to delete ${app.name} at ${app.url} ?`
);
if (proceed) {
deleteApp(app.id);
}
};
// Support keyboard navigation for actions
const keyboardActionHandler = (
e: KeyboardEvent,
app: App,
handler: Function
) => {
if (e.key === 'Enter') {
handler(app);
}
};
const dragEndHanlder = (result: DropResult): void => { const dragEndHanlder = (result: DropResult): void => {
if (config.useOrdering !== 'orderId') { if (!isCustomOrder) {
createNotification({ createNotification({
title: 'Error', title: 'Error',
message: 'Custom order is disabled', message: 'Custom order is disabled',
@ -62,43 +95,18 @@ export const AppTable = (props: Props): JSX.Element => {
reorderApps(tmpApps); reorderApps(tmpApps);
}; };
// Action handlers
const deleteAppHandler = (id: number, name: string) => {
const proceed = window.confirm(`Are you sure you want to delete ${name}?`);
if (proceed) {
deleteApp(id);
}
};
const updateAppHandler = (id: number) => {
const app = apps.find((a) => a.id === id) as App;
props.openFormForUpdating(app);
};
const pinAppHandler = (id: number) => {
const app = apps.find((a) => a.id === id) as App;
pinApp(app);
};
const changeAppVisibiltyHandler = (id: number) => {
const app = apps.find((a) => a.id === id) as App;
updateApp(id, { ...app, isPublic: !app.isPublic });
};
return ( return (
<Fragment> <Fragment>
<Message isPrimary={false}> <div className={classes.Message}>
{config.useOrdering === 'orderId' ? ( {isCustomOrder ? (
<p>You can drag and drop single rows to reorder application</p> <p>You can drag and drop single rows to reorder application</p>
) : ( ) : (
<p> <p>
Custom order is disabled. You can change it in the{' '} Custom order is disabled. You can change it in{' '}
<Link to="/settings/general">settings</Link> <Link to="/settings/other">settings</Link>
</p> </p>
)} )}
</Message> </div>
<DragDropContext onDragEnd={dragEndHanlder}> <DragDropContext onDragEnd={dragEndHanlder}>
<Droppable droppableId="apps"> <Droppable droppableId="apps">
{(provided) => ( {(provided) => (
@ -135,15 +143,54 @@ export const AppTable = (props: Props): JSX.Element => {
<td style={{ width: '200px' }}> <td style={{ width: '200px' }}>
{app.isPublic ? 'Visible' : 'Hidden'} {app.isPublic ? 'Visible' : 'Hidden'}
</td> </td>
{!snapshot.isDragging && ( {!snapshot.isDragging && (
<TableActions <td className={classes.TableActions}>
entity={app} <div
deleteHandler={deleteAppHandler} className={classes.TableAction}
updateHandler={updateAppHandler} onClick={() => deleteAppHandler(app)}
pinHanlder={pinAppHandler} onKeyDown={(e) =>
changeVisibilty={changeAppVisibiltyHandler} keyboardActionHandler(
/> e,
app,
deleteAppHandler
)
}
tabIndex={0}
>
<Icon icon="mdiDelete" />
</div>
<div
className={classes.TableAction}
onClick={() => props.updateAppHandler(app)}
onKeyDown={(e) =>
keyboardActionHandler(
e,
app,
props.updateAppHandler
)
}
tabIndex={0}
>
<Icon icon="mdiPencil" />
</div>
<div
className={classes.TableAction}
onClick={() => pinApp(app)}
onKeyDown={(e) =>
keyboardActionHandler(e, app, pinApp)
}
tabIndex={0}
>
{app.isPinned ? (
<Icon
icon="mdiPinOff"
color="var(--color-accent)"
/>
) : (
<Icon icon="mdiPin" />
)}
</div>
</td>
)} )}
</tr> </tr>
); );

View file

@ -19,6 +19,7 @@ import { AppForm } from './AppForm/AppForm';
import { AppTable } from './AppTable/AppTable'; import { AppTable } from './AppTable/AppTable';
// Utils // Utils
import { appTemplate } from '../../utility';
import { State } from '../../store/reducers'; import { State } from '../../store/reducers';
import { bindActionCreators } from 'redux'; import { bindActionCreators } from 'redux';
import { actionCreators } from '../../store'; import { actionCreators } from '../../store';
@ -28,53 +29,57 @@ interface Props {
} }
export const Apps = (props: Props): JSX.Element => { export const Apps = (props: Props): JSX.Element => {
// Get Redux state
const { const {
apps: { apps, loading }, apps: { apps, loading },
auth: { isAuthenticated }, auth: { isAuthenticated },
} = useSelector((state: State) => state); } = useSelector((state: State) => state);
// Get Redux action creators
const dispatch = useDispatch(); const dispatch = useDispatch();
const { getApps, setEditApp } = bindActionCreators(actionCreators, dispatch); const { getApps } = bindActionCreators(actionCreators, dispatch);
const [modalIsOpen, setModalIsOpen] = useState(false);
const [isInEdit, setIsInEdit] = useState(false);
const [isInUpdate, setIsInUpdate] = useState(false);
const [appInUpdate, setAppInUpdate] = useState<App>(appTemplate);
// Load apps if array is empty
useEffect(() => { useEffect(() => {
if (!apps.length) { if (!apps.length) {
getApps(); getApps();
} }
}, []); }, []);
// Form // observe if user is authenticated -> set default view if not
const [modalIsOpen, setModalIsOpen] = useState(false);
const [showTable, setShowTable] = useState(false);
// Observe if user is authenticated -> set default view if not
useEffect(() => { useEffect(() => {
if (!isAuthenticated) { if (!isAuthenticated) {
setShowTable(false); setIsInEdit(false);
setModalIsOpen(false); setModalIsOpen(false);
} }
}, [isAuthenticated]); }, [isAuthenticated]);
// Form actions
const toggleModal = (): void => { const toggleModal = (): void => {
setModalIsOpen(!modalIsOpen); setModalIsOpen(!modalIsOpen);
setIsInUpdate(false);
}; };
const toggleEdit = (): void => { const toggleEdit = (): void => {
setShowTable(!showTable); setIsInEdit(!isInEdit);
setIsInUpdate(false);
}; };
const openFormForUpdating = (app: App): void => { const toggleUpdate = (app: App): void => {
setEditApp(app); setAppInUpdate(app);
setIsInUpdate(true);
setModalIsOpen(true); setModalIsOpen(true);
}; };
return ( return (
<Container> <Container>
<Modal isOpen={modalIsOpen} setIsOpen={setModalIsOpen}> <Modal isOpen={modalIsOpen} setIsOpen={setModalIsOpen}>
<AppForm modalHandler={toggleModal} /> {!isInUpdate ? (
<AppForm modalHandler={toggleModal} />
) : (
<AppForm modalHandler={toggleModal} app={appInUpdate} />
)}
</Modal> </Modal>
<Headline <Headline
@ -84,14 +89,7 @@ export const Apps = (props: Props): JSX.Element => {
{isAuthenticated && ( {isAuthenticated && (
<div className={classes.ActionsContainer}> <div className={classes.ActionsContainer}>
<ActionButton <ActionButton name="Add" icon="mdiPlusBox" handler={toggleModal} />
name="Add"
icon="mdiPlusBox"
handler={() => {
setEditApp(null);
toggleModal();
}}
/>
<ActionButton name="Edit" icon="mdiPencil" handler={toggleEdit} /> <ActionButton name="Edit" icon="mdiPencil" handler={toggleEdit} />
</div> </div>
)} )}
@ -99,10 +97,10 @@ export const Apps = (props: Props): JSX.Element => {
<div className={classes.Apps}> <div className={classes.Apps}>
{loading ? ( {loading ? (
<Spinner /> <Spinner />
) : !showTable ? ( ) : !isInEdit ? (
<AppGrid apps={apps} searching={props.searching} /> <AppGrid apps={apps} searching={props.searching} />
) : ( ) : (
<AppTable openFormForUpdating={openFormForUpdating} /> <AppTable updateAppHandler={toggleUpdate} />
)} )}
</div> </div>
</Container> </Container>

View file

@ -10,10 +10,6 @@
text-transform: uppercase; text-transform: uppercase;
} }
.BookmarkHeader:hover {
cursor: pointer;
}
.Bookmarks { .Bookmarks {
display: flex; display: flex;
flex-direction: column; flex-direction: column;

View file

@ -1,52 +1,28 @@
import { Fragment } from 'react'; import { Fragment } from 'react';
// Redux import { useSelector } from 'react-redux';
import { useDispatch, useSelector } from 'react-redux';
import { State } from '../../../store/reducers'; import { State } from '../../../store/reducers';
import { bindActionCreators } from 'redux';
import { actionCreators } from '../../../store';
// Typescript
import { Bookmark, Category } from '../../../interfaces'; import { Bookmark, Category } from '../../../interfaces';
// Other
import classes from './BookmarkCard.module.css'; import classes from './BookmarkCard.module.css';
import { Icon } from '../../UI'; import { Icon } from '../../UI';
import { iconParser, isImage, isSvg, isUrl, urlParser } from '../../../utility'; import { iconParser, isImage, isSvg, isUrl, urlParser } from '../../../utility';
interface Props { interface Props {
category: Category; category: Category;
fromHomepage?: boolean;
} }
export const BookmarkCard = (props: Props): JSX.Element => { export const BookmarkCard = (props: Props): JSX.Element => {
const { category, fromHomepage = false } = props; const { config } = useSelector((state: State) => state.config);
const {
config: { config },
auth: { isAuthenticated },
} = useSelector((state: State) => state);
const dispatch = useDispatch();
const { setEditCategory } = bindActionCreators(actionCreators, dispatch);
return ( return (
<div className={classes.BookmarkCard}> <div className={classes.BookmarkCard}>
<h3 <h3>{props.category.name}</h3>
className={
fromHomepage || !isAuthenticated ? '' : classes.BookmarkHeader
}
onClick={() => {
if (!fromHomepage && isAuthenticated) {
setEditCategory(category);
}
}}
>
{category.name}
</h3>
<div className={classes.Bookmarks}> <div className={classes.Bookmarks}>
{category.bookmarks.map((bookmark: Bookmark) => { {props.category.bookmarks.map((bookmark: Bookmark) => {
const redirectUrl = urlParser(bookmark.url)[1]; const redirectUrl = urlParser(bookmark.url)[1];
let iconEl: JSX.Element = <Fragment></Fragment>; let iconEl: JSX.Element = <Fragment></Fragment>;

View file

@ -20,3 +20,12 @@
grid-template-columns: repeat(4, 1fr); grid-template-columns: repeat(4, 1fr);
} }
} }
.BookmarksMessage {
color: var(--color-primary);
}
.BookmarksMessage a {
color: var(--color-accent);
font-weight: 600;
}

View file

@ -5,57 +5,48 @@ import classes from './BookmarkGrid.module.css';
import { Category } from '../../../interfaces'; import { Category } from '../../../interfaces';
import { BookmarkCard } from '../BookmarkCard/BookmarkCard'; import { BookmarkCard } from '../BookmarkCard/BookmarkCard';
import { Message } from '../../UI';
interface Props { interface Props {
categories: Category[]; categories: Category[];
totalCategories?: number; totalCategories?: number;
searching: boolean; searching: boolean;
fromHomepage?: boolean;
} }
export const BookmarkGrid = (props: Props): JSX.Element => { export const BookmarkGrid = (props: Props): JSX.Element => {
const {
categories,
totalCategories,
searching,
fromHomepage = false,
} = props;
let bookmarks: JSX.Element; let bookmarks: JSX.Element;
if (categories.length) { if (props.categories.length) {
if (searching && !categories[0].bookmarks.length) { if (props.searching && !props.categories[0].bookmarks.length) {
bookmarks = <Message>No bookmarks match your search criteria</Message>; bookmarks = (
<p className={classes.BookmarksMessage}>
No bookmarks match your search criteria
</p>
);
} else { } else {
bookmarks = ( bookmarks = (
<div className={classes.BookmarkGrid}> <div className={classes.BookmarkGrid}>
{categories.map( {props.categories.map(
(category: Category): JSX.Element => ( (category: Category): JSX.Element => (
<BookmarkCard <BookmarkCard category={category} key={category.id} />
category={category}
fromHomepage={fromHomepage}
key={category.id}
/>
) )
)} )}
</div> </div>
); );
} }
} else { } else {
if (totalCategories) { if (props.totalCategories) {
bookmarks = ( bookmarks = (
<Message> <p className={classes.BookmarksMessage}>
There are no pinned categories. You can pin them from the{' '} There are no pinned categories. You can pin them from the{' '}
<Link to="/bookmarks">/bookmarks</Link> menu <Link to="/bookmarks">/bookmarks</Link> menu
</Message> </p>
); );
} else { } else {
bookmarks = ( bookmarks = (
<Message> <p className={classes.BookmarksMessage}>
You don't have any bookmarks. You can add a new one from{' '} You don't have any bookmarks. You can add a new one from{' '}
<Link to="/bookmarks">/bookmarks</Link> menu <Link to="/bookmarks">/bookmarks</Link> menu
</Message> </p>
); );
} }
} }

View file

@ -0,0 +1,29 @@
.TableActions {
display: flex;
align-items: center;
}
.TableAction {
width: 22px;
}
.TableAction:hover {
cursor: pointer;
}
.Message {
width: 100%;
display: flex;
justify-content: center;
align-items: baseline;
color: var(--color-primary);
margin-bottom: 20px;
}
.Message a {
color: var(--color-accent);
}
.Message a:hover {
cursor: pointer;
}

View file

@ -0,0 +1,272 @@
import { KeyboardEvent, useState, useEffect, Fragment } from 'react';
import {
DragDropContext,
Droppable,
Draggable,
DropResult,
} from 'react-beautiful-dnd';
import { Link } from 'react-router-dom';
// Redux
import { useDispatch, useSelector } from 'react-redux';
import { State } from '../../../store/reducers';
import { bindActionCreators } from 'redux';
import { actionCreators } from '../../../store';
// Typescript
import { Bookmark, Category } from '../../../interfaces';
import { ContentType } from '../Bookmarks';
// CSS
import classes from './BookmarkTable.module.css';
// UI
import { Table, Icon } from '../../UI';
interface Props {
contentType: ContentType;
categories: Category[];
updateHandler: (data: Category | Bookmark) => void;
}
export const BookmarkTable = (props: Props): JSX.Element => {
const { config } = useSelector((state: State) => state.config);
const dispatch = useDispatch();
const {
pinCategory,
deleteCategory,
deleteBookmark,
createNotification,
reorderCategories,
} = bindActionCreators(actionCreators, dispatch);
const [localCategories, setLocalCategories] = useState<Category[]>([]);
const [isCustomOrder, setIsCustomOrder] = useState<boolean>(false);
// Copy categories array
useEffect(() => {
setLocalCategories([...props.categories]);
}, [props.categories]);
// Check ordering
useEffect(() => {
const order = config.useOrdering;
if (order === 'orderId') {
setIsCustomOrder(true);
}
});
const deleteCategoryHandler = (category: Category): void => {
const proceed = window.confirm(
`Are you sure you want to delete ${category.name}? It will delete ALL assigned bookmarks`
);
if (proceed) {
deleteCategory(category.id);
}
};
const deleteBookmarkHandler = (bookmark: Bookmark): void => {
const proceed = window.confirm(
`Are you sure you want to delete ${bookmark.name}?`
);
if (proceed) {
deleteBookmark(bookmark.id, bookmark.categoryId);
}
};
const keyboardActionHandler = (
e: KeyboardEvent,
category: Category,
handler: Function
) => {
if (e.key === 'Enter') {
handler(category);
}
};
const dragEndHanlder = (result: DropResult): void => {
if (!isCustomOrder) {
createNotification({
title: 'Error',
message: 'Custom order is disabled',
});
return;
}
if (!result.destination) {
return;
}
const tmpCategories = [...localCategories];
const [movedApp] = tmpCategories.splice(result.source.index, 1);
tmpCategories.splice(result.destination.index, 0, movedApp);
setLocalCategories(tmpCategories);
reorderCategories(tmpCategories);
};
if (props.contentType === ContentType.category) {
return (
<Fragment>
<div className={classes.Message}>
{isCustomOrder ? (
<p>You can drag and drop single rows to reorder categories</p>
) : (
<p>
Custom order is disabled. You can change it in{' '}
<Link to="/settings/other">settings</Link>
</p>
)}
</div>
<DragDropContext onDragEnd={dragEndHanlder}>
<Droppable droppableId="categories">
{(provided) => (
<Table
headers={['Name', 'Visibility', 'Actions']}
innerRef={provided.innerRef}
>
{localCategories.map(
(category: Category, index): JSX.Element => {
return (
<Draggable
key={category.id}
draggableId={category.id.toString()}
index={index}
>
{(provided, snapshot) => {
const style = {
border: snapshot.isDragging
? '1px solid var(--color-accent)'
: 'none',
borderRadius: '4px',
...provided.draggableProps.style,
};
return (
<tr
{...provided.draggableProps}
{...provided.dragHandleProps}
ref={provided.innerRef}
style={style}
>
<td style={{ width: '300px' }}>
{category.name}
</td>
<td style={{ width: '300px' }}>
{category.isPublic ? 'Visible' : 'Hidden'}
</td>
{!snapshot.isDragging && (
<td className={classes.TableActions}>
<div
className={classes.TableAction}
onClick={() =>
deleteCategoryHandler(category)
}
onKeyDown={(e) =>
keyboardActionHandler(
e,
category,
deleteCategoryHandler
)
}
tabIndex={0}
>
<Icon icon="mdiDelete" />
</div>
<div
className={classes.TableAction}
onClick={() =>
props.updateHandler(category)
}
tabIndex={0}
>
<Icon icon="mdiPencil" />
</div>
<div
className={classes.TableAction}
onClick={() => pinCategory(category)}
onKeyDown={(e) =>
keyboardActionHandler(
e,
category,
pinCategory
)
}
tabIndex={0}
>
{category.isPinned ? (
<Icon
icon="mdiPinOff"
color="var(--color-accent)"
/>
) : (
<Icon icon="mdiPin" />
)}
</div>
</td>
)}
</tr>
);
}}
</Draggable>
);
}
)}
</Table>
)}
</Droppable>
</DragDropContext>
</Fragment>
);
} else {
const bookmarks: { bookmark: Bookmark; categoryName: string }[] = [];
props.categories.forEach((category: Category) => {
category.bookmarks.forEach((bookmark: Bookmark) => {
bookmarks.push({
bookmark,
categoryName: category.name,
});
});
});
return (
<Table
headers={['Name', 'URL', 'Icon', 'Visibility', 'Category', 'Actions']}
>
{bookmarks.map(
(bookmark: { bookmark: Bookmark; categoryName: string }) => {
return (
<tr key={bookmark.bookmark.id}>
<td>{bookmark.bookmark.name}</td>
<td>{bookmark.bookmark.url}</td>
<td>{bookmark.bookmark.icon}</td>
<td>{bookmark.bookmark.isPublic ? 'Visible' : 'Hidden'}</td>
<td>{bookmark.categoryName}</td>
<td className={classes.TableActions}>
<div
className={classes.TableAction}
onClick={() => deleteBookmarkHandler(bookmark.bookmark)}
tabIndex={0}
>
<Icon icon="mdiDelete" />
</div>
<div
className={classes.TableAction}
onClick={() => props.updateHandler(bookmark.bookmark)}
tabIndex={0}
>
<Icon icon="mdiPencil" />
</div>
</td>
</tr>
);
}
)}
</Table>
);
}
};

View file

@ -14,19 +14,15 @@ import { Category, Bookmark } from '../../interfaces';
import classes from './Bookmarks.module.css'; import classes from './Bookmarks.module.css';
// UI // UI
import { import { Container, Headline, ActionButton, Spinner, Modal } from '../UI';
Container,
Headline,
ActionButton,
Spinner,
Modal,
Message,
} from '../UI';
// Components // Components
import { BookmarkGrid } from './BookmarkGrid/BookmarkGrid'; import { BookmarkGrid } from './BookmarkGrid/BookmarkGrid';
import { BookmarkTable } from './BookmarkTable/BookmarkTable';
import { Form } from './Form/Form'; import { Form } from './Form/Form';
import { Table } from './Table/Table';
// Utils
import { bookmarkTemplate, categoryTemplate } from '../../utility';
interface Props { interface Props {
searching: boolean; searching: boolean;
@ -38,99 +34,74 @@ export enum ContentType {
} }
export const Bookmarks = (props: Props): JSX.Element => { export const Bookmarks = (props: Props): JSX.Element => {
// Get Redux state
const { const {
bookmarks: { loading, categories, categoryInEdit }, bookmarks: { loading, categories },
auth: { isAuthenticated }, auth: { isAuthenticated },
} = useSelector((state: State) => state); } = useSelector((state: State) => state);
// Get Redux action creators
const dispatch = useDispatch(); const dispatch = useDispatch();
const { getCategories, setEditCategory, setEditBookmark } = const { getCategories } = bindActionCreators(actionCreators, dispatch);
bindActionCreators(actionCreators, dispatch);
const [modalIsOpen, setModalIsOpen] = useState(false);
const [formContentType, setFormContentType] = useState(ContentType.category);
const [isInEdit, setIsInEdit] = useState(false);
const [tableContentType, setTableContentType] = useState(
ContentType.category
);
const [isInUpdate, setIsInUpdate] = useState(false);
const [categoryInUpdate, setCategoryInUpdate] =
useState<Category>(categoryTemplate);
const [bookmarkInUpdate, setBookmarkInUpdate] =
useState<Bookmark>(bookmarkTemplate);
// Load categories if array is empty
useEffect(() => { useEffect(() => {
if (!categories.length) { if (!categories.length) {
getCategories(); getCategories();
} }
}, []); }, []);
// Form // observe if user is authenticated -> set default view if not
const [modalIsOpen, setModalIsOpen] = useState(false);
const [formContentType, setFormContentType] = useState(ContentType.category);
const [isInUpdate, setIsInUpdate] = useState(false);
// Table
const [showTable, setShowTable] = useState(false);
const [tableContentType, setTableContentType] = useState(
ContentType.category
);
// Observe if user is authenticated -> set default view (grid) if not
useEffect(() => { useEffect(() => {
if (!isAuthenticated) { if (!isAuthenticated) {
setShowTable(false); setIsInEdit(false);
setModalIsOpen(false); setModalIsOpen(false);
} }
}, [isAuthenticated]); }, [isAuthenticated]);
useEffect(() => {
if (categoryInEdit && !modalIsOpen) {
setTableContentType(ContentType.bookmark);
setShowTable(true);
}
}, [categoryInEdit]);
useEffect(() => {
setShowTable(false);
setEditCategory(null);
}, []);
// Form actions
const toggleModal = (): void => { const toggleModal = (): void => {
setModalIsOpen(!modalIsOpen); setModalIsOpen(!modalIsOpen);
}; };
const openFormForAdding = (contentType: ContentType) => { const addActionHandler = (contentType: ContentType) => {
setFormContentType(contentType); setFormContentType(contentType);
setIsInUpdate(false); setIsInUpdate(false);
toggleModal(); toggleModal();
}; };
const openFormForUpdating = (data: Category | Bookmark): void => { const editActionHandler = (contentType: ContentType) => {
setIsInUpdate(true);
const instanceOfCategory = (object: any): object is Category => {
return 'bookmarks' in object;
};
if (instanceOfCategory(data)) {
setFormContentType(ContentType.category);
setEditCategory(data);
} else {
setFormContentType(ContentType.bookmark);
setEditBookmark(data);
}
toggleModal();
};
// Table actions
const showTableForEditing = (contentType: ContentType) => {
// We're in the edit mode and the same button was clicked - go back to list // We're in the edit mode and the same button was clicked - go back to list
if (showTable && contentType === tableContentType) { if (isInEdit && contentType === tableContentType) {
setEditCategory(null); setIsInEdit(false);
setShowTable(false);
} else { } else {
setShowTable(true); setIsInEdit(true);
setTableContentType(contentType); setTableContentType(contentType);
} }
}; };
const finishEditing = () => { const instanceOfCategory = (object: any): object is Category => {
setShowTable(false); return 'bookmarks' in object;
setEditCategory(null); };
const goToUpdateMode = (data: Category | Bookmark): void => {
setIsInUpdate(true);
if (instanceOfCategory(data)) {
setFormContentType(ContentType.category);
setCategoryInUpdate(data);
} else {
setFormContentType(ContentType.bookmark);
setBookmarkInUpdate(data);
}
toggleModal();
}; };
return ( return (
@ -140,6 +111,8 @@ export const Bookmarks = (props: Props): JSX.Element => {
modalHandler={toggleModal} modalHandler={toggleModal}
contentType={formContentType} contentType={formContentType}
inUpdate={isInUpdate} inUpdate={isInUpdate}
category={categoryInUpdate}
bookmark={bookmarkInUpdate}
/> />
</Modal> </Modal>
@ -150,44 +123,35 @@ export const Bookmarks = (props: Props): JSX.Element => {
<ActionButton <ActionButton
name="Add Category" name="Add Category"
icon="mdiPlusBox" icon="mdiPlusBox"
handler={() => openFormForAdding(ContentType.category)} handler={() => addActionHandler(ContentType.category)}
/> />
<ActionButton <ActionButton
name="Add Bookmark" name="Add Bookmark"
icon="mdiPlusBox" icon="mdiPlusBox"
handler={() => openFormForAdding(ContentType.bookmark)} handler={() => addActionHandler(ContentType.bookmark)}
/> />
<ActionButton <ActionButton
name="Edit Categories" name="Edit Categories"
icon="mdiPencil" icon="mdiPencil"
handler={() => showTableForEditing(ContentType.category)} handler={() => editActionHandler(ContentType.category)}
/>
<ActionButton
name="Edit Bookmarks"
icon="mdiPencil"
handler={() => editActionHandler(ContentType.bookmark)}
/> />
{showTable && tableContentType === ContentType.bookmark && (
<ActionButton
name="Finish Editing"
icon="mdiPencil"
handler={finishEditing}
/>
)}
</div> </div>
)} )}
{categories.length && isAuthenticated && !showTable ? (
<Message isPrimary={false}>
Click on category name to edit its bookmarks
</Message>
) : (
<></>
)}
{loading ? ( {loading ? (
<Spinner /> <Spinner />
) : !showTable ? ( ) : !isInEdit ? (
<BookmarkGrid categories={categories} searching={props.searching} /> <BookmarkGrid categories={categories} searching={props.searching} />
) : ( ) : (
<Table <BookmarkTable
contentType={tableContentType} contentType={tableContentType}
openFormForUpdating={openFormForUpdating} categories={categories}
updateHandler={goToUpdateMode}
/> />
)} )}
</Container> </Container>

View file

@ -69,17 +69,6 @@ export const BookmarksForm = ({
const formSubmitHandler = (e: FormEvent): void => { const formSubmitHandler = (e: FormEvent): void => {
e.preventDefault(); e.preventDefault();
for (let field of ['name', 'url', 'icon'] as const) {
if (/^ +$/.test(formData[field])) {
createNotification({
title: 'Error',
message: `Field cannot be empty: ${field}`,
});
return;
}
}
const createFormData = (): FormData => { const createFormData = (): FormData => {
const data = new FormData(); const data = new FormData();
if (customIcon) { if (customIcon) {
@ -88,7 +77,7 @@ export const BookmarksForm = ({
data.append('name', formData.name); data.append('name', formData.name);
data.append('url', formData.url); data.append('url', formData.url);
data.append('categoryId', `${formData.categoryId}`); data.append('categoryId', `${formData.categoryId}`);
data.append('isPublic', `${formData.isPublic ? 1 : 0}`); data.append('isPublic', `${formData.isPublic}`);
return data; return data;
}; };
@ -148,15 +137,15 @@ export const BookmarksForm = ({
} }
modalHandler(); modalHandler();
}
setFormData({ ...newBookmarkTemplate, categoryId: formData.categoryId }); setFormData(newBookmarkTemplate);
setCustomIcon(null);
setCustomIcon(null);
}
}; };
return ( return (
<ModalForm modalHandler={modalHandler} formHandler={formSubmitHandler}> <ModalForm modalHandler={modalHandler} formHandler={formSubmitHandler}>
{/* NAME */}
<InputGroup> <InputGroup>
<label htmlFor="name">Bookmark Name</label> <label htmlFor="name">Bookmark Name</label>
<input <input
@ -170,7 +159,6 @@ export const BookmarksForm = ({
/> />
</InputGroup> </InputGroup>
{/* URL */}
<InputGroup> <InputGroup>
<label htmlFor="url">Bookmark URL</label> <label htmlFor="url">Bookmark URL</label>
<input <input
@ -184,7 +172,6 @@ export const BookmarksForm = ({
/> />
</InputGroup> </InputGroup>
{/* CATEGORY */}
<InputGroup> <InputGroup>
<label htmlFor="categoryId">Bookmark Category</label> <label htmlFor="categoryId">Bookmark Category</label>
<select <select
@ -205,7 +192,6 @@ export const BookmarksForm = ({
</select> </select>
</InputGroup> </InputGroup>
{/* ICON */}
{!useCustomIcon ? ( {!useCustomIcon ? (
// mdi // mdi
<InputGroup> <InputGroup>
@ -241,7 +227,7 @@ export const BookmarksForm = ({
name="icon" name="icon"
id="icon" id="icon"
onChange={(e) => fileChangeHandler(e)} onChange={(e) => fileChangeHandler(e)}
accept=".jpg,.jpeg,.png,.svg,.ico" accept=".jpg,.jpeg,.png,.svg"
/> />
<span <span
onClick={() => { onClick={() => {
@ -255,7 +241,6 @@ export const BookmarksForm = ({
</InputGroup> </InputGroup>
)} )}
{/* VISIBILTY */}
<InputGroup> <InputGroup>
<label htmlFor="isPublic">Bookmark visibility</label> <label htmlFor="isPublic">Bookmark visibility</label>
<select <select

View file

@ -60,10 +60,10 @@ export const CategoryForm = ({
addCategory(formData); addCategory(formData);
} else { } else {
updateCategory(category.id, formData); updateCategory(category.id, formData);
modalHandler();
} }
setFormData(newCategoryTemplate); setFormData(newCategoryTemplate);
modalHandler();
}; };
return ( return (

View file

@ -1,26 +1,22 @@
// Typescript // Typescript
import { Bookmark, Category } from '../../../interfaces';
import { ContentType } from '../Bookmarks'; import { ContentType } from '../Bookmarks';
// Utils // Utils
import { CategoryForm } from './CategoryForm'; import { CategoryForm } from './CategoryForm';
import { BookmarksForm } from './BookmarksForm'; import { BookmarksForm } from './BookmarksForm';
import { Fragment } from 'react'; import { Fragment } from 'react';
import { useSelector } from 'react-redux';
import { State } from '../../../store/reducers';
import { bookmarkTemplate, categoryTemplate } from '../../../utility';
interface Props { interface Props {
modalHandler: () => void; modalHandler: () => void;
contentType: ContentType; contentType: ContentType;
inUpdate?: boolean; inUpdate?: boolean;
category?: Category;
bookmark?: Bookmark;
} }
export const Form = (props: Props): JSX.Element => { export const Form = (props: Props): JSX.Element => {
const { categoryInEdit, bookmarkInEdit } = useSelector( const { modalHandler, contentType, inUpdate, category, bookmark } = props;
(state: State) => state.bookmarks
);
const { modalHandler, contentType, inUpdate } = props;
return ( return (
<Fragment> <Fragment>
@ -37,15 +33,9 @@ export const Form = (props: Props): JSX.Element => {
// form: update // form: update
<Fragment> <Fragment>
{contentType === ContentType.category ? ( {contentType === ContentType.category ? (
<CategoryForm <CategoryForm modalHandler={modalHandler} category={category} />
modalHandler={modalHandler}
category={categoryInEdit || categoryTemplate}
/>
) : ( ) : (
<BookmarksForm <BookmarksForm modalHandler={modalHandler} bookmark={bookmark} />
modalHandler={modalHandler}
bookmark={bookmarkInEdit || bookmarkTemplate}
/>
)} )}
</Fragment> </Fragment>
)} )}

View file

@ -1,188 +0,0 @@
import { useState, useEffect, Fragment } from 'react';
import {
DragDropContext,
Droppable,
Draggable,
DropResult,
} from 'react-beautiful-dnd';
// Redux
import { useDispatch, useSelector } from 'react-redux';
import { State } from '../../../store/reducers';
import { bindActionCreators } from 'redux';
import { actionCreators } from '../../../store';
// Typescript
import { Bookmark, Category } from '../../../interfaces';
// UI
import { Message, Table } from '../../UI';
import { TableActions } from '../../Actions/TableActions';
import { bookmarkTemplate } from '../../../utility';
interface Props {
openFormForUpdating: (data: Category | Bookmark) => void;
}
export const BookmarksTable = ({ openFormForUpdating }: Props): JSX.Element => {
const {
bookmarks: { categoryInEdit },
config: { config },
} = useSelector((state: State) => state);
const dispatch = useDispatch();
const {
deleteBookmark,
updateBookmark,
createNotification,
reorderBookmarks,
} = bindActionCreators(actionCreators, dispatch);
const [localBookmarks, setLocalBookmarks] = useState<Bookmark[]>([]);
// Copy bookmarks array
useEffect(() => {
if (categoryInEdit) {
setLocalBookmarks([...categoryInEdit.bookmarks]);
}
}, [categoryInEdit]);
// Drag and drop handler
const dragEndHanlder = (result: DropResult): void => {
if (config.useOrdering !== 'orderId') {
createNotification({
title: 'Error',
message: 'Custom order is disabled',
});
return;
}
if (!result.destination) {
return;
}
const tmpBookmarks = [...localBookmarks];
const [movedBookmark] = tmpBookmarks.splice(result.source.index, 1);
tmpBookmarks.splice(result.destination.index, 0, movedBookmark);
setLocalBookmarks(tmpBookmarks);
const categoryId = categoryInEdit?.id || -1;
reorderBookmarks(tmpBookmarks, categoryId);
};
// Action hanlders
const deleteBookmarkHandler = (id: number, name: string) => {
const categoryId = categoryInEdit?.id || -1;
const proceed = window.confirm(`Are you sure you want to delete ${name}?`);
if (proceed) {
deleteBookmark(id, categoryId);
}
};
const updateBookmarkHandler = (id: number) => {
const bookmark =
categoryInEdit?.bookmarks.find((b) => b.id === id) || bookmarkTemplate;
openFormForUpdating(bookmark);
};
const changeBookmarkVisibiltyHandler = (id: number) => {
const bookmark =
categoryInEdit?.bookmarks.find((b) => b.id === id) || bookmarkTemplate;
const categoryId = categoryInEdit?.id || -1;
const [prev, curr] = [categoryId, categoryId];
updateBookmark(
id,
{ ...bookmark, isPublic: !bookmark.isPublic },
{ prev, curr }
);
};
return (
<Fragment>
{!categoryInEdit ? (
<Message isPrimary={false}>
Switch to grid view and click on the name of category you want to edit
</Message>
) : (
<Message isPrimary={false}>
Editing bookmarks from&nbsp;<span>{categoryInEdit.name}</span>
&nbsp;category
</Message>
)}
{categoryInEdit && (
<DragDropContext onDragEnd={dragEndHanlder}>
<Droppable droppableId="bookmarks">
{(provided) => (
<Table
headers={[
'Name',
'URL',
'Icon',
'Visibility',
'Category',
'Actions',
]}
innerRef={provided.innerRef}
>
{localBookmarks.map((bookmark, index): JSX.Element => {
return (
<Draggable
key={bookmark.id}
draggableId={bookmark.id.toString()}
index={index}
>
{(provided, snapshot) => {
const style = {
border: snapshot.isDragging
? '1px solid var(--color-accent)'
: 'none',
borderRadius: '4px',
...provided.draggableProps.style,
};
return (
<tr
{...provided.draggableProps}
{...provided.dragHandleProps}
ref={provided.innerRef}
style={style}
>
<td style={{ width: '200px' }}>{bookmark.name}</td>
<td style={{ width: '200px' }}>{bookmark.url}</td>
<td style={{ width: '200px' }}>{bookmark.icon}</td>
<td style={{ width: '200px' }}>
{bookmark.isPublic ? 'Visible' : 'Hidden'}
</td>
<td style={{ width: '200px' }}>
{categoryInEdit.name}
</td>
{!snapshot.isDragging && (
<TableActions
entity={bookmark}
deleteHandler={deleteBookmarkHandler}
updateHandler={updateBookmarkHandler}
changeVisibilty={changeBookmarkVisibiltyHandler}
showPin={false}
/>
)}
</tr>
);
}}
</Draggable>
);
})}
</Table>
)}
</Droppable>
</DragDropContext>
)}
</Fragment>
);
};

View file

@ -1,166 +0,0 @@
import { useState, useEffect, Fragment } from 'react';
import {
DragDropContext,
Droppable,
Draggable,
DropResult,
} from 'react-beautiful-dnd';
import { Link } from 'react-router-dom';
// Redux
import { useDispatch, useSelector } from 'react-redux';
import { State } from '../../../store/reducers';
import { bindActionCreators } from 'redux';
import { actionCreators } from '../../../store';
// Typescript
import { Bookmark, Category } from '../../../interfaces';
// UI
import { Message, Table } from '../../UI';
import { TableActions } from '../../Actions/TableActions';
interface Props {
openFormForUpdating: (data: Category | Bookmark) => void;
}
export const CategoryTable = ({ openFormForUpdating }: Props): JSX.Element => {
const {
config: { config },
bookmarks: { categories },
} = useSelector((state: State) => state);
const dispatch = useDispatch();
const {
pinCategory,
deleteCategory,
createNotification,
reorderCategories,
updateCategory,
} = bindActionCreators(actionCreators, dispatch);
const [localCategories, setLocalCategories] = useState<Category[]>([]);
// Copy categories array
useEffect(() => {
setLocalCategories([...categories]);
}, [categories]);
// Drag and drop handler
const dragEndHanlder = (result: DropResult): void => {
if (config.useOrdering !== 'orderId') {
createNotification({
title: 'Error',
message: 'Custom order is disabled',
});
return;
}
if (!result.destination) {
return;
}
const tmpCategories = [...localCategories];
const [movedCategory] = tmpCategories.splice(result.source.index, 1);
tmpCategories.splice(result.destination.index, 0, movedCategory);
setLocalCategories(tmpCategories);
reorderCategories(tmpCategories);
};
// Action handlers
const deleteCategoryHandler = (id: number, name: string) => {
const proceed = window.confirm(
`Are you sure you want to delete ${name}? It will delete ALL assigned bookmarks`
);
if (proceed) {
deleteCategory(id);
}
};
const updateCategoryHandler = (id: number) => {
const category = categories.find((c) => c.id === id) as Category;
openFormForUpdating(category);
};
const pinCategoryHandler = (id: number) => {
const category = categories.find((c) => c.id === id) as Category;
pinCategory(category);
};
const changeCategoryVisibiltyHandler = (id: number) => {
const category = categories.find((c) => c.id === id) as Category;
updateCategory(id, { ...category, isPublic: !category.isPublic });
};
return (
<Fragment>
<Message isPrimary={false}>
{config.useOrdering === 'orderId' ? (
<p>You can drag and drop single rows to reorder categories</p>
) : (
<p>
Custom order is disabled. You can change it in the{' '}
<Link to="/settings/general">settings</Link>
</p>
)}
</Message>
<DragDropContext onDragEnd={dragEndHanlder}>
<Droppable droppableId="categories">
{(provided) => (
<Table
headers={['Name', 'Visibility', 'Actions']}
innerRef={provided.innerRef}
>
{localCategories.map((category, index): JSX.Element => {
return (
<Draggable
key={category.id}
draggableId={category.id.toString()}
index={index}
>
{(provided, snapshot) => {
const style = {
border: snapshot.isDragging
? '1px solid var(--color-accent)'
: 'none',
borderRadius: '4px',
...provided.draggableProps.style,
};
return (
<tr
{...provided.draggableProps}
{...provided.dragHandleProps}
ref={provided.innerRef}
style={style}
>
<td style={{ width: '300px' }}>{category.name}</td>
<td style={{ width: '300px' }}>
{category.isPublic ? 'Visible' : 'Hidden'}
</td>
{!snapshot.isDragging && (
<TableActions
entity={category}
deleteHandler={deleteCategoryHandler}
updateHandler={updateCategoryHandler}
pinHanlder={pinCategoryHandler}
changeVisibilty={changeCategoryVisibiltyHandler}
/>
)}
</tr>
);
}}
</Draggable>
);
})}
</Table>
)}
</Droppable>
</DragDropContext>
</Fragment>
);
};

View file

@ -1,20 +0,0 @@
import { Category, Bookmark } from '../../../interfaces';
import { ContentType } from '../Bookmarks';
import { BookmarksTable } from './BookmarksTable';
import { CategoryTable } from './CategoryTable';
interface Props {
contentType: ContentType;
openFormForUpdating: (data: Category | Bookmark) => void;
}
export const Table = (props: Props): JSX.Element => {
const tableEl =
props.contentType === ContentType.category ? (
<CategoryTable openFormForUpdating={props.openFormForUpdating} />
) : (
<BookmarksTable openFormForUpdating={props.openFormForUpdating} />
);
return tableEl;
};

View file

@ -1,10 +1,6 @@
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom'; import { Link } from 'react-router-dom';
// Redux
import { useSelector } from 'react-redux';
import { State } from '../../../store/reducers';
// CSS // CSS
import classes from './Header.module.css'; import classes from './Header.module.css';
@ -16,10 +12,6 @@ import { getDateTime } from './functions/getDateTime';
import { greeter } from './functions/greeter'; import { greeter } from './functions/greeter';
export const Header = (): JSX.Element => { export const Header = (): JSX.Element => {
const { hideHeader, hideDate, showTime } = useSelector(
(state: State) => state.config.config
);
const [dateTime, setDateTime] = useState<string>(getDateTime()); const [dateTime, setDateTime] = useState<string>(getDateTime());
const [greeting, setGreeting] = useState<string>(greeter()); const [greeting, setGreeting] = useState<string>(greeter());
@ -36,18 +28,14 @@ export const Header = (): JSX.Element => {
return ( return (
<header className={classes.Header}> <header className={classes.Header}>
{(!hideDate || showTime) && <p>{dateTime}</p>} <p>{dateTime}</p>
<Link to="/settings" className={classes.SettingsLink}> <Link to="/settings" className={classes.SettingsLink}>
Go to Settings Go to Settings
</Link> </Link>
<span className={classes.HeaderMain}>
{!hideHeader && ( <h1>{greeting}</h1>
<span className={classes.HeaderMain}> <WeatherWidget />
<h1>{greeting}</h1> </span>
<WeatherWidget />
</span>
)}
</header> </header>
); );
}; };

View file

@ -30,42 +30,22 @@ export const getDateTime = (): string => {
const useAmericanDate = localStorage.useAmericanDate === 'true'; const useAmericanDate = localStorage.useAmericanDate === 'true';
const showTime = localStorage.showTime === 'true'; const showTime = localStorage.showTime === 'true';
const hideDate = localStorage.hideDate === 'true';
// Date
let dateEl = '';
if (!hideDate) {
if (!useAmericanDate) {
dateEl = `${days[now.getDay()]}, ${now.getDate()} ${
months[now.getMonth()]
} ${now.getFullYear()}`;
} else {
dateEl = `${days[now.getDay()]}, ${
months[now.getMonth()]
} ${now.getDate()} ${now.getFullYear()}`;
}
}
// Time
const p = parseTime; const p = parseTime;
let timeEl = '';
if (showTime) { const time = `${p(now.getHours())}:${p(now.getMinutes())}:${p(
const time = `${p(now.getHours())}:${p(now.getMinutes())}:${p( now.getSeconds()
now.getSeconds() )}`;
)}`;
timeEl = time; const timeEl = showTime ? ` - ${time}` : '';
if (!useAmericanDate) {
return `${days[now.getDay()]}, ${now.getDate()} ${
months[now.getMonth()]
} ${now.getFullYear()}${timeEl}`;
} else {
return `${days[now.getDay()]}, ${
months[now.getMonth()]
} ${now.getDate()} ${now.getFullYear()}${timeEl}`;
} }
// Separator
let separator = '';
if (!hideDate && showTime) {
separator = ' - ';
}
// Output
return `${dateEl}${separator}${timeEl}`;
}; };

View file

@ -11,7 +11,7 @@ import { actionCreators } from '../../store';
import { App, Category } from '../../interfaces'; import { App, Category } from '../../interfaces';
// UI // UI
import { Icon, Container, SectionHeadline, Spinner, Message } from '../UI'; import { Icon, Container, SectionHeadline, Spinner } from '../UI';
// CSS // CSS
import classes from './Home.module.css'; import classes from './Home.module.css';
@ -30,7 +30,6 @@ export const Home = (): JSX.Element => {
apps: { apps, loading: appsLoading }, apps: { apps, loading: appsLoading },
bookmarks: { categories, loading: bookmarksLoading }, bookmarks: { categories, loading: bookmarksLoading },
config: { config }, config: { config },
auth: { isAuthenticated },
} = useSelector((state: State) => state); } = useSelector((state: State) => state);
const dispatch = useDispatch(); const dispatch = useDispatch();
@ -64,10 +63,8 @@ export const Home = (): JSX.Element => {
if (localSearch) { if (localSearch) {
// Search through apps // Search through apps
setAppSearchResult([ setAppSearchResult([
...apps.filter(({ name, description }) => ...apps.filter(({ name }) =>
new RegExp(escapeRegex(localSearch), 'i').test( new RegExp(escapeRegex(localSearch), 'i').test(name)
`${name} ${description}`
)
), ),
]); ]);
@ -101,20 +98,9 @@ export const Home = (): JSX.Element => {
<div></div> <div></div>
)} )}
<Header /> {!config.hideHeader ? <Header /> : <div></div>}
{!isAuthenticated && {!config.hideApps ? (
!apps.some((a) => a.isPinned) &&
!categories.some((c) => c.isPinned) ? (
<Message>
Welcome to Flame! Go to <Link to="/settings/app">/settings</Link>,
login and start customizing your new homepage
</Message>
) : (
<></>
)}
{!config.hideApps && (isAuthenticated || apps.some((a) => a.isPinned)) ? (
<Fragment> <Fragment>
<SectionHeadline title="Applications" link="/applications" /> <SectionHeadline title="Applications" link="/applications" />
{appsLoading ? ( {appsLoading ? (
@ -133,11 +119,10 @@ export const Home = (): JSX.Element => {
<div className={classes.HomeSpace}></div> <div className={classes.HomeSpace}></div>
</Fragment> </Fragment>
) : ( ) : (
<></> <div></div>
)} )}
{!config.hideCategories && {!config.hideCategories ? (
(isAuthenticated || categories.some((c) => c.isPinned)) ? (
<Fragment> <Fragment>
<SectionHeadline title="Bookmarks" link="/bookmarks" /> <SectionHeadline title="Bookmarks" link="/bookmarks" />
{bookmarksLoading ? ( {bookmarksLoading ? (
@ -153,12 +138,11 @@ export const Home = (): JSX.Element => {
} }
totalCategories={categories.length} totalCategories={categories.length}
searching={!!localSearch} searching={!!localSearch}
fromHomepage={true}
/> />
)} )}
</Fragment> </Fragment>
) : ( ) : (
<></> <div></div>
)} )}
<Link to="/settings" className={classes.SettingsButton}> <Link to="/settings" className={classes.SettingsButton}>

View file

@ -9,7 +9,6 @@
border-bottom: 2px solid var(--color-accent); border-bottom: 2px solid var(--color-accent);
opacity: 0.5; opacity: 0.5;
transition: all 0.2s; transition: all 0.2s;
border-radius: 0px;
} }
.SearchBar:focus { .SearchBar:focus {

View file

@ -64,22 +64,16 @@ export const SearchBar = (props: Props): JSX.Element => {
}; };
const searchHandler = (e: KeyboardEvent<HTMLInputElement>) => { const searchHandler = (e: KeyboardEvent<HTMLInputElement>) => {
const { const { isLocal, search, query, isURL, sameTab } = searchParser(
isLocal, inputRef.current.value
encodedURL, );
primarySearch,
secondarySearch,
isURL,
sameTab,
rawQuery,
} = searchParser(inputRef.current.value);
if (isLocal) { if (isLocal) {
setLocalSearch(encodedURL); setLocalSearch(search);
} }
if (e.code === 'Enter' || e.code === 'NumpadEnter') { if (e.code === 'Enter' || e.code === 'NumpadEnter') {
if (!primarySearch.prefix) { if (!query.prefix) {
// Prefix not found -> emit notification // Prefix not found -> emit notification
createNotification({ createNotification({
title: 'Error', title: 'Error',
@ -96,21 +90,19 @@ export const SearchBar = (props: Props): JSX.Element => {
} else if (bookmarkSearchResult?.[0]?.bookmarks?.length) { } else if (bookmarkSearchResult?.[0]?.bookmarks?.length) {
redirectUrl(bookmarkSearchResult[0].bookmarks[0].url, sameTab); redirectUrl(bookmarkSearchResult[0].bookmarks[0].url, sameTab);
} else { } else {
// no local results -> search the internet with the default search provider if query is not empty // no local results -> search the internet with the default search provider
if (!/^ *$/.test(rawQuery)) { let template = query.template;
let template = primarySearch.template;
if (primarySearch.prefix === 'l') { if (query.prefix === 'l') {
template = secondarySearch.template; template = 'https://duckduckgo.com/?q=';
}
const url = `${template}${encodedURL}`;
redirectUrl(url, sameTab);
} }
const url = `${template}${search}`;
redirectUrl(url, sameTab);
} }
} else { } else {
// Valid query -> redirect to search results // Valid query -> redirect to search results
const url = `${primarySearch.template}${encodedURL}`; const url = `${query.template}${search}`;
redirectUrl(url, sameTab); redirectUrl(url, sameTab);
} }
} else if (e.code === 'Escape') { } else if (e.code === 'Escape') {

View file

@ -1,57 +1,43 @@
import { Fragment } from 'react'; import { Fragment } from 'react';
// UI
import { Button, SettingsHeadline } from '../../UI'; import { Button, SettingsHeadline } from '../../UI';
import { AuthForm } from './AuthForm/AuthForm';
import classes from './AppDetails.module.css'; import classes from './AppDetails.module.css';
// Store
import { useSelector } from 'react-redux';
import { State } from '../../../store/reducers';
// Other
import { checkVersion } from '../../../utility'; import { checkVersion } from '../../../utility';
import { AuthForm } from './AuthForm/AuthForm';
export const AppDetails = (): JSX.Element => { export const AppDetails = (): JSX.Element => {
const { isAuthenticated } = useSelector((state: State) => state.auth);
return ( return (
<Fragment> <Fragment>
<SettingsHeadline text="Authentication" /> <SettingsHeadline text="Authentication" />
<AuthForm /> <AuthForm />
{isAuthenticated && ( <hr className={classes.separator} />
<Fragment>
<hr className={classes.separator} />
<div> <div>
<SettingsHeadline text="App version" /> <SettingsHeadline text="App version" />
<p className={classes.text}> <p className={classes.text}>
<a <a
href="https://github.com/pawelmalak/flame" href="https://github.com/pawelmalak/flame"
target="_blank" target="_blank"
rel="noreferrer" rel="noreferrer"
> >
Flame Flame
</a>{' '} </a>{' '}
version {process.env.REACT_APP_VERSION} version {process.env.REACT_APP_VERSION}
</p> </p>
<p className={classes.text}> <p className={classes.text}>
See changelog{' '} See changelog{' '}
<a <a
href="https://github.com/pawelmalak/flame/blob/master/CHANGELOG.md" href="https://github.com/pawelmalak/flame/blob/master/CHANGELOG.md"
target="_blank" target="_blank"
rel="noreferrer" rel="noreferrer"
> >
here here
</a> </a>
</p> </p>
<Button click={() => checkVersion(true)}>Check for updates</Button> <Button click={() => checkVersion(true)}>Check for updates</Button>
</div> </div>
</Fragment>
)}
</Fragment> </Fragment>
); );
}; };

View file

@ -1,4 +1,4 @@
import { FormEvent, Fragment, useEffect, useState, useRef } from 'react'; import { FormEvent, Fragment, useEffect, useState } from 'react';
// Redux // Redux
import { useSelector, useDispatch } from 'react-redux'; import { useSelector, useDispatch } from 'react-redux';
@ -23,12 +23,6 @@ export const AuthForm = (): JSX.Element => {
duration: '14d', duration: '14d',
}); });
const passwordInputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
passwordInputRef.current?.focus();
}, []);
useEffect(() => { useEffect(() => {
if (token) { if (token) {
const decoded = decodeToken(token); const decoded = decodeToken(token);
@ -58,7 +52,6 @@ export const AuthForm = (): JSX.Element => {
name="password" name="password"
placeholder="••••••" placeholder="••••••"
autoComplete="current-password" autoComplete="current-password"
ref={passwordInputRef}
value={formData.password} value={formData.password}
onChange={(e) => onChange={(e) =>
setFormData({ ...formData, password: e.target.value }) setFormData({ ...formData, password: e.target.value })

View file

@ -59,7 +59,7 @@ export const DockerSettings = (): JSX.Element => {
<SettingsHeadline text="Docker" /> <SettingsHeadline text="Docker" />
{/* CUSTOM DOCKER SOCKET HOST */} {/* CUSTOM DOCKER SOCKET HOST */}
<InputGroup> <InputGroup>
<label htmlFor="dockerHost">Docker host</label> <label htmlFor="dockerHost">Docker Host</label>
<input <input
type="text" type="text"
id="dockerHost" id="dockerHost"

View file

@ -1,242 +0,0 @@
// React
import { useState, useEffect, FormEvent, ChangeEvent, Fragment } from 'react';
import { useDispatch, useSelector } from 'react-redux';
// Typescript
import { Query, GeneralForm } from '../../../interfaces';
// Components
import { CustomQueries } from './CustomQueries/CustomQueries';
// UI
import { Button, SettingsHeadline, InputGroup } from '../../UI';
// Utils
import { inputHandler, generalSettingsTemplate } from '../../../utility';
// Data
import searchQueries from '../../../utility/searchQueries.json';
// Redux
import { State } from '../../../store/reducers';
import { bindActionCreators } from 'redux';
import { actionCreators } from '../../../store';
export const GeneralSettings = (): JSX.Element => {
const {
config: { loading, customQueries, config },
bookmarks: { categories },
} = useSelector((state: State) => state);
const dispatch = useDispatch();
const { updateConfig, sortApps, sortCategories, sortBookmarks } =
bindActionCreators(actionCreators, dispatch);
const queries = searchQueries.queries;
// Initial state
const [formData, setFormData] = useState<GeneralForm>(
generalSettingsTemplate
);
// Get config
useEffect(() => {
setFormData({
...config,
});
}, [loading]);
// Form handler
const formSubmitHandler = async (e: FormEvent) => {
e.preventDefault();
// Save settings
await updateConfig(formData);
// Sort entities with new settings
if (formData.useOrdering !== config.useOrdering) {
sortApps();
sortCategories();
for (let { id } of categories) {
sortBookmarks(id);
}
}
};
// Input handler
const inputChangeHandler = (
e: ChangeEvent<HTMLInputElement | HTMLSelectElement>,
options?: { isNumber?: boolean; isBool?: boolean }
) => {
inputHandler<GeneralForm>({
e,
options,
setStateHandler: setFormData,
state: formData,
});
};
return (
<Fragment>
<form
onSubmit={(e) => formSubmitHandler(e)}
style={{ marginBottom: '30px' }}
>
{/* === GENERAL OPTIONS === */}
<SettingsHeadline text="General" />
{/* SORT TYPE */}
<InputGroup>
<label htmlFor="useOrdering">Sorting type</label>
<select
id="useOrdering"
name="useOrdering"
value={formData.useOrdering}
onChange={(e) => inputChangeHandler(e)}
>
<option value="createdAt">By creation date</option>
<option value="name">Alphabetical order</option>
<option value="orderId">Custom order</option>
</select>
</InputGroup>
{/* === APPS OPTIONS === */}
<SettingsHeadline text="Apps" />
{/* PIN APPS */}
<InputGroup>
<label htmlFor="pinAppsByDefault">
Pin new applications by default
</label>
<select
id="pinAppsByDefault"
name="pinAppsByDefault"
value={formData.pinAppsByDefault ? 1 : 0}
onChange={(e) => inputChangeHandler(e, { isBool: true })}
>
<option value={1}>True</option>
<option value={0}>False</option>
</select>
</InputGroup>
{/* APPS OPPENING */}
<InputGroup>
<label htmlFor="appsSameTab">Open applications in the same tab</label>
<select
id="appsSameTab"
name="appsSameTab"
value={formData.appsSameTab ? 1 : 0}
onChange={(e) => inputChangeHandler(e, { isBool: true })}
>
<option value={1}>True</option>
<option value={0}>False</option>
</select>
</InputGroup>
{/* === BOOKMARKS OPTIONS === */}
<SettingsHeadline text="Bookmarks" />
{/* PIN CATEGORIES */}
<InputGroup>
<label htmlFor="pinCategoriesByDefault">
Pin new categories by default
</label>
<select
id="pinCategoriesByDefault"
name="pinCategoriesByDefault"
value={formData.pinCategoriesByDefault ? 1 : 0}
onChange={(e) => inputChangeHandler(e, { isBool: true })}
>
<option value={1}>True</option>
<option value={0}>False</option>
</select>
</InputGroup>
{/* BOOKMARKS OPPENING */}
<InputGroup>
<label htmlFor="bookmarksSameTab">
Open bookmarks in the same tab
</label>
<select
id="bookmarksSameTab"
name="bookmarksSameTab"
value={formData.bookmarksSameTab ? 1 : 0}
onChange={(e) => inputChangeHandler(e, { isBool: true })}
>
<option value={1}>True</option>
<option value={0}>False</option>
</select>
</InputGroup>
{/* === SEARCH OPTIONS === */}
<SettingsHeadline text="Search" />
<InputGroup>
<label htmlFor="defaultSearchProvider">Primary search provider</label>
<select
id="defaultSearchProvider"
name="defaultSearchProvider"
value={formData.defaultSearchProvider}
onChange={(e) => inputChangeHandler(e)}
>
{[...queries, ...customQueries].map((query: Query, idx) => {
const isCustom = idx >= queries.length;
return (
<option key={idx} value={query.prefix}>
{isCustom && '+'} {query.name}
</option>
);
})}
</select>
</InputGroup>
{formData.defaultSearchProvider === 'l' && (
<InputGroup>
<label htmlFor="secondarySearchProvider">
Secondary search provider
</label>
<select
id="secondarySearchProvider"
name="secondarySearchProvider"
value={formData.secondarySearchProvider}
onChange={(e) => inputChangeHandler(e)}
>
{[...queries, ...customQueries].map((query: Query, idx) => {
const isCustom = idx >= queries.length;
return (
<option key={idx} value={query.prefix}>
{isCustom && '+'} {query.name}
</option>
);
})}
</select>
<span>
Will be used when "Local search" is primary search provider and
there are not any local results
</span>
</InputGroup>
)}
<InputGroup>
<label htmlFor="searchSameTab">
Open search results in the same tab
</label>
<select
id="searchSameTab"
name="searchSameTab"
value={formData.searchSameTab ? 1 : 0}
onChange={(e) => inputChangeHandler(e, { isBool: true })}
>
<option value={1}>True</option>
<option value={0}>False</option>
</select>
</InputGroup>
<Button>Save changes</Button>
</form>
{/* CUSTOM QUERIES */}
<SettingsHeadline text="Custom search providers" />
<CustomQueries />
</Fragment>
);
};

View file

@ -0,0 +1,30 @@
.QueriesGrid {
display: grid;
grid-template-columns: repeat(3, 1fr);
}
.QueriesGrid span {
color: var(--color-primary);
}
.QueriesGrid span:last-child {
margin-bottom: 10px;
}
.ActionIcons {
display: flex;
}
.ActionIcons svg {
width: 20px;
}
.ActionIcons svg:hover {
cursor: pointer;
}
.Separator {
grid-column: 1 / 4;
border-bottom: 1px solid var(--color-primary);
margin: 10px 0;
}

View file

@ -9,8 +9,11 @@ import { actionCreators } from '../../../../store';
// Typescript // Typescript
import { Query } from '../../../../interfaces'; import { Query } from '../../../../interfaces';
// CSS
import classes from './CustomQueries.module.css';
// UI // UI
import { Modal, Icon, Button, CompactTable, ActionIcons } from '../../../UI'; import { Modal, Icon, Button } from '../../../UI';
// Components // Components
import { QueriesForm } from './QueriesForm'; import { QueriesForm } from './QueriesForm';
@ -64,27 +67,33 @@ export const CustomQueries = (): JSX.Element => {
)} )}
</Modal> </Modal>
<section> <div>
{customQueries.length ? ( <div className={classes.QueriesGrid}>
<CompactTable headers={['Name', 'Prefix', 'Actions']}> {customQueries.length > 0 && (
{customQueries.map((q: Query, idx) => ( <Fragment>
<Fragment key={idx}> <span>Name</span>
<span>{q.name}</span> <span>Prefix</span>
<span>{q.prefix}</span> <span>Actions</span>
<ActionIcons>
<span onClick={() => updateHandler(q)}> <div className={classes.Separator}></div>
<Icon icon="mdiPencil" /> </Fragment>
</span> )}
<span onClick={() => deleteHandler(q)}>
<Icon icon="mdiDelete" /> {customQueries.map((q: Query, idx) => (
</span> <Fragment key={idx}>
</ActionIcons> <span>{q.name}</span>
</Fragment> <span>{q.prefix}</span>
))} <span className={classes.ActionIcons}>
</CompactTable> <span onClick={() => updateHandler(q)}>
) : ( <Icon icon="mdiPencil" />
<></> </span>
)} <span onClick={() => deleteHandler(q)}>
<Icon icon="mdiDelete" />
</span>
</span>
</Fragment>
))}
</div>
<Button <Button
click={() => { click={() => {
@ -94,7 +103,7 @@ export const CustomQueries = (): JSX.Element => {
> >
Add new search provider Add new search provider
</Button> </Button>
</section> </div>
</Fragment> </Fragment>
); );
}; };

View file

@ -0,0 +1,141 @@
// React
import { useState, useEffect, FormEvent, ChangeEvent, Fragment } from 'react';
import { useDispatch, useSelector } from 'react-redux';
// Typescript
import { Query, SearchForm } from '../../../interfaces';
// Components
import { CustomQueries } from './CustomQueries/CustomQueries';
// UI
import { Button, SettingsHeadline, InputGroup } from '../../UI';
// Utils
import { inputHandler, searchSettingsTemplate } from '../../../utility';
// Data
import { queries } from '../../../utility/searchQueries.json';
// Redux
import { State } from '../../../store/reducers';
import { bindActionCreators } from 'redux';
import { actionCreators } from '../../../store';
export const SearchSettings = (): JSX.Element => {
const { loading, customQueries, config } = useSelector(
(state: State) => state.config
);
const dispatch = useDispatch();
const { updateConfig } = bindActionCreators(actionCreators, dispatch);
// Initial state
const [formData, setFormData] = useState<SearchForm>(searchSettingsTemplate);
// Get config
useEffect(() => {
setFormData({
...config,
});
}, [loading]);
// Form handler
const formSubmitHandler = async (e: FormEvent) => {
e.preventDefault();
// Save settings
await updateConfig(formData);
};
// Input handler
const inputChangeHandler = (
e: ChangeEvent<HTMLInputElement | HTMLSelectElement>,
options?: { isNumber?: boolean; isBool?: boolean }
) => {
inputHandler<SearchForm>({
e,
options,
setStateHandler: setFormData,
state: formData,
});
};
return (
<Fragment>
{/* GENERAL SETTINGS */}
<form
onSubmit={(e) => formSubmitHandler(e)}
style={{ marginBottom: '30px' }}
>
<SettingsHeadline text="General" />
<InputGroup>
<label htmlFor="defaultSearchProvider">Default Search Provider</label>
<select
id="defaultSearchProvider"
name="defaultSearchProvider"
value={formData.defaultSearchProvider}
onChange={(e) => inputChangeHandler(e)}
>
{[...queries, ...customQueries].map((query: Query, idx) => {
const isCustom = idx >= queries.length;
return (
<option key={idx} value={query.prefix}>
{isCustom && '+'} {query.name}
</option>
);
})}
</select>
</InputGroup>
<InputGroup>
<label htmlFor="searchSameTab">
Open search results in the same tab
</label>
<select
id="searchSameTab"
name="searchSameTab"
value={formData.searchSameTab ? 1 : 0}
onChange={(e) => inputChangeHandler(e, { isBool: true })}
>
<option value={1}>True</option>
<option value={0}>False</option>
</select>
</InputGroup>
<InputGroup>
<label htmlFor="hideSearch">Hide search bar</label>
<select
id="hideSearch"
name="hideSearch"
value={formData.hideSearch ? 1 : 0}
onChange={(e) => inputChangeHandler(e, { isBool: true })}
>
<option value={1}>True</option>
<option value={0}>False</option>
</select>
</InputGroup>
<InputGroup>
<label htmlFor="disableAutofocus">Disable search bar autofocus</label>
<select
id="disableAutofocus"
name="disableAutofocus"
value={formData.disableAutofocus ? 1 : 0}
onChange={(e) => inputChangeHandler(e, { isBool: true })}
>
<option value={1}>True</option>
<option value={0}>False</option>
</select>
</InputGroup>
<Button>Save changes</Button>
</form>
{/* CUSTOM QUERIES */}
<SettingsHeadline text="Custom search providers" />
<CustomQueries />
</Fragment>
);
};

View file

@ -11,12 +11,12 @@ import { Route as SettingsRoute } from '../../interfaces';
import classes from './Settings.module.css'; import classes from './Settings.module.css';
// Components // Components
import { Themer } from './Themer/Themer'; import { Themer } from '../Themer/Themer';
import { WeatherSettings } from './WeatherSettings/WeatherSettings'; import { WeatherSettings } from './WeatherSettings/WeatherSettings';
import { UISettings } from './UISettings/UISettings'; import { UISettings } from './UISettings/UISettings';
import { AppDetails } from './AppDetails/AppDetails'; import { AppDetails } from './AppDetails/AppDetails';
import { StyleSettings } from './StyleSettings/StyleSettings'; import { StyleSettings } from './StyleSettings/StyleSettings';
import { GeneralSettings } from './GeneralSettings/GeneralSettings'; import { SearchSettings } from './SearchSettings/SearchSettings';
import { DockerSettings } from './DockerSettings/DockerSettings'; import { DockerSettings } from './DockerSettings/DockerSettings';
import { ProtectedRoute } from '../Routing/ProtectedRoute'; import { ProtectedRoute } from '../Routing/ProtectedRoute';
@ -24,11 +24,9 @@ import { ProtectedRoute } from '../Routing/ProtectedRoute';
import { Container, Headline } from '../UI'; import { Container, Headline } from '../UI';
// Data // Data
import clientRoutes from './settings.json'; import { routes } from './settings.json';
export const Settings = (): JSX.Element => { export const Settings = (): JSX.Element => {
const routes = clientRoutes.routes;
const { isAuthenticated } = useSelector((state: State) => state.auth); const { isAuthenticated } = useSelector((state: State) => state.auth);
const tabs = isAuthenticated ? routes : routes.filter((r) => !r.authRequired); const tabs = isAuthenticated ? routes : routes.filter((r) => !r.authRequired);
@ -61,8 +59,8 @@ export const Settings = (): JSX.Element => {
component={WeatherSettings} component={WeatherSettings}
/> />
<ProtectedRoute <ProtectedRoute
path="/settings/general" path="/settings/search"
component={GeneralSettings} component={SearchSettings}
/> />
<ProtectedRoute path="/settings/interface" component={UISettings} /> <ProtectedRoute path="/settings/interface" component={UISettings} />
<ProtectedRoute <ProtectedRoute

View file

@ -1,7 +0,0 @@
.ThemeBuilder {
margin-bottom: 30px;
}
.Buttons button:not(:last-child) {
margin-right: 10px;
}

View file

@ -1,95 +0,0 @@
import { useState, useEffect } from 'react';
// Redux
import { useSelector, useDispatch } from 'react-redux';
import { bindActionCreators } from 'redux';
import { actionCreators } from '../../../../store';
import { State } from '../../../../store/reducers';
// Other
import { Theme } from '../../../../interfaces';
// UI
import { Button, Modal } from '../../../UI';
import { ThemeGrid } from '../ThemeGrid/ThemeGrid';
import classes from './ThemeBuilder.module.css';
import { ThemeCreator } from './ThemeCreator';
import { ThemeEditor } from './ThemeEditor';
interface Props {
themes: Theme[];
}
export const ThemeBuilder = ({ themes }: Props): JSX.Element => {
const {
auth: { isAuthenticated },
theme: { themeInEdit, userThemes },
} = useSelector((state: State) => state);
const { editTheme } = bindActionCreators(actionCreators, useDispatch());
const [showModal, toggleShowModal] = useState(false);
const [isInEdit, toggleIsInEdit] = useState(false);
useEffect(() => {
if (themeInEdit) {
toggleIsInEdit(false);
toggleShowModal(true);
}
}, [themeInEdit]);
useEffect(() => {
if (isInEdit && !userThemes.length) {
toggleIsInEdit(false);
toggleShowModal(false);
}
}, [userThemes]);
return (
<div className={classes.ThemeBuilder}>
{/* MODALS */}
<Modal
isOpen={showModal}
setIsOpen={() => toggleShowModal(!showModal)}
cb={() => editTheme(null)}
>
{isInEdit ? (
<ThemeEditor modalHandler={() => toggleShowModal(!showModal)} />
) : (
<ThemeCreator modalHandler={() => toggleShowModal(!showModal)} />
)}
</Modal>
{/* USER THEMES */}
<ThemeGrid themes={themes} />
{/* BUTTONS */}
{isAuthenticated && (
<div className={classes.Buttons}>
<Button
click={() => {
editTheme(null);
toggleIsInEdit(false);
toggleShowModal(!showModal);
}}
>
Create new theme
</Button>
{themes.length ? (
<Button
click={() => {
toggleIsInEdit(true);
toggleShowModal(!showModal);
}}
>
Edit user themes
</Button>
) : (
<></>
)}
</div>
)}
</div>
);
};

View file

@ -1,5 +0,0 @@
.ColorsContainer {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-gap: 10px;
}

View file

@ -1,152 +0,0 @@
import { ChangeEvent, FormEvent, useState, useEffect } from 'react';
// Redux
import { useDispatch, useSelector } from 'react-redux';
import { bindActionCreators } from 'redux';
import { actionCreators } from '../../../../store';
import { State } from '../../../../store/reducers';
// UI
import { Button, InputGroup, ModalForm } from '../../../UI';
import classes from './ThemeCreator.module.css';
// Other
import { Theme } from '../../../../interfaces';
interface Props {
modalHandler: () => void;
}
export const ThemeCreator = ({ modalHandler }: Props): JSX.Element => {
const {
theme: { activeTheme, themeInEdit },
} = useSelector((state: State) => state);
const { addTheme, updateTheme, editTheme } = bindActionCreators(
actionCreators,
useDispatch()
);
const [formData, setFormData] = useState<Theme>({
name: '',
isCustom: true,
colors: {
primary: '#ffffff',
accent: '#ffffff',
background: '#ffffff',
},
});
useEffect(() => {
setFormData({ ...formData, colors: activeTheme.colors });
}, [activeTheme]);
useEffect(() => {
if (themeInEdit) {
setFormData(themeInEdit);
}
}, [themeInEdit]);
const inputChangeHandler = (e: ChangeEvent<HTMLInputElement>) => {
const { name, value } = e.target;
setFormData({
...formData,
[name]: value,
});
};
const setColor = ({
target: { value, name },
}: ChangeEvent<HTMLInputElement>) => {
setFormData({
...formData,
colors: {
...formData.colors,
[name]: value,
},
});
};
const closeModal = () => {
editTheme(null);
modalHandler();
};
const formHandler = (e: FormEvent) => {
e.preventDefault();
if (!themeInEdit) {
addTheme(formData);
} else {
updateTheme(formData, themeInEdit.name);
}
// close modal
closeModal();
// clear theme name
setFormData({ ...formData, name: '' });
};
return (
<ModalForm formHandler={formHandler} modalHandler={closeModal}>
<InputGroup>
<label htmlFor="name">Theme name</label>
<input
type="text"
name="name"
id="name"
placeholder="my_theme"
required
value={formData.name}
onChange={(e) => inputChangeHandler(e)}
/>
</InputGroup>
<div className={classes.ColorsContainer}>
<InputGroup>
<label htmlFor="primary">Primary color</label>
<input
type="color"
name="primary"
id="primary"
required
value={formData.colors.primary}
onChange={(e) => setColor(e)}
/>
</InputGroup>
<InputGroup>
<label htmlFor="accent">Accent color</label>
<input
type="color"
name="accent"
id="accent"
required
value={formData.colors.accent}
onChange={(e) => setColor(e)}
/>
</InputGroup>
<InputGroup>
<label htmlFor="background">Background color</label>
<input
type="color"
name="background"
id="background"
required
value={formData.colors.background}
onChange={(e) => setColor(e)}
/>
</InputGroup>
</div>
{!themeInEdit ? (
<Button>Add theme</Button>
) : (
<Button>Update theme</Button>
)}
</ModalForm>
);
};

View file

@ -1,57 +0,0 @@
import { Fragment } from 'react';
// Redux
import { useSelector, useDispatch } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Theme } from '../../../../interfaces';
import { actionCreators } from '../../../../store';
import { State } from '../../../../store/reducers';
// Other
import { ActionIcons, CompactTable, Icon, ModalForm } from '../../../UI';
interface Props {
modalHandler: () => void;
}
export const ThemeEditor = (props: Props): JSX.Element => {
const {
theme: { userThemes },
} = useSelector((state: State) => state);
const { deleteTheme, editTheme } = bindActionCreators(
actionCreators,
useDispatch()
);
const updateHandler = (theme: Theme) => {
props.modalHandler();
editTheme(theme);
};
const deleteHandler = (theme: Theme) => {
if (window.confirm(`Are you sure you want to delete this theme?`)) {
deleteTheme(theme.name);
}
};
return (
<ModalForm formHandler={() => {}} modalHandler={props.modalHandler}>
<CompactTable headers={['Name', 'Actions']}>
{userThemes.map((t, idx) => (
<Fragment key={idx}>
<span>{t.name}</span>
<ActionIcons>
<span onClick={() => updateHandler(t)}>
<Icon icon="mdiPencil" />
</span>
<span onClick={() => deleteHandler(t)}>
<Icon icon="mdiDelete" />
</span>
</ActionIcons>
</Fragment>
))}
</CompactTable>
</ModalForm>
);
};

View file

@ -1,22 +0,0 @@
// Components
import { ThemePreview } from '../ThemePreview/ThemePreview';
// Other
import { Theme } from '../../../../interfaces';
import classes from './ThemeGrid.module.css';
interface Props {
themes: Theme[];
}
export const ThemeGrid = ({ themes }: Props): JSX.Element => {
return (
<div className={classes.ThemerGrid}>
{themes.map(
(theme: Theme, idx: number): JSX.Element => (
<ThemePreview key={idx} theme={theme} />
)
)}
</div>
);
};

View file

@ -1,38 +0,0 @@
// Redux
import { useDispatch } from 'react-redux';
import { bindActionCreators } from 'redux';
import { actionCreators } from '../../../../store';
// Other
import { Theme } from '../../../../interfaces/Theme';
import classes from './ThemePreview.module.css';
interface Props {
theme: Theme;
}
export const ThemePreview = ({
theme: { colors, name },
}: Props): JSX.Element => {
const { setTheme } = bindActionCreators(actionCreators, useDispatch());
return (
<div className={classes.ThemePreview} onClick={() => setTheme(colors)}>
<div className={classes.ColorsPreview}>
<div
className={classes.ColorPreview}
style={{ backgroundColor: colors.background }}
></div>
<div
className={classes.ColorPreview}
style={{ backgroundColor: colors.primary }}
></div>
<div
className={classes.ColorPreview}
style={{ backgroundColor: colors.accent }}
></div>
</div>
<p>{name}</p>
</div>
);
};

View file

@ -1,105 +0,0 @@
import { ChangeEvent, FormEvent, Fragment, useEffect, useState } from 'react';
// Redux
import { useDispatch, useSelector } from 'react-redux';
import { bindActionCreators } from 'redux';
import { actionCreators } from '../../../store';
import { State } from '../../../store/reducers';
// Typescript
import { Theme, ThemeSettingsForm } from '../../../interfaces';
// Components
import { Button, InputGroup, SettingsHeadline, Spinner } from '../../UI';
import { ThemeBuilder } from './ThemeBuilder/ThemeBuilder';
import { ThemeGrid } from './ThemeGrid/ThemeGrid';
// Other
import {
inputHandler,
parseThemeToPAB,
themeSettingsTemplate,
} from '../../../utility';
export const Themer = (): JSX.Element => {
const {
auth: { isAuthenticated },
config: { loading, config },
theme: { themes, userThemes },
} = useSelector((state: State) => state);
const dispatch = useDispatch();
const { updateConfig } = bindActionCreators(actionCreators, dispatch);
// Initial state
const [formData, setFormData] = useState<ThemeSettingsForm>(
themeSettingsTemplate
);
// Get config
useEffect(() => {
setFormData({
...config,
});
}, [loading]);
// Form handler
const formSubmitHandler = async (e: FormEvent) => {
e.preventDefault();
// Save settings
await updateConfig({ ...formData });
};
// Input handler
const inputChangeHandler = (
e: ChangeEvent<HTMLInputElement | HTMLSelectElement>,
options?: { isNumber?: boolean; isBool?: boolean }
) => {
inputHandler<ThemeSettingsForm>({
e,
options,
setStateHandler: setFormData,
state: formData,
});
};
const customThemesEl = (
<Fragment>
<SettingsHeadline text="User themes" />
<ThemeBuilder themes={userThemes} />
</Fragment>
);
return (
<Fragment>
<SettingsHeadline text="App themes" />
{!themes.length ? <Spinner /> : <ThemeGrid themes={themes} />}
{!userThemes.length ? isAuthenticated && customThemesEl : customThemesEl}
{isAuthenticated && (
<form onSubmit={formSubmitHandler}>
<SettingsHeadline text="Other settings" />
<InputGroup>
<label htmlFor="defaultTheme">Default theme for new users</label>
<select
id="defaultTheme"
name="defaultTheme"
value={formData.defaultTheme}
onChange={(e) => inputChangeHandler(e)}
>
{[...themes, ...userThemes].map((theme: Theme, idx) => (
<option key={idx} value={parseThemeToPAB(theme.colors)}>
{theme.isCustom && '+'} {theme.name}
</option>
))}
</select>
</InputGroup>
<Button>Save changes</Button>
</form>
)}
</Fragment>
);
};

View file

@ -7,22 +7,27 @@ import { bindActionCreators } from 'redux';
import { actionCreators } from '../../../store'; import { actionCreators } from '../../../store';
// Typescript // Typescript
import { UISettingsForm } from '../../../interfaces'; import { OtherSettingsForm } from '../../../interfaces';
// UI // UI
import { InputGroup, Button, SettingsHeadline } from '../../UI'; import { InputGroup, Button, SettingsHeadline } from '../../UI';
// Utils // Utils
import { uiSettingsTemplate, inputHandler } from '../../../utility'; import { otherSettingsTemplate, inputHandler } from '../../../utility';
export const UISettings = (): JSX.Element => { export const UISettings = (): JSX.Element => {
const { loading, config } = useSelector((state: State) => state.config); const { loading, config } = useSelector((state: State) => state.config);
const dispatch = useDispatch(); const dispatch = useDispatch();
const { updateConfig } = bindActionCreators(actionCreators, dispatch); const { updateConfig, sortApps, sortCategories } = bindActionCreators(
actionCreators,
dispatch
);
// Initial state // Initial state
const [formData, setFormData] = useState<UISettingsForm>(uiSettingsTemplate); const [formData, setFormData] = useState<OtherSettingsForm>(
otherSettingsTemplate
);
// Get config // Get config
useEffect(() => { useEffect(() => {
@ -40,6 +45,10 @@ export const UISettings = (): JSX.Element => {
// Update local page title // Update local page title
document.title = formData.customTitle; document.title = formData.customTitle;
// Sort apps and categories with new settings
sortApps();
sortCategories();
}; };
// Input handler // Input handler
@ -47,7 +56,7 @@ export const UISettings = (): JSX.Element => {
e: ChangeEvent<HTMLInputElement | HTMLSelectElement>, e: ChangeEvent<HTMLInputElement | HTMLSelectElement>,
options?: { isNumber?: boolean; isBool?: boolean } options?: { isNumber?: boolean; isBool?: boolean }
) => { ) => {
inputHandler<UISettingsForm>({ inputHandler<OtherSettingsForm>({
e, e,
options, options,
setStateHandler: setFormData, setStateHandler: setFormData,
@ -57,7 +66,7 @@ export const UISettings = (): JSX.Element => {
return ( return (
<form onSubmit={(e) => formSubmitHandler(e)}> <form onSubmit={(e) => formSubmitHandler(e)}>
{/* === OTHER OPTIONS === */} {/* OTHER OPTIONS */}
<SettingsHeadline text="Miscellaneous" /> <SettingsHeadline text="Miscellaneous" />
{/* PAGE TITLE */} {/* PAGE TITLE */}
<InputGroup> <InputGroup>
@ -72,82 +81,6 @@ export const UISettings = (): JSX.Element => {
/> />
</InputGroup> </InputGroup>
{/* === SEARCH OPTIONS === */}
<SettingsHeadline text="Search" />
{/* HIDE SEARCHBAR */}
<InputGroup>
<label htmlFor="hideSearch">Hide search bar</label>
<select
id="hideSearch"
name="hideSearch"
value={formData.hideSearch ? 1 : 0}
onChange={(e) => inputChangeHandler(e, { isBool: true })}
>
<option value={1}>True</option>
<option value={0}>False</option>
</select>
</InputGroup>
{/* AUTOFOCUS SEARCHBAR */}
<InputGroup>
<label htmlFor="disableAutofocus">Disable search bar autofocus</label>
<select
id="disableAutofocus"
name="disableAutofocus"
value={formData.disableAutofocus ? 1 : 0}
onChange={(e) => inputChangeHandler(e, { isBool: true })}
>
<option value={1}>True</option>
<option value={0}>False</option>
</select>
</InputGroup>
{/* === HEADER OPTIONS === */}
<SettingsHeadline text="Header" />
{/* HIDE HEADER */}
<InputGroup>
<label htmlFor="hideHeader">
Hide headline (greetings and weather)
</label>
<select
id="hideHeader"
name="hideHeader"
value={formData.hideHeader ? 1 : 0}
onChange={(e) => inputChangeHandler(e, { isBool: true })}
>
<option value={1}>True</option>
<option value={0}>False</option>
</select>
</InputGroup>
{/* HIDE DATE */}
<InputGroup>
<label htmlFor="hideDate">Hide date</label>
<select
id="hideDate"
name="hideDate"
value={formData.hideDate ? 1 : 0}
onChange={(e) => inputChangeHandler(e, { isBool: true })}
>
<option value={1}>True</option>
<option value={0}>False</option>
</select>
</InputGroup>
{/* HIDE TIME */}
<InputGroup>
<label htmlFor="showTime">Hide time</label>
<select
id="showTime"
name="showTime"
value={formData.showTime ? 1 : 0}
onChange={(e) => inputChangeHandler(e, { isBool: true })}
>
<option value={0}>True</option>
<option value={1}>False</option>
</select>
</InputGroup>
{/* DATE FORMAT */} {/* DATE FORMAT */}
<InputGroup> <InputGroup>
<label htmlFor="useAmericanDate">Date formatting</label> <label htmlFor="useAmericanDate">Date formatting</label>
@ -162,6 +95,99 @@ export const UISettings = (): JSX.Element => {
</select> </select>
</InputGroup> </InputGroup>
{/* BEAHVIOR OPTIONS */}
<SettingsHeadline text="App Behavior" />
{/* PIN APPS */}
<InputGroup>
<label htmlFor="pinAppsByDefault">
Pin new applications by default
</label>
<select
id="pinAppsByDefault"
name="pinAppsByDefault"
value={formData.pinAppsByDefault ? 1 : 0}
onChange={(e) => inputChangeHandler(e, { isBool: true })}
>
<option value={1}>True</option>
<option value={0}>False</option>
</select>
</InputGroup>
{/* PIN CATEGORIES */}
<InputGroup>
<label htmlFor="pinCategoriesByDefault">
Pin new categories by default
</label>
<select
id="pinCategoriesByDefault"
name="pinCategoriesByDefault"
value={formData.pinCategoriesByDefault ? 1 : 0}
onChange={(e) => inputChangeHandler(e, { isBool: true })}
>
<option value={1}>True</option>
<option value={0}>False</option>
</select>
</InputGroup>
{/* SORT TYPE */}
<InputGroup>
<label htmlFor="useOrdering">Sorting type</label>
<select
id="useOrdering"
name="useOrdering"
value={formData.useOrdering}
onChange={(e) => inputChangeHandler(e)}
>
<option value="createdAt">By creation date</option>
<option value="name">Alphabetical order</option>
<option value="orderId">Custom order</option>
</select>
</InputGroup>
{/* APPS OPPENING */}
<InputGroup>
<label htmlFor="appsSameTab">Open applications in the same tab</label>
<select
id="appsSameTab"
name="appsSameTab"
value={formData.appsSameTab ? 1 : 0}
onChange={(e) => inputChangeHandler(e, { isBool: true })}
>
<option value={1}>True</option>
<option value={0}>False</option>
</select>
</InputGroup>
{/* BOOKMARKS OPPENING */}
<InputGroup>
<label htmlFor="bookmarksSameTab">Open bookmarks in the same tab</label>
<select
id="bookmarksSameTab"
name="bookmarksSameTab"
value={formData.bookmarksSameTab ? 1 : 0}
onChange={(e) => inputChangeHandler(e, { isBool: true })}
>
<option value={1}>True</option>
<option value={0}>False</option>
</select>
</InputGroup>
{/* HEADER OPTIONS */}
<SettingsHeadline text="Header" />
{/* HIDE HEADER */}
<InputGroup>
<label htmlFor="hideHeader">Hide greeting and date</label>
<select
id="hideHeader"
name="hideHeader"
value={formData.hideHeader ? 1 : 0}
onChange={(e) => inputChangeHandler(e, { isBool: true })}
>
<option value={1}>True</option>
<option value={0}>False</option>
</select>
</InputGroup>
{/* CUSTOM GREETINGS */} {/* CUSTOM GREETINGS */}
<InputGroup> <InputGroup>
<label htmlFor="greetingsSchema">Custom greetings</label> <label htmlFor="greetingsSchema">Custom greetings</label>
@ -174,8 +200,8 @@ export const UISettings = (): JSX.Element => {
onChange={(e) => inputChangeHandler(e)} onChange={(e) => inputChangeHandler(e)}
/> />
<span> <span>
Greetings must be separated with semicolon. All 4 messages must be Greetings must be separated with semicolon. Only 4 messages can be
filled, even if they are the same used
</span> </span>
</InputGroup> </InputGroup>
@ -207,8 +233,22 @@ export const UISettings = (): JSX.Element => {
<span>Names must be separated with semicolon</span> <span>Names must be separated with semicolon</span>
</InputGroup> </InputGroup>
{/* === SECTIONS OPTIONS === */} {/* SHOW TIME */}
<SettingsHeadline text="Sections" /> <InputGroup>
<label htmlFor="showTime">Show time</label>
<select
id="showTime"
name="showTime"
value={formData.showTime ? 1 : 0}
onChange={(e) => inputChangeHandler(e, { isBool: true })}
>
<option value={1}>True</option>
<option value={0}>False</option>
</select>
</InputGroup>
{/* MODULES OPTIONS */}
<SettingsHeadline text="Modules" />
{/* HIDE APPS */} {/* HIDE APPS */}
<InputGroup> <InputGroup>
<label htmlFor="hideApps">Hide applications</label> <label htmlFor="hideApps">Hide applications</label>
@ -223,9 +263,9 @@ export const UISettings = (): JSX.Element => {
</select> </select>
</InputGroup> </InputGroup>
{/* HIDE BOOKMARK CATEGORIES */} {/* HIDE CATEGORIES */}
<InputGroup> <InputGroup>
<label htmlFor="hideCategories">Hide bookmarks</label> <label htmlFor="hideCategories">Hide categories</label>
<select <select
id="hideCategories" id="hideCategories"
name="hideCategories" name="hideCategories"

View file

@ -11,7 +11,7 @@ import { State } from '../../../store/reducers';
import { ApiResponse, Weather, WeatherForm } from '../../../interfaces'; import { ApiResponse, Weather, WeatherForm } from '../../../interfaces';
// UI // UI
import { InputGroup, Button, SettingsHeadline } from '../../UI'; import { InputGroup, Button } from '../../UI';
// Utils // Utils
import { inputHandler, weatherSettingsTemplate } from '../../../utility'; import { inputHandler, weatherSettingsTemplate } from '../../../utility';
@ -82,23 +82,8 @@ export const WeatherSettings = (): JSX.Element => {
}); });
}; };
// Get user location
const getLocation = () => {
window.navigator.geolocation.getCurrentPosition(
({ coords: { latitude, longitude } }) => {
setFormData({
...formData,
lat: latitude,
long: longitude,
});
}
);
};
return ( return (
<form onSubmit={(e) => formSubmitHandler(e)}> <form onSubmit={(e) => formSubmitHandler(e)}>
<SettingsHeadline text="API" />
{/* API KEY */}
<InputGroup> <InputGroup>
<label htmlFor="WEATHER_API_KEY">API key</label> <label htmlFor="WEATHER_API_KEY">API key</label>
<input <input
@ -119,10 +104,8 @@ export const WeatherSettings = (): JSX.Element => {
</span> </span>
</InputGroup> </InputGroup>
<SettingsHeadline text="Location" />
{/* LAT */}
<InputGroup> <InputGroup>
<label htmlFor="lat">Latitude</label> <label htmlFor="lat">Location latitude</label>
<input <input
type="number" type="number"
id="lat" id="lat"
@ -133,14 +116,20 @@ export const WeatherSettings = (): JSX.Element => {
step="any" step="any"
lang="en-150" lang="en-150"
/> />
<span onClick={getLocation}> <span>
<a href="#">Click to get current location</a> You can use
<a
href="https://www.latlong.net/convert-address-to-lat-long.html"
target="blank"
>
{' '}
latlong.net
</a>
</span> </span>
</InputGroup> </InputGroup>
{/* LONG */}
<InputGroup> <InputGroup>
<label htmlFor="long">Longitude</label> <label htmlFor="long">Location longitude</label>
<input <input
type="number" type="number"
id="long" id="long"
@ -153,8 +142,6 @@ export const WeatherSettings = (): JSX.Element => {
/> />
</InputGroup> </InputGroup>
<SettingsHeadline text="Other" />
{/* TEMPERATURE */}
<InputGroup> <InputGroup>
<label htmlFor="isCelsius">Temperature unit</label> <label htmlFor="isCelsius">Temperature unit</label>
<select <select
@ -168,20 +155,6 @@ export const WeatherSettings = (): JSX.Element => {
</select> </select>
</InputGroup> </InputGroup>
{/* WEATHER DATA */}
<InputGroup>
<label htmlFor="weatherData">Additional weather data</label>
<select
id="weatherData"
name="weatherData"
value={formData.weatherData}
onChange={(e) => inputChangeHandler(e)}
>
<option value="cloud">Cloud coverage</option>
<option value="humidity">Humidity</option>
</select>
</InputGroup>
<Button>Save changes</Button> <Button>Save changes</Button>
</form> </form>
); );

View file

@ -6,8 +6,13 @@
"authRequired": false "authRequired": false
}, },
{ {
"name": "General", "name": "Weather",
"dest": "/settings/general", "dest": "/settings/weather",
"authRequired": true
},
{
"name": "Search",
"dest": "/settings/search",
"authRequired": true "authRequired": true
}, },
{ {
@ -15,11 +20,6 @@
"dest": "/settings/interface", "dest": "/settings/interface",
"authRequired": true "authRequired": true
}, },
{
"name": "Weather",
"dest": "/settings/weather",
"authRequired": true
},
{ {
"name": "Docker", "name": "Docker",
"dest": "/settings/docker", "dest": "/settings/docker",

View file

@ -14,6 +14,7 @@
text-transform: capitalize; text-transform: capitalize;
margin: 8px 0; margin: 8px 0;
color: var(--color-primary); color: var(--color-primary);
/* align-self: flex-start; */
} }
.ColorsPreview { .ColorsPreview {
@ -31,4 +32,4 @@
width: 40px; width: 40px;
height: 40px; height: 40px;
} }
} }

View file

@ -0,0 +1,32 @@
import { Theme } from '../../interfaces/Theme';
import classes from './ThemePreview.module.css';
interface Props {
theme: Theme;
applyTheme: Function;
}
export const ThemePreview = (props: Props): JSX.Element => {
return (
<div
className={classes.ThemePreview}
onClick={() => props.applyTheme(props.theme.name)}
>
<div className={classes.ColorsPreview}>
<div
className={classes.ColorPreview}
style={{ backgroundColor: props.theme.colors.background }}
></div>
<div
className={classes.ColorPreview}
style={{ backgroundColor: props.theme.colors.primary }}
></div>
<div
className={classes.ColorPreview}
style={{ backgroundColor: props.theme.colors.accent }}
></div>
</div>
<p>{props.theme.name}</p>
</div>
);
};

View file

@ -15,4 +15,4 @@
.ThemerGrid { .ThemerGrid {
grid-template-columns: 1fr 1fr 1fr; grid-template-columns: 1fr 1fr 1fr;
} }
} }

View file

@ -0,0 +1,29 @@
import { Fragment } from 'react';
import { useDispatch } from 'react-redux';
import { bindActionCreators } from 'redux';
import { actionCreators } from '../../store';
import classes from './Themer.module.css';
import { themes } from './themes.json';
import { Theme } from '../../interfaces/Theme';
import { ThemePreview } from './ThemePreview';
export const Themer = (): JSX.Element => {
const dispatch = useDispatch();
const { setTheme } = bindActionCreators(actionCreators, dispatch);
return (
<Fragment>
<div>
<div className={classes.ThemerGrid}>
{themes.map(
(theme: Theme, idx: number): JSX.Element => (
<ThemePreview key={idx} theme={theme} applyTheme={setTheme} />
)
)}
</div>
</div>
</Fragment>
);
};

View file

@ -6,8 +6,7 @@
"background": "#1a1a1a", "background": "#1a1a1a",
"primary": "#FFFDEA", "primary": "#FFFDEA",
"accent": "#5c5c5c" "accent": "#5c5c5c"
}, }
"isCustom": false
}, },
{ {
"name": "gazette", "name": "gazette",
@ -15,8 +14,7 @@
"background": "#F2F7FF", "background": "#F2F7FF",
"primary": "#000000", "primary": "#000000",
"accent": "#5c5c5c" "accent": "#5c5c5c"
}, }
"isCustom": false
}, },
{ {
"name": "espresso", "name": "espresso",
@ -24,8 +22,7 @@
"background": "#21211F", "background": "#21211F",
"primary": "#D1B59A", "primary": "#D1B59A",
"accent": "#4E4E4E" "accent": "#4E4E4E"
}, }
"isCustom": false
}, },
{ {
"name": "cab", "name": "cab",
@ -33,8 +30,7 @@
"background": "#F6D305", "background": "#F6D305",
"primary": "#1F1F1F", "primary": "#1F1F1F",
"accent": "#424242" "accent": "#424242"
}, }
"isCustom": false
}, },
{ {
"name": "cloud", "name": "cloud",
@ -42,8 +38,7 @@
"background": "#f1f2f0", "background": "#f1f2f0",
"primary": "#35342f", "primary": "#35342f",
"accent": "#37bbe4" "accent": "#37bbe4"
}, }
"isCustom": false
}, },
{ {
"name": "lime", "name": "lime",
@ -51,8 +46,7 @@
"background": "#263238", "background": "#263238",
"primary": "#AABBC3", "primary": "#AABBC3",
"accent": "#aeea00" "accent": "#aeea00"
}, }
"isCustom": false
}, },
{ {
"name": "white", "name": "white",
@ -60,8 +54,7 @@
"background": "#ffffff", "background": "#ffffff",
"primary": "#222222", "primary": "#222222",
"accent": "#dddddd" "accent": "#dddddd"
}, }
"isCustom": false
}, },
{ {
"name": "tron", "name": "tron",
@ -69,8 +62,7 @@
"background": "#242B33", "background": "#242B33",
"primary": "#EFFBFF", "primary": "#EFFBFF",
"accent": "#6EE2FF" "accent": "#6EE2FF"
}, }
"isCustom": false
}, },
{ {
"name": "blues", "name": "blues",
@ -78,8 +70,7 @@
"background": "#2B2C56", "background": "#2B2C56",
"primary": "#EFF1FC", "primary": "#EFF1FC",
"accent": "#6677EB" "accent": "#6677EB"
}, }
"isCustom": false
}, },
{ {
"name": "passion", "name": "passion",
@ -87,8 +78,7 @@
"background": "#f5f5f5", "background": "#f5f5f5",
"primary": "#12005e", "primary": "#12005e",
"accent": "#8e24aa" "accent": "#8e24aa"
}, }
"isCustom": false
}, },
{ {
"name": "chalk", "name": "chalk",
@ -96,8 +86,7 @@
"background": "#263238", "background": "#263238",
"primary": "#AABBC3", "primary": "#AABBC3",
"accent": "#FF869A" "accent": "#FF869A"
}, }
"isCustom": false
}, },
{ {
"name": "paper", "name": "paper",
@ -105,8 +94,7 @@
"background": "#F8F6F1", "background": "#F8F6F1",
"primary": "#4C432E", "primary": "#4C432E",
"accent": "#AA9A73" "accent": "#AA9A73"
}, }
"isCustom": false
}, },
{ {
"name": "neon", "name": "neon",
@ -114,8 +102,7 @@
"background": "#091833", "background": "#091833",
"primary": "#EFFBFF", "primary": "#EFFBFF",
"accent": "#ea00d9" "accent": "#ea00d9"
}, }
"isCustom": false
}, },
{ {
"name": "pumpkin", "name": "pumpkin",
@ -123,8 +110,7 @@
"background": "#2d3436", "background": "#2d3436",
"primary": "#EFFBFF", "primary": "#EFFBFF",
"accent": "#ffa500" "accent": "#ffa500"
}, }
"isCustom": false
}, },
{ {
"name": "onedark", "name": "onedark",
@ -132,17 +118,7 @@
"background": "#282c34", "background": "#282c34",
"primary": "#dfd9d6", "primary": "#dfd9d6",
"accent": "#98c379" "accent": "#98c379"
}, }
"isCustom": false
},
{
"name": "mint",
"colors": {
"background": "#282525",
"primary": "#d9d9d9",
"accent": "#50fbc2"
},
"isCustom": false
} }
] ]
} }

View file

@ -23,7 +23,7 @@
.InputGroup span { .InputGroup span {
font-size: 12px; font-size: 12px;
color: var(--color-primary); color: var(--color-primary)
} }
.InputGroup span a { .InputGroup span a {
@ -37,14 +37,4 @@
.InputGroup textarea { .InputGroup textarea {
resize: none; resize: none;
height: 50vh; height: 50vh;
} }
.InputGroup input[type='color'] {
margin: 0;
padding: 0;
background-color: transparent;
}
.InputGroup input[type='color']:hover {
cursor: pointer;
}

View file

@ -1,4 +1,4 @@
import classes from './SettingsHeadline.module.css'; const classes = require('./SettingsHeadline.module.css');
interface Props { interface Props {
text: string; text: string;

View file

@ -1,11 +0,0 @@
.ActionIcons {
display: flex;
}
.ActionIcons svg {
width: 20px;
}
.ActionIcons svg:hover {
cursor: pointer;
}

View file

@ -1,10 +0,0 @@
import { ReactNode } from 'react';
import styles from './ActionIcons.module.css';
interface Props {
children: ReactNode;
}
export const ActionIcons = ({ children }: Props): JSX.Element => {
return <span className={styles.ActionIcons}>{children}</span>;
};

View file

@ -10,7 +10,7 @@ interface Props {
} }
export const WeatherIcon = (props: Props): JSX.Element => { export const WeatherIcon = (props: Props): JSX.Element => {
const { activeTheme } = useSelector((state: State) => state.theme); const { theme } = useSelector((state: State) => state.theme);
const icon = props.isDay const icon = props.isDay
? new IconMapping().mapIcon(props.weatherStatusCode, TimeOfDay.day) ? new IconMapping().mapIcon(props.weatherStatusCode, TimeOfDay.day)
@ -18,7 +18,7 @@ export const WeatherIcon = (props: Props): JSX.Element => {
useEffect(() => { useEffect(() => {
const delay = setTimeout(() => { const delay = setTimeout(() => {
const skycons = new Skycons({ color: activeTheme.colors.accent }); const skycons = new Skycons({ color: theme.colors.accent });
skycons.add(`weather-icon`, icon); skycons.add(`weather-icon`, icon);
skycons.play(); skycons.play();
}, 1); }, 1);
@ -26,7 +26,7 @@ export const WeatherIcon = (props: Props): JSX.Element => {
return () => { return () => {
clearTimeout(delay); clearTimeout(delay);
}; };
}, [props.weatherStatusCode, icon, activeTheme.colors.accent]); }, [props.weatherStatusCode, icon, theme.colors.accent]);
return <canvas id={`weather-icon`} width="50" height="50"></canvas>; return <canvas id={`weather-icon`} width="50" height="50"></canvas>;
}; };

View file

@ -6,32 +6,24 @@ interface Props {
isOpen: boolean; isOpen: boolean;
setIsOpen: Function; setIsOpen: Function;
children: ReactNode; children: ReactNode;
cb?: Function;
} }
export const Modal = ({ export const Modal = (props: Props): JSX.Element => {
isOpen,
setIsOpen,
children,
cb,
}: Props): JSX.Element => {
const modalRef = useRef(null); const modalRef = useRef(null);
const modalClasses = [ const modalClasses = [
classes.Modal, classes.Modal,
isOpen ? classes.ModalOpen : classes.ModalClose, props.isOpen ? classes.ModalOpen : classes.ModalClose,
].join(' '); ].join(' ');
const clickHandler = (e: MouseEvent) => { const clickHandler = (e: MouseEvent) => {
if (e.target === modalRef.current) { if (e.target === modalRef.current) {
setIsOpen(false); props.setIsOpen(false);
if (cb) cb();
} }
}; };
return ( return (
<div className={modalClasses} onClick={clickHandler} ref={modalRef}> <div className={modalClasses} onClick={clickHandler} ref={modalRef}>
{children} {props.children}
</div> </div>
); );
}; };

View file

@ -1,16 +0,0 @@
.CompactTable {
display: grid;
}
.CompactTable span {
color: var(--color-primary);
}
.CompactTable span:last-child {
margin-bottom: 10px;
}
.Separator {
border-bottom: 1px solid var(--color-primary);
margin: 10px 0;
}

View file

@ -1,27 +0,0 @@
import { ReactNode } from 'react';
import classes from './CompactTable.module.css';
interface Props {
headers: string[];
children?: ReactNode;
}
export const CompactTable = ({ headers, children }: Props): JSX.Element => {
return (
<div
className={classes.CompactTable}
style={{ gridTemplateColumns: `repeat(${headers.length}, 1fr)` }}
>
{headers.map((h, idx) => (
<span key={idx}>{h}</span>
))}
<div
className={classes.Separator}
style={{ gridColumn: `1 / ${headers.length + 1}` }}
></div>
{children}
</div>
);
};

View file

@ -1,14 +0,0 @@
import { ReactNode } from 'react';
import classes from './Message.module.css';
interface Props {
children: ReactNode;
isPrimary?: boolean;
}
export const Message = ({ children, isPrimary = true }: Props): JSX.Element => {
const style = isPrimary ? classes.message : classes.messageCenter;
return <p className={style}>{children}</p>;
};

View file

@ -1,12 +1,10 @@
export * from './Tables/Table/Table'; export * from './Table/Table';
export * from './Tables/CompactTable/CompactTable';
export * from './Spinner/Spinner'; export * from './Spinner/Spinner';
export * from './Notification/Notification'; export * from './Notification/Notification';
export * from './Modal/Modal'; export * from './Modal/Modal';
export * from './Layout/Layout'; export * from './Layout/Layout';
export * from './Icons/Icon/Icon'; export * from './Icons/Icon/Icon';
export * from './Icons/WeatherIcon/WeatherIcon'; export * from './Icons/WeatherIcon/WeatherIcon';
export * from './Icons/ActionIcons/ActionIcons';
export * from './Headlines/Headline/Headline'; export * from './Headlines/Headline/Headline';
export * from './Headlines/SectionHeadline/SectionHeadline'; export * from './Headlines/SectionHeadline/SectionHeadline';
export * from './Headlines/SettingsHeadline/SettingsHeadline'; export * from './Headlines/SettingsHeadline/SettingsHeadline';
@ -14,4 +12,3 @@ export * from './Forms/InputGroup/InputGroup';
export * from './Forms/ModalForm/ModalForm'; export * from './Forms/ModalForm/ModalForm';
export * from './Buttons/ActionButton/ActionButton'; export * from './Buttons/ActionButton/ActionButton';
export * from './Buttons/Button/Button'; export * from './Buttons/Button/Button';
export * from './Text/Message/Message';

View file

@ -13,14 +13,22 @@ import classes from './WeatherWidget.module.css';
// UI // UI
import { WeatherIcon } from '../../UI'; import { WeatherIcon } from '../../UI';
import { State } from '../../../store/reducers'; import { State } from '../../../store/reducers';
import { weatherTemplate } from '../../../utility/templateObjects/weatherTemplate';
export const WeatherWidget = (): JSX.Element => { export const WeatherWidget = (): JSX.Element => {
const { loading: configLoading, config } = useSelector( const { loading, config } = useSelector((state: State) => state.config);
(state: State) => state.config
);
const [weather, setWeather] = useState<Weather>(weatherTemplate); const [weather, setWeather] = useState<Weather>({
externalLastUpdate: '',
tempC: 0,
tempF: 0,
isDay: 1,
cloud: 0,
conditionText: '',
conditionCode: 1000,
id: -1,
createdAt: new Date(),
updatedAt: new Date(),
});
const [isLoading, setIsLoading] = useState(true); const [isLoading, setIsLoading] = useState(true);
// Initial request to get data // Initial request to get data
@ -57,7 +65,8 @@ export const WeatherWidget = (): JSX.Element => {
return ( return (
<div className={classes.WeatherWidget}> <div className={classes.WeatherWidget}>
{configLoading || {isLoading ||
loading ||
(config.WEATHER_API_KEY && weather.id > 0 && ( (config.WEATHER_API_KEY && weather.id > 0 && (
<Fragment> <Fragment>
<div className={classes.WeatherIcon}> <div className={classes.WeatherIcon}>
@ -67,15 +76,12 @@ export const WeatherWidget = (): JSX.Element => {
/> />
</div> </div>
<div className={classes.WeatherDetails}> <div className={classes.WeatherDetails}>
{/* TEMPERATURE */}
{config.isCelsius ? ( {config.isCelsius ? (
<span>{weather.tempC}°C</span> <span>{weather.tempC}°C</span>
) : ( ) : (
<span>{Math.round(weather.tempF)}°F</span> <span>{weather.tempF}°F</span>
)} )}
<span>{weather.cloud}%</span>
{/* ADDITIONAL DATA */}
<span>{weather[config.weatherData]}%</span>
</div> </div>
</Fragment> </Fragment>
))} ))}

View file

@ -5,7 +5,6 @@ export interface NewApp {
url: string; url: string;
icon: string; icon: string;
isPublic: boolean; isPublic: boolean;
description: string;
} }
export interface App extends Model, NewApp { export interface App extends Model, NewApp {

View file

@ -8,6 +8,4 @@ export interface NewBookmark {
isPublic: boolean; isPublic: boolean;
} }
export interface Bookmark extends Model, NewBookmark { export interface Bookmark extends Model, NewBookmark {}
orderId: number;
}

View file

@ -1,5 +1,3 @@
import { WeatherData } from '../types';
export interface Config { export interface Config {
WEATHER_API_KEY: string; WEATHER_API_KEY: string;
lat: number; lat: number;
@ -17,7 +15,6 @@ export interface Config {
hideCategories: boolean; hideCategories: boolean;
hideSearch: boolean; hideSearch: boolean;
defaultSearchProvider: string; defaultSearchProvider: string;
secondarySearchProvider: string;
dockerApps: boolean; dockerApps: boolean;
dockerHost: string; dockerHost: string;
kubernetesApps: boolean; kubernetesApps: boolean;
@ -28,8 +25,4 @@ export interface Config {
daySchema: string; daySchema: string;
monthSchema: string; monthSchema: string;
showTime: boolean; showTime: boolean;
defaultTheme: string;
isKilometer: boolean;
weatherData: WeatherData;
hideDate: boolean;
} }

View file

@ -1,37 +1,32 @@
import { WeatherData } from '../types';
export interface WeatherForm { export interface WeatherForm {
WEATHER_API_KEY: string; WEATHER_API_KEY: string;
lat: number; lat: number;
long: number; long: number;
isCelsius: boolean; isCelsius: boolean;
weatherData: WeatherData;
} }
export interface GeneralForm { export interface SearchForm {
hideSearch: boolean;
defaultSearchProvider: string; defaultSearchProvider: string;
secondarySearchProvider: string;
searchSameTab: boolean; searchSameTab: boolean;
disableAutofocus: boolean;
}
export interface OtherSettingsForm {
customTitle: string;
pinAppsByDefault: boolean; pinAppsByDefault: boolean;
pinCategoriesByDefault: boolean; pinCategoriesByDefault: boolean;
useOrdering: string;
appsSameTab: boolean;
bookmarksSameTab: boolean;
}
export interface UISettingsForm {
customTitle: string;
hideHeader: boolean; hideHeader: boolean;
hideApps: boolean; hideApps: boolean;
hideCategories: boolean; hideCategories: boolean;
useOrdering: string;
appsSameTab: boolean;
bookmarksSameTab: boolean;
useAmericanDate: boolean; useAmericanDate: boolean;
greetingsSchema: string; greetingsSchema: string;
daySchema: string; daySchema: string;
monthSchema: string; monthSchema: string;
showTime: boolean; showTime: boolean;
hideDate: boolean;
hideSearch: boolean;
disableAutofocus: boolean;
} }
export interface DockerSettingsForm { export interface DockerSettingsForm {
@ -40,7 +35,3 @@ export interface DockerSettingsForm {
kubernetesApps: boolean; kubernetesApps: boolean;
unpinStoppedApps: boolean; unpinStoppedApps: boolean;
} }
export interface ThemeSettingsForm {
defaultTheme: string;
}

View file

@ -4,8 +4,6 @@ export interface SearchResult {
isLocal: boolean; isLocal: boolean;
isURL: boolean; isURL: boolean;
sameTab: boolean; sameTab: boolean;
encodedURL: string; search: string;
primarySearch: Query; query: Query;
secondarySearch: Query;
rawQuery: string;
} }

View file

@ -1,11 +1,8 @@
export interface ThemeColors {
background: string;
primary: string;
accent: string;
}
export interface Theme { export interface Theme {
name: string; name: string;
colors: ThemeColors; colors: {
isCustom: boolean; background: string;
} primary: string;
accent: string;
}
}

View file

@ -8,7 +8,4 @@ export interface Weather extends Model {
cloud: number; cloud: number;
conditionText: string; conditionText: string;
conditionCode: number; conditionCode: number;
humidity: number; }
windK: number;
windM: number;
}

View file

@ -7,7 +7,6 @@ import {
GetAppsAction, GetAppsAction,
PinAppAction, PinAppAction,
ReorderAppsAction, ReorderAppsAction,
SetEditAppAction,
SortAppsAction, SortAppsAction,
UpdateAppAction, UpdateAppAction,
} from '../actions/app'; } from '../actions/app';
@ -197,11 +196,3 @@ export const sortApps = () => async (dispatch: Dispatch<SortAppsAction>) => {
console.log(err); console.log(err);
} }
}; };
export const setEditApp =
(app: App | null) => (dispatch: Dispatch<SetEditAppAction>) => {
dispatch({
type: ActionType.setEditApp,
payload: app,
});
};

View file

@ -1,8 +1,5 @@
import axios from 'axios'; import axios from 'axios';
import { Dispatch } from 'redux'; import { Dispatch } from 'redux';
import { applyAuth } from '../../utility';
import { ActionType } from '../action-types';
import { import {
ApiResponse, ApiResponse,
Bookmark, Bookmark,
@ -11,7 +8,8 @@ import {
NewBookmark, NewBookmark,
NewCategory, NewCategory,
} from '../../interfaces'; } from '../../interfaces';
import { applyAuth } from '../../utility';
import { ActionType } from '../action-types';
import { import {
AddBookmarkAction, AddBookmarkAction,
AddCategoryAction, AddCategoryAction,
@ -19,11 +17,7 @@ import {
DeleteCategoryAction, DeleteCategoryAction,
GetCategoriesAction, GetCategoriesAction,
PinCategoryAction, PinCategoryAction,
ReorderBookmarksAction,
ReorderCategoriesAction, ReorderCategoriesAction,
SetEditBookmarkAction,
SetEditCategoryAction,
SortBookmarksAction,
SortCategoriesAction, SortCategoriesAction,
UpdateBookmarkAction, UpdateBookmarkAction,
UpdateCategoryAction, UpdateCategoryAction,
@ -101,8 +95,6 @@ export const addBookmark =
type: ActionType.addBookmark, type: ActionType.addBookmark,
payload: res.data.data, payload: res.data.data,
}); });
dispatch<any>(sortBookmarks(res.data.data.categoryId));
} catch (err) { } catch (err) {
console.log(err); console.log(err);
} }
@ -274,8 +266,6 @@ export const updateBookmark =
payload: res.data.data, payload: res.data.data,
}); });
} }
dispatch<any>(sortBookmarks(res.data.data.categoryId));
} catch (err) { } catch (err) {
console.log(err); console.log(err);
} }
@ -329,73 +319,3 @@ export const reorderCategories =
console.log(err); console.log(err);
} }
}; };
export const setEditCategory =
(category: Category | null) =>
(dispatch: Dispatch<SetEditCategoryAction>) => {
dispatch({
type: ActionType.setEditCategory,
payload: category,
});
};
export const setEditBookmark =
(bookmark: Bookmark | null) =>
(dispatch: Dispatch<SetEditBookmarkAction>) => {
dispatch({
type: ActionType.setEditBookmark,
payload: bookmark,
});
};
export const reorderBookmarks =
(bookmarks: Bookmark[], categoryId: number) =>
async (dispatch: Dispatch<ReorderBookmarksAction>) => {
interface ReorderQuery {
bookmarks: {
id: number;
orderId: number;
}[];
}
try {
const updateQuery: ReorderQuery = { bookmarks: [] };
bookmarks.forEach((bookmark, index) =>
updateQuery.bookmarks.push({
id: bookmark.id,
orderId: index + 1,
})
);
await axios.put<ApiResponse<{}>>(
'/api/bookmarks/0/reorder',
updateQuery,
{ headers: applyAuth() }
);
dispatch({
type: ActionType.reorderBookmarks,
payload: { bookmarks, categoryId },
});
} catch (err) {
console.log(err);
}
};
export const sortBookmarks =
(categoryId: number) => async (dispatch: Dispatch<SortBookmarksAction>) => {
try {
const res = await axios.get<ApiResponse<Config>>('/api/config');
dispatch({
type: ActionType.sortBookmarks,
payload: {
orderType: res.data.data.useOrdering,
categoryId,
},
});
} catch (err) {
console.log(err);
}
};

View file

@ -7,11 +7,18 @@ import {
UpdateConfigAction, UpdateConfigAction,
UpdateQueryAction, UpdateQueryAction,
} from '../actions/config'; } from '../actions/config';
import axios, { AxiosError } from 'axios'; import axios from 'axios';
import { ApiResponse, Config, Query } from '../../interfaces'; import {
ApiResponse,
Config,
DockerSettingsForm,
OtherSettingsForm,
Query,
SearchForm,
WeatherForm,
} from '../../interfaces';
import { ActionType } from '../action-types'; import { ActionType } from '../action-types';
import { storeUIConfig, applyAuth } from '../../utility'; import { storeUIConfig, applyAuth } from '../../utility';
import { ConfigFormData } from '../../types';
const keys: (keyof Config)[] = [ const keys: (keyof Config)[] = [
'useAmericanDate', 'useAmericanDate',
@ -19,7 +26,6 @@ const keys: (keyof Config)[] = [
'daySchema', 'daySchema',
'monthSchema', 'monthSchema',
'showTime', 'showTime',
'hideDate',
]; ];
export const getConfig = () => async (dispatch: Dispatch<GetConfigAction>) => { export const getConfig = () => async (dispatch: Dispatch<GetConfigAction>) => {
@ -44,7 +50,9 @@ export const getConfig = () => async (dispatch: Dispatch<GetConfigAction>) => {
}; };
export const updateConfig = export const updateConfig =
(formData: ConfigFormData) => (
formData: WeatherForm | OtherSettingsForm | SearchForm | DockerSettingsForm
) =>
async (dispatch: Dispatch<UpdateConfigAction>) => { async (dispatch: Dispatch<UpdateConfigAction>) => {
try { try {
const res = await axios.put<ApiResponse<Config>>( const res = await axios.put<ApiResponse<Config>>(
@ -103,15 +111,7 @@ export const addQuery =
payload: res.data.data, payload: res.data.data,
}); });
} catch (err) { } catch (err) {
const error = err as AxiosError<{ error: string }>; console.log(err);
dispatch<any>({
type: ActionType.createNotification,
payload: {
title: 'Error',
message: error.response?.data.error,
},
});
} }
}; };

View file

@ -1,128 +1,26 @@
import { Dispatch } from 'redux'; import { Dispatch } from 'redux';
import { import { SetThemeAction } from '../actions/theme';
AddThemeAction,
DeleteThemeAction,
EditThemeAction,
FetchThemesAction,
SetThemeAction,
UpdateThemeAction,
} from '../actions/theme';
import { ActionType } from '../action-types'; import { ActionType } from '../action-types';
import { Theme, ApiResponse, ThemeColors } from '../../interfaces'; import { Theme } from '../../interfaces/Theme';
import { applyAuth, parseThemeToPAB } from '../../utility'; import { themes } from '../../components/Themer/themes.json';
import axios, { AxiosError } from 'axios';
export const setTheme = export const setTheme =
(colors: ThemeColors, remeberTheme: boolean = true) => (name: string) => (dispatch: Dispatch<SetThemeAction>) => {
(dispatch: Dispatch<SetThemeAction>) => { const theme = themes.find((theme) => theme.name === name);
if (remeberTheme) {
localStorage.setItem('theme', parseThemeToPAB(colors));
}
for (const [key, value] of Object.entries(colors)) { if (theme) {
document.body.style.setProperty(`--color-${key}`, value); localStorage.setItem('theme', name);
} loadTheme(theme);
dispatch({
type: ActionType.setTheme,
payload: colors,
});
};
export const fetchThemes =
() => async (dispatch: Dispatch<FetchThemesAction>) => {
try {
const res = await axios.get<ApiResponse<Theme[]>>('/api/themes');
dispatch({ dispatch({
type: ActionType.fetchThemes, type: ActionType.setTheme,
payload: res.data.data, payload: theme,
});
} catch (err) {
console.log(err);
}
};
export const addTheme =
(theme: Theme) => async (dispatch: Dispatch<AddThemeAction>) => {
try {
const res = await axios.post<ApiResponse<Theme>>('/api/themes', theme, {
headers: applyAuth(),
});
dispatch({
type: ActionType.addTheme,
payload: res.data.data,
});
dispatch<any>({
type: ActionType.createNotification,
payload: {
title: 'Success',
message: 'Theme added',
},
});
} catch (err) {
const error = err as AxiosError<{ error: string }>;
dispatch<any>({
type: ActionType.createNotification,
payload: {
title: 'Error',
message: error.response?.data.error,
},
}); });
} }
}; };
export const deleteTheme = export const loadTheme = (theme: Theme): void => {
(name: string) => async (dispatch: Dispatch<DeleteThemeAction>) => { for (const [key, value] of Object.entries(theme.colors)) {
try { document.body.style.setProperty(`--color-${key}`, value);
const res = await axios.delete<ApiResponse<Theme[]>>( }
`/api/themes/${name}`, };
{ headers: applyAuth() }
);
dispatch({
type: ActionType.deleteTheme,
payload: res.data.data,
});
dispatch<any>({
type: ActionType.createNotification,
payload: {
title: 'Success',
message: 'Theme deleted',
},
});
} catch (err) {
console.log(err);
}
};
export const editTheme =
(theme: Theme | null) => (dispatch: Dispatch<EditThemeAction>) => {
dispatch({
type: ActionType.editTheme,
payload: theme,
});
};
export const updateTheme =
(theme: Theme, originalName: string) =>
async (dispatch: Dispatch<UpdateThemeAction>) => {
try {
const res = await axios.put<ApiResponse<Theme[]>>(
`/api/themes/${originalName}`,
theme,
{ headers: applyAuth() }
);
dispatch({
type: ActionType.updateTheme,
payload: res.data.data,
});
} catch (err) {
console.log(err);
}
};

View file

@ -1,11 +1,6 @@
export enum ActionType { export enum ActionType {
// THEME // THEME
setTheme = 'SET_THEME', setTheme = 'SET_THEME',
fetchThemes = 'FETCH_THEMES',
addTheme = 'ADD_THEME',
deleteTheme = 'DELETE_THEME',
updateTheme = 'UPDATE_THEME',
editTheme = 'EDIT_THEME',
// CONFIG // CONFIG
getConfig = 'GET_CONFIG', getConfig = 'GET_CONFIG',
updateConfig = 'UPDATE_CONFIG', updateConfig = 'UPDATE_CONFIG',
@ -28,7 +23,6 @@ export enum ActionType {
updateApp = 'UPDATE_APP', updateApp = 'UPDATE_APP',
reorderApps = 'REORDER_APPS', reorderApps = 'REORDER_APPS',
sortApps = 'SORT_APPS', sortApps = 'SORT_APPS',
setEditApp = 'SET_EDIT_APP',
// CATEGORES // CATEGORES
getCategories = 'GET_CATEGORIES', getCategories = 'GET_CATEGORIES',
getCategoriesSuccess = 'GET_CATEGORIES_SUCCESS', getCategoriesSuccess = 'GET_CATEGORIES_SUCCESS',
@ -39,14 +33,10 @@ export enum ActionType {
updateCategory = 'UPDATE_CATEGORY', updateCategory = 'UPDATE_CATEGORY',
sortCategories = 'SORT_CATEGORIES', sortCategories = 'SORT_CATEGORIES',
reorderCategories = 'REORDER_CATEGORIES', reorderCategories = 'REORDER_CATEGORIES',
setEditCategory = 'SET_EDIT_CATEGORY',
// BOOKMARKS // BOOKMARKS
addBookmark = 'ADD_BOOKMARK', addBookmark = 'ADD_BOOKMARK',
deleteBookmark = 'DELETE_BOOKMARK', deleteBookmark = 'DELETE_BOOKMARK',
updateBookmark = 'UPDATE_BOOKMARK', updateBookmark = 'UPDATE_BOOKMARK',
setEditBookmark = 'SET_EDIT_BOOKMARK',
reorderBookmarks = 'REORDER_BOOKMARKS',
sortBookmarks = 'SORT_BOOKMARKS',
// AUTH // AUTH
login = 'LOGIN', login = 'LOGIN',
logout = 'LOGOUT', logout = 'LOGOUT',

View file

@ -36,8 +36,3 @@ export interface SortAppsAction {
type: ActionType.sortApps; type: ActionType.sortApps;
payload: string; payload: string;
} }
export interface SetEditAppAction {
type: ActionType.setEditApp;
payload: App | null;
}

View file

@ -56,29 +56,3 @@ export interface ReorderCategoriesAction {
type: ActionType.reorderCategories; type: ActionType.reorderCategories;
payload: Category[]; payload: Category[];
} }
export interface SetEditCategoryAction {
type: ActionType.setEditCategory;
payload: Category | null;
}
export interface SetEditBookmarkAction {
type: ActionType.setEditBookmark;
payload: Bookmark | null;
}
export interface ReorderBookmarksAction {
type: ActionType.reorderBookmarks;
payload: {
bookmarks: Bookmark[];
categoryId: number;
};
}
export interface SortBookmarksAction {
type: ActionType.sortBookmarks;
payload: {
orderType: string;
categoryId: number;
};
}

View file

@ -1,13 +1,6 @@
import { App } from '../../interfaces'; import { App } from '../../interfaces';
import { import { SetThemeAction } from './theme';
AddThemeAction,
DeleteThemeAction,
EditThemeAction,
FetchThemesAction,
SetThemeAction,
UpdateThemeAction,
} from './theme';
import { import {
AddQueryAction, AddQueryAction,
@ -31,7 +24,6 @@ import {
UpdateAppAction, UpdateAppAction,
ReorderAppsAction, ReorderAppsAction,
SortAppsAction, SortAppsAction,
SetEditAppAction,
} from './app'; } from './app';
import { import {
@ -45,10 +37,6 @@ import {
AddBookmarkAction, AddBookmarkAction,
DeleteBookmarkAction, DeleteBookmarkAction,
UpdateBookmarkAction, UpdateBookmarkAction,
SetEditCategoryAction,
SetEditBookmarkAction,
ReorderBookmarksAction,
SortBookmarksAction,
} from './bookmark'; } from './bookmark';
import { import {
@ -61,11 +49,6 @@ import {
export type Action = export type Action =
// Theme // Theme
| SetThemeAction | SetThemeAction
| FetchThemesAction
| AddThemeAction
| DeleteThemeAction
| UpdateThemeAction
| EditThemeAction
// Config // Config
| GetConfigAction | GetConfigAction
| UpdateConfigAction | UpdateConfigAction
@ -84,7 +67,6 @@ export type Action =
| UpdateAppAction | UpdateAppAction
| ReorderAppsAction | ReorderAppsAction
| SortAppsAction | SortAppsAction
| SetEditAppAction
// Categories // Categories
| GetCategoriesAction<any> | GetCategoriesAction<any>
| AddCategoryAction | AddCategoryAction
@ -93,14 +75,10 @@ export type Action =
| UpdateCategoryAction | UpdateCategoryAction
| SortCategoriesAction | SortCategoriesAction
| ReorderCategoriesAction | ReorderCategoriesAction
| SetEditCategoryAction
// Bookmarks // Bookmarks
| AddBookmarkAction | AddBookmarkAction
| DeleteBookmarkAction | DeleteBookmarkAction
| UpdateBookmarkAction | UpdateBookmarkAction
| SetEditBookmarkAction
| ReorderBookmarksAction
| SortBookmarksAction
// Auth // Auth
| LoginAction | LoginAction
| LogoutAction | LogoutAction

View file

@ -1,32 +1,7 @@
import { ActionType } from '../action-types'; import { ActionType } from '../action-types';
import { Theme, ThemeColors } from '../../interfaces'; import { Theme } from '../../interfaces';
export interface SetThemeAction { export interface SetThemeAction {
type: ActionType.setTheme; type: ActionType.setTheme;
payload: ThemeColors;
}
export interface FetchThemesAction {
type: ActionType.fetchThemes;
payload: Theme[];
}
export interface AddThemeAction {
type: ActionType.addTheme;
payload: Theme; payload: Theme;
} }
export interface DeleteThemeAction {
type: ActionType.deleteTheme;
payload: Theme[];
}
export interface UpdateThemeAction {
type: ActionType.updateTheme;
payload: Theme[];
}
export interface EditThemeAction {
type: ActionType.editTheme;
payload: Theme | null;
}

View file

@ -7,14 +7,12 @@ interface AppsState {
loading: boolean; loading: boolean;
apps: App[]; apps: App[];
errors: string | undefined; errors: string | undefined;
appInUpdate: App | null;
} }
const initialState: AppsState = { const initialState: AppsState = {
loading: true, loading: true,
apps: [], apps: [],
errors: undefined, errors: undefined,
appInUpdate: null,
}; };
export const appsReducer = ( export const appsReducer = (
@ -22,86 +20,71 @@ export const appsReducer = (
action: Action action: Action
): AppsState => { ): AppsState => {
switch (action.type) { switch (action.type) {
case ActionType.getApps: { case ActionType.getApps:
return { return {
...state, ...state,
loading: true, loading: true,
errors: undefined, errors: undefined,
}; };
}
case ActionType.getAppsSuccess: { case ActionType.getAppsSuccess:
return { return {
...state, ...state,
loading: false, loading: false,
apps: action.payload || [], apps: action.payload || [],
}; };
}
case ActionType.pinApp: { case ActionType.pinApp:
const appIdx = state.apps.findIndex( const pinnedAppIdx = state.apps.findIndex(
(app) => app.id === action.payload.id (app) => app.id === action.payload.id
); );
return { return {
...state, ...state,
apps: [ apps: [
...state.apps.slice(0, appIdx), ...state.apps.slice(0, pinnedAppIdx),
action.payload, action.payload,
...state.apps.slice(appIdx + 1), ...state.apps.slice(pinnedAppIdx + 1),
], ],
}; };
}
case ActionType.addAppSuccess: { case ActionType.addAppSuccess:
return { return {
...state, ...state,
apps: [...state.apps, action.payload], apps: [...state.apps, action.payload],
}; };
}
case ActionType.deleteApp: { case ActionType.deleteApp:
return { return {
...state, ...state,
apps: [...state.apps].filter((app) => app.id !== action.payload), apps: [...state.apps].filter((app) => app.id !== action.payload),
}; };
}
case ActionType.updateApp: { case ActionType.updateApp:
const appIdx = state.apps.findIndex( const updatedAppIdx = state.apps.findIndex(
(app) => app.id === action.payload.id (app) => app.id === action.payload.id
); );
return { return {
...state, ...state,
apps: [ apps: [
...state.apps.slice(0, appIdx), ...state.apps.slice(0, updatedAppIdx),
action.payload, action.payload,
...state.apps.slice(appIdx + 1), ...state.apps.slice(updatedAppIdx + 1),
], ],
}; };
}
case ActionType.reorderApps: { case ActionType.reorderApps:
return { return {
...state, ...state,
apps: action.payload, apps: action.payload,
}; };
}
case ActionType.sortApps: { case ActionType.sortApps:
return { return {
...state, ...state,
apps: sortData<App>(state.apps, action.payload), apps: sortData<App>(state.apps, action.payload),
}; };
}
case ActionType.setEditApp: {
return {
...state,
appInUpdate: action.payload,
};
}
default: default:
return state; return state;

Some files were not shown because too many files have changed in this diff Show more