bump version

This commit is contained in:
srgooglo 2022-09-30 15:56:08 +02:00
parent 42c9b1b6bf
commit 1e7ef46c91
86 changed files with 7432 additions and 5 deletions

View File

@ -1,3 +1,3 @@
{ {
"version": "0.20.1" "version": "0.20.2"
} }

View File

@ -16,5 +16,5 @@
"7zip-min": "1.4.3", "7zip-min": "1.4.3",
"axios": "0.21.1" "axios": "0.21.1"
}, },
"version": "0.20.1" "version": "0.20.2"
} }

View File

@ -0,0 +1,66 @@
const path = require("path")
const { builtinModules } = require("module")
const aliases = {
"~": __dirname,
"~/": `${path.resolve(__dirname, "src")}/`,
"@src": path.join(__dirname, "src"),
cores: path.join(__dirname, "src/cores"),
schemas: path.join(__dirname, "constants"),
config: path.join(__dirname, "config"),
extensions: path.resolve(__dirname, "src/extensions"),
pages: path.join(__dirname, "src/pages"),
theme: path.join(__dirname, "src/theme"),
components: path.join(__dirname, "src/components"),
models: path.join(__dirname, "src/models"),
utils: path.join(__dirname, "src/utils"),
layouts: path.join(__dirname, "src/layouts"),
}
module.exports = (config = {}) => {
if (!config.resolve) {
config.resolve = {}
}
if (!config.server) {
config.server = {}
}
config.resolve.alias = aliases
config.server.port = process.env.listenPort ?? 8000
config.server.host = "0.0.0.0"
config.server.fs = {
allow: [".."]
}
config.envDir = path.join(__dirname, "environments")
config.css = {
preprocessorOptions: {
less: {
javascriptEnabled: true,
}
}
}
// config.build = {
// sourcemap: "inline",
// target: `node16`,
// outDir: "dist",
// assetsDir: ".",
// minify: process.env.MODE !== "development",
// rollupOptions: {
// external: [
// "electron",
// "electron-devtools-installer",
// ...builtinModules.flatMap(p => [p, `node:16`]),
// ],
// output: {
// entryFileNames: "[name].js",
// },
// },
// emptyOutDir: true,
// brotliSize: false,
// }
return config
}

View File

@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.ico" />
<meta name="viewport" content="viewport-fit=cover, width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/App.jsx"></script>
</body>
</html>

View File

@ -0,0 +1,68 @@
{
"name": "@comty/console",
"version": "0.20.2",
"license": "MIT",
"scripts": {
"build": "vite build",
"dev": "vite"
},
"peerDependencies": {
"react": "^16.8.6"
},
"dependencies": {
"@ant-design/icons": "4.7.0",
"@corenode/utils": "0.28.26",
"@foxify/events": "2.0.1",
"@loadable/component": "5.15.2",
"@vitejs/plugin-react": "^2.1.0",
"antd": "4.23.2",
"chart.js": "3.7.0",
"classnames": "2.3.1",
"evite": "0.12.3",
"feather-reactjs": "2.0.13",
"fuse.js": "6.5.3",
"global": "4.4.0",
"history": "5.2.0",
"js-cookie": "3.0.1",
"jwt-decode": "3.1.2",
"less": "4.1.2",
"linebridge": "0.13.0",
"moment": "2.29.1",
"nprogress": "^0.2.0",
"rc-animate": "^3.1.1",
"rc-util": "^5.19.3",
"rc-virtual-list": "^3.4.4",
"react-beautiful-dnd": "13.1.0",
"react-chartjs-2": "4.0.1",
"react-color": "2.19.3",
"react-contexify": "5.0.0",
"react-draggable": "4.4.4",
"react-helmet": "6.1.0",
"react-i18next": "11.15.3",
"react-icons": "4.3.1",
"react-intersection-observer": "8.33.1",
"react-json-view": "1.21.3",
"react-lazy-load-image-component": "^1.5.4",
"react-loadable": "^5.5.0",
"react-motion": "0.5.2",
"react-reveal": "1.2.2",
"react-rnd": "10.3.5",
"rxjs": "^7.5.5",
"store": "^2.0.12"
},
"devDependencies": {
"@types/jest": "^26.0.24",
"@types/node": "^16.4.10",
"@types/react": "^17.0.15",
"@types/react-dom": "^17.0.9",
"@types/react-router-config": "^5.0.3",
"@types/react-router-dom": "^5.1.8",
"@typescript-eslint/eslint-plugin": "^4.29.0",
"concurrently": "^7.4.0",
"corenode": "0.28.26",
"cors": "2.8.5",
"cross-env": "^7.0.3",
"express": "^4.17.1",
"vite": "3.1.4"
}
}

View File

@ -0,0 +1,366 @@
// Patch global prototypes
Array.prototype.findAndUpdateObject = function (discriminator, obj) {
let index = this.findIndex(item => item[discriminator] === obj[discriminator])
if (index !== -1) {
this[index] = obj
}
return index
}
Array.prototype.move = function (from, to) {
this.splice(to, 0, this.splice(from, 1)[0])
return this
}
String.prototype.toTitleCase = function () {
return this.replace(/\w\S*/g, function (txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase()
})
}
Promise.tasked = function (promises) {
return new Promise(async (resolve, reject) => {
let rejected = false
for await (let promise of promises) {
if (rejected) {
return
}
try {
await promise()
} catch (error) {
rejected = true
return reject(error)
}
}
if (!rejected) {
return resolve()
}
})
}
import React from "react"
import { EviteRuntime } from "evite"
import { Helmet } from "react-helmet"
import * as antd from "antd"
import { Translation } from "react-i18next"
import config from "config"
import { Session, User } from "models"
import { NotFound, RenderError, Crash, Login } from "components"
import { Icons } from "components/Icons"
import Layout from "./layout"
import * as Router from "./router"
import "theme/index.less"
class App extends React.Component {
sessionController = new Session()
userController = new User()
state = {
session: null,
user: null,
}
static async initialize() {
window.app.version = config.package.version
}
static publicEvents = {
"clearAllOverlays": function () {
window.app.DrawerController.closeAll()
},
}
eventsHandlers = {
"app.close": () => {
if (window.isElectron) {
window.electron.ipcRenderer.invoke("app.close")
}
},
"app.minimize": () => {
if (window.isElectron) {
window.electron.ipcRenderer.invoke("app.minimize")
}
},
"app.openCreator": (...args) => {
return App.publicMethods.openCreator(...args)
},
"app.createLogin": async () => {
app.DrawerController.open("login", Login, {
componentProps: {
sessionController: this.sessionController
}
})
},
"session.logout": async () => {
await this.sessionController.logout()
},
"session.created": async () => {
await this.flushState()
await this.initialization()
// if is `/login` move to `/`
if (window.location.pathname === "/login") {
app.setLocation("/")
}
},
"session.destroyed": async () => {
await this.flushState()
app.eventBus.emit("app.forceToLogin")
},
"session.regenerated": async () => {
//await this.flushState()
//await this.initialization()
},
"session.invalid": async (error) => {
const token = await Session.token
if (!this.state.session && !token) {
return false
}
await this.sessionController.forgetLocalSession()
await this.flushState()
app.eventBus.emit("app.forceToLogin")
antd.notification.open({
message: <Translation>
{(t) => t("Invalid Session")}
</Translation>,
description: <Translation>
{(t) => t(error)}
</Translation>,
icon: <Icons.MdOutlineAccessTimeFilled />,
})
},
"app.forceToLogin": () => {
window.app.setLocation("/login")
},
"websocket_connected": () => {
if (this.wsReconnecting) {
this.wsReconnectingTry = 0
this.wsReconnecting = false
this.initialization()
setTimeout(() => {
console.log("WS Reconnected")
}, 500)
}
},
"websocket_connection_error": () => {
if (!this.wsReconnecting) {
this.latencyWarning = null
this.wsReconnectingTry = 0
this.wsReconnecting = true
console.log("WS Reconnecting")
}
this.wsReconnectingTry = this.wsReconnectingTry + 1
if (this.wsReconnectingTry > 3 && app.settings.get("app.reloadOnWSConnectionError")) {
window.location.reload()
}
},
"websocket_latency_too_high": () => {
if (!this.latencyWarning) {
this.latencyWarning = true
antd.notification.open({
message: <Translation>
{(t) => t("Latency Warning")}
</Translation>,
description: <Translation>
{(t) => t("The latency between your computer and the server is too high. This may cause some issues. Please check your internet connection.")}
</Translation>,
icon: <Icons.MdOutlineAccessTimeFilled />,
})
}
},
"websocket_latency_normal": () => {
if (this.latencyWarning) {
this.latencyWarning = null
antd.notification.close("latency-warning")
}
},
}
static staticRenders = {
PageLoad: () => {
return <antd.Skeleton active />
},
NotFound: (props) => {
return <NotFound />
},
RenderError: (props) => {
return <RenderError {...props} />
},
Crash: Crash.CrashWrapper,
Initialization: () => {
return <div className="app_splash_wrapper">
<div className="splash_logo">
<img src={config.logo.alt} />
</div>
<div className="splash_label">
<Icons.LoadingOutlined />
</div>
</div>
}
}
static publicMethods = {
}
constructor(props) {
super(props)
Object.keys(this.eventsHandlers).forEach((event) => {
app.eventBus.on(event, this.eventsHandlers[event])
})
}
flushState = async () => {
await this.setState({ session: null, user: null })
}
componentDidMount = async () => {
app.eventBus.emit("app.initialization.start")
await this.initialization()
app.eventBus.emit("app.initialization.finish")
}
initialization = async () => {
console.debug(`[App] Initializing app`)
const initializationTasks = [
async () => {
try {
// get remotes origins from config
const defaultRemotes = config.remotes
// get storaged remotes origins
const storedRemotes = await app.settings.get("remotes") ?? {}
// mount main api bridge
await this.props.cores.ApiCore.connectBridge("main", {
origin: storedRemotes.mainApi ?? defaultRemotes.mainApi,
locked: true,
})
await this.props.cores.ApiCore.namespaces["main"].initialize()
app.eventBus.emit("app.initialization.api_success")
} catch (error) {
app.eventBus.emit("app.initialization.api_error", error)
console.error(`[App] Error while initializing api`, error)
throw {
cause: "Cannot connect to API",
details: `Sorry but we cannot connect to the API. Please try again later. [${config.remotes.mainApi}]`,
}
}
},
async () => {
try {
await this.__SessionInit()
app.eventBus.emit("app.initialization.session_success")
} catch (error) {
app.eventBus.emit("app.initialization.session_error", error)
throw {
cause: "Cannot initialize session",
details: error.message,
}
}
},
async () => {
try {
await this.__UserInit()
app.eventBus.emit("app.initialization.user_success")
} catch (error) {
app.eventBus.emit("app.initialization.user_error", error)
throw {
cause: "Cannot initialize user data",
details: error.message,
}
}
},
]
await Promise.tasked(initializationTasks).catch((reason) => {
console.error(`[App] Initialization failed: ${reason.cause}`)
app.eventBus.emit("runtime.crash", {
message: `App initialization failed (${reason.cause})`,
details: reason.details,
})
})
}
__SessionInit = async () => {
const token = await Session.token
if (!token || token == null) {
app.eventBus.emit("app.forceToLogin")
return false
}
const session = await this.sessionController.getCurrentSession().catch((error) => {
console.error(`[App] Cannot get current session: ${error.message}`)
return false
})
await this.setState({ session })
}
__UserInit = async () => {
if (!this.state.session) {
return false
}
const user = await User.data()
await this.setState({ user })
}
render() {
return <React.Fragment>
<Helmet>
<title>{config.app.siteName}</title>
</Helmet>
<Router.InternalRouter>
<Layout
user={this.state.user}
staticRenders={App.staticRenders}
bindProps={{
staticRenders: App.staticRenders,
user: this.state.user,
session: this.state.session,
sessionController: this.sessionController,
userController: this.userController,
}}
>
<Router.PageRender />
</Layout>
</Router.InternalRouter>
</React.Fragment>
}
}
export default new EviteRuntime(App)

View File

@ -0,0 +1,27 @@
import React from "react"
import classnames from "classnames"
import "./index.less"
export default (props) => {
const { children } = props
return <div
style={{
...props.style,
padding: props.padding,
}}
className={classnames(
"actionsBar",
[props.mode],
{["transparent"]: props.type === "transparent"},
{["spaced"]: props.spaced},
)}
>
<div
style={props.wrapperStyle}
className="wrapper"
>
{children}
</div>
</div>
}

View File

@ -0,0 +1,100 @@
@actionsBar_height: fit-content;
.actionsBar {
--ignore-dragger: true;
display: inline-block;
white-space: nowrap;
overflow-x: overlay;
padding: 15px;
width: 100%;
height: @actionsBar_height;
border: 1px solid #e0e0e0;
border-radius: 8px;
background-color: #0c0c0c15;
backdrop-filter: blur(10px);
--webkit-backdrop-filter: blur(10px);
transition: all 200ms ease-in-out;
::-webkit-scrollbar {
position: absolute;
display: none;
width: 0;
height: 0;
z-index: 0;
}
.wrapper {
display: flex;
flex-direction: row;
align-items: center;
height: 100%;
transition: all 200ms ease-in-out;
> div {
margin: 0 5px;
display: flex;
flex-direction: column;
align-items: flex-start;
justify-content: center;
--ignore-dragger: true;
span {
height: fit-content;
}
}
}
&.float {
z-index: 1000;
position: sticky;
bottom: 0;
top: 0;
right: 0;
width: 100%;
}
&.fixedBottom {
z-index: 1000;
position: fixed;
bottom: 0;
right: 0;
left: 0;
width: 100%;
margin-bottom: 10px;
}
&.fixedTop {
z-index: 1000;
position: fixed;
top: 0;
right: 0;
left: 0;
width: 100%;
margin-bottom: 10px;
}
&.transparent {
background-color: transparent;
border: none;
backdrop-filter: none;
--webkit-backdrop-filter: none;
}
&.spaced {
.wrapper {
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
}
}
}

View File

@ -0,0 +1,38 @@
import React from "react"
import { Result, Button } from "antd"
import "./index.less"
export const CrashComponent = (props) => {
const {
crash = {
details: "Unknown error",
}
} = props
return <Result
status="error"
title="Well, we're sorry! The application has a fatal crash."
subTitle={crash.message}
extra={[
<Button type="primary" key="reload" onClick={() => window.location.reload()}>
Reload app
</Button>
]}
>
{crash.details &&
<div>
<code>{crash.details}</code>
</div>}
</Result>
}
export const CrashWrapper = (props) => {
const { crash } = props
return <div className="crashWrapper">
<CrashComponent crash={crash} />
</div>
}
export default CrashComponent

View File

@ -0,0 +1,62 @@
.crashWrapper {
position: absolute;
width: 100vw;
height: 100vh;
top: 0;
left: 0;
z-index: 10000;
background: rgba(0, 0, 0, 0.7);
backdrop-filter: blur(10px);
color: #fff;
.ant-result,
.ant-result-title,
.ant-result-subtitle,
.ant-result-extra {
color: #fff;
}
.ant-result-content {
background-color: rgba(0, 0, 0, 0.7) !important;
}
code {
user-select: text;
color: #fff;
font-family: "DM Mono", monospace;
}
h1,
h2,
h3,
h4,
h5,
h6,
p,
span,
pre {
color: #fff;
}
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
animation: opacity-fade-in 0.3s ease-in-out;
}
@keyframes opacity-fade-in {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}

View File

@ -0,0 +1,23 @@
import React from "react"
import { Button } from "antd"
import classnames from "classnames"
import "./index.less"
export default (props) => {
return <div className="followButton">
<div className="counter">
{props.count}
</div>
<Button
type="ghost"
onClick={props.onClick}
className={classnames(
"btn",
{ ["followed"]: props.followed }
)}
>
<span>{props.followed ? "Following" : "Follow"}</span>
</Button>
</div>
}

View File

@ -0,0 +1,82 @@
@borderRadius: 8px;
.followButton {
display: inline-flex;
flex-direction: row;
align-items: center;
transition: all 150ms ease-in-out;
outline: 1px solid var(--border-color);
border-radius: @borderRadius;
.counter {
padding: 5px 15px;
}
.btn {
cursor: pointer;
width: 100px;
padding: 5px 15px;
transition: all 150ms ease-in-out;
border-radius: @borderRadius;
border-left: 1.5px solid var(--border-color);
border-top: 0;
border-right: 0;
border-bottom: 0;
text-align: center;
letter-spacing: 1px;
span {
user-select: none !important;
transition: all 150ms ease-in-out;
color: white !important;
}
opacity: 0.9;
background : linear-gradient(120deg, #6559ae, #ff7159, #6559ae);
background-size : 400% 400%;
background-position: 14% 0%;
&:hover {
opacity: 1;
animation: gradientMove 2s forwards ease-in-out infinite;
background: linear-gradient(120deg, #6559ae, #ff7159, #6559ae);
background-size: 400% 400%;
background-position: 14% 0%;
}
// make an click animation transforming size
&:active {
transform: scale(0.95);
}
&.followed {
background: none;
span {
color: #7e7e7e !important;
}
}
}
}
@keyframes gradientMove {
0% {
background-position: 14% 0%;
}
50% {
background-position: 87% 100%;
}
100% {
background-position: 14% 0%;
}
}

View File

@ -0,0 +1,43 @@
import React from "react"
import * as antd from "antd"
import { Icons } from "components/Icons"
import "./index.less"
export default (props) => {
if (props.followers.length === 0) {
return <antd.Result
icon={<Icons.UserX style={{ fontSize: "50px" }} />}
>
<h2>
It's seems this user has no followers, yet.
</h2>
<h3>
Maybe you can help them out?
</h3>
</antd.Result>
}
return <div className="followersList">
{props.followers.map((follower) => {
return <div className="follower">
<div className="avatar">
<antd.Avatar shape="square" src={follower.avatar} />
</div>
<div className="names">
<div>
<h2>
{follower.fullName ?? follower.username}
</h2>
</div>
<div>
<span>
@{follower.username}
</span>
</div>
</div>
</div>
})}
</div>
}

View File

@ -0,0 +1,65 @@
@borderRadius: 12px;
.ant-result {
display : flex;
flex-direction: column;
align-items : center;
}
.ant-result-icon {
background-color: var(--background-color-accent);
border-radius : @borderRadius;
width : fit-content;
padding : 20px;
svg {
margin: 0;
color : var(--background-color-contrast);
}
}
.ant-result-content {
background-color: var(--background-color-accent);
border-radius : @borderRadius;
h2 {
color: var(--background-color-contrast);
}
h3 {
color : var(--background-color-contrast);
font-weight: 100;
}
}
.followersList {
.follower {
width : 100%;
//max-width: 50vw;
padding : 10px;
display : inline-flex;
align-items : center;
border-radius: 8px;
border : 1px solid var(--border-color);
h2 {
margin: 0;
font-size: 22px;
line-height: 26px;
}
>div {
margin-right: 10px;
}
.names {
}
}
>div {
margin-bottom: 20px;
}
}

View File

@ -0,0 +1,29 @@
import React from "react"
import config from "config"
import "./index.less"
export default (props) => {
const renderLinks = () => {
return config.footerLinks.map((link, index) => {
let linkProps = {
key: index,
}
if (link.url) {
linkProps.href = link.url
}
if (link.location) {
linkProps.onClick = () => {
app.setLocation(link.location)
}
}
return <>| <a {...linkProps}>{link.label}</a> {index === config.footerLinks.length - 1 ? "|" : ""} </>
})
}
return <div className="footer">
{config.app.copyright} {config.footerLinks ? renderLinks() : null}
</div>
}

View File

@ -0,0 +1,9 @@
.footer {
position: fixed;
bottom: 0;
padding: 10px;
font-family: "DM Mono", monospace;
font-size: 12px;
font-weight: 200;
}

View File

@ -0,0 +1,400 @@
import React from "react"
import { Icons } from "components/Icons"
import {
Form,
Input,
Button,
Checkbox,
Select,
Dropdown,
Slider,
InputNumber,
DatePicker,
AutoComplete,
Divider,
Switch,
} from "antd"
import HeadShake from "react-reveal/HeadShake"
import "./index.less"
const allComponents = {
Input,
Button,
Checkbox,
Select,
Dropdown,
Slider,
InputNumber,
DatePicker,
AutoComplete,
Divider,
Switch,
}
export default class FormGenerator extends React.Component {
ref = React.createRef()
fieldsReferences = {}
unsetValues = {}
discardedValues = []
state = {
validating: false,
shakeItem: false,
failed: {},
}
ctx = {
clearErrors: () => {
this.setState({ failed: {} })
},
clearForm: () => {
this.ctx.clearErrors()
this.ctx.toogleValidation(false)
this.ref.current.resetFields()
},
finish: () => this.ref.current.submit(),
error: (id, error) => {
this.handleFormError(id, error)
},
shake: (id) => {
this.formItemShake(id)
},
toogleValidation: (to) => {
if (typeof to !== "undefined") {
return this.setState({ validating: to })
}
this.setState({ validating: !this.state.validating })
return this.state.validating
},
formRef: this.ref,
}
handleFinish(payload) {
if (typeof this.props.onFinish !== "function") {
console.error(`onFinish is not an function`)
return false
}
// try to read unset values
Object.keys(this.fieldsReferences).forEach((key) => {
const ref = this.fieldsReferences[key].current
if (typeof ref.state !== "undefined") {
this.unsetValues[key] = ref.state?.value || ref.state?.checked
}
})
// filter discarded values
try {
const keys = Object.keys(payload)
this.discardedValues.forEach((id) => {
if (keys.includes(id)) {
delete payload[id]
}
})
} catch (error) {
// terrible
}
// fulfil unset values
payload = { ...payload, ...this.unsetValues }
return this.props.onFinish(payload, this.ctx)
}
formItemShake(id) {
this.setState({ shakeItem: id })
setTimeout(() => {
this.setState({ shakeItem: false })
}, 50)
}
handleFormError(item, error) {
let fails = this.state.failed
fails[item] = error ?? true
this.setState({ failed: fails })
this.formItemShake(item)
}
handleFailChange(event) {
const itemID = event.target.id
if (itemID) {
let fails = this.state.failed
if (fails["all"]) {
fails["all"] = false
this.setState({ failed: fails })
}
if (fails[itemID]) {
// try deactivate failed statement
fails[itemID] = false
this.setState({ failed: fails })
}
}
}
shouldShakeItem(id) {
try {
const mutation = false
if (this.state.shakeItem === "all") {
return mutation
}
if (this.state.shakeItem == id) {
return mutation
}
} catch (error) {
// not returning
}
}
discardValueFromId = (id) => {
let ids = []
if (Array.isArray(id)) {
ids = id
} else {
ids.push(id)
}
ids.forEach((_id) => {
const value = this.discardedValues ?? []
value.push(_id)
this.discardedValues = value
})
}
renderValidationIcon() {
if (this.props.renderLoadingIcon && this.state.validating) {
return <Icons.LoadingOutlined spin style={{ margin: 0 }} />
}
return null
}
renderElementPrefix = (element) => {
if (element.icon) {
let renderIcon = null
const iconType = typeof element.icon
switch (iconType) {
case "string": {
if (typeof Icons[element.icon] !== "undefined") {
renderIcon = React.createElement(Icons[element.icon])
} else {
console.warn("provided icon is not available on icons libs")
}
break
}
case "object": {
renderIcon = element.icon
break
}
default: {
console.warn(`cannot mutate icon cause type (${iconType}) is not handled`)
break
}
}
if (renderIcon) {
// try to generate icon with props
return React.cloneElement(renderIcon, element.iconProps ? { ...element.iconProps } : null)
}
} else {
return element.prefix ?? null
}
}
renderItems(elements) {
if (Array.isArray(elements)) {
try {
return elements.map((field) => {
let { item, element } = field
// if item has no id, return an uncontrolled field
if (typeof field.id === "undefined") {
return React.createElement(allComponents[element.component], element.props)
}
// fulfill
if (typeof item === "undefined") {
item = {}
}
if (typeof element === "undefined") {
element = {}
}
// check if component is available on library
if (typeof allComponents[element.component] === "undefined") {
console.warn(`[${element.component}] is not an valid component`)
return null
}
// handle groups
if (typeof field.group !== "undefined") {
return (
<div style={{ display: "flex" }} key={field.id}>
{this.renderItems(field.group)}
</div>
)
}
//* RENDER
const failStatement = this.state.failed["all"] ?? this.state.failed[field.id]
const rules = item.rules
const hasFeedback = item.hasFeedback ?? false
let elementProps = {
disabled: this.state.validating,
...element.props,
}
let itemProps = {
...item.props,
}
switch (element.component) {
case "Checkbox": {
elementProps.onChange = (e) => {
this.unsetValues[field.id] = e.target.checked
elementProps.checked = e.target.checked
elementProps.value = e.target.checked
}
break
}
case "Button": {
this.discardValueFromId(field.id)
if (field.withValidation) {
elementProps.icon = this.state.validating ? (
<Icons.LoadingOutlined spin style={{ marginRight: "7px" }} />
) : null
}
break
}
case "Input": {
itemProps = {
...itemProps,
hasFeedback,
rules,
onChange: (e) => this.handleFailChange(e),
help: failStatement ? failStatement : null,
validateStatus: failStatement ? "error" : null,
}
elementProps = {
...elementProps,
id: field.id,
prefix: this.renderElementPrefix(element) ?? null,
placeholder: element.placeholder,
}
break
}
case "Select": {
if (typeof element.renderItem !== "undefined") {
elementProps.children = element.renderItem
}
if (typeof element.options !== "undefined" && !element.renderItem) {
if (!Array.isArray(element.options)) {
console.warn(
`Invalid options data type, expecting Array > received ${typeof element.options}`,
)
return null
}
elementProps.children = element.options.map((option) => {
return (
<Select.Option key={option.id ?? Math.random} value={option.value ?? option.id}>
{option.name ?? null}
</Select.Option>
)
})
}
itemProps = {
...itemProps,
hasFeedback,
rules,
validateStatus: failStatement ? "error" : null,
help: failStatement ? failStatement : null,
}
break
}
default: {
itemProps = {
...itemProps,
hasFeedback,
rules,
validateStatus: failStatement ? "error" : null,
help: failStatement ? failStatement : null,
}
break
}
}
// set reference
this.fieldsReferences[field.id] = elementProps.ref = React.createRef()
// return field
return (
<div className={field.className} style={field.style} key={field.id}>
{field.title ?? null}
<HeadShake spy={this.shouldShakeItem(field.id)}>
<Form.Item label={field.label} name={field.id} key={field.id} {...itemProps}>
{React.createElement(allComponents[element.component], elementProps)}
</Form.Item>
</HeadShake>
</div>
)
})
} catch (error) {
console.log(error)
return null
}
}
}
componentDidMount() {
if (!this.props.items) {
console.warn(`items not provided, nothing to render`)
return null
}
// handle discardedValues
if (Array.isArray(this.props.items)) {
this.props.items.forEach((item) => {
if (item.ignoreValue) {
this.discardValueFromId(item.id)
}
})
}
}
render() {
const helpStatus = this.state.failed["all"] ?? this.state.failed["result"]
const validateStatus = this.state.failed["all"] || this.state.failed["result"] ? "error" : null
if (!this.props.items) {
console.warn(`Nothing to render`)
return null
}
return <div
key={this.props.id}
id={this.props.id}
className="formWrapper"
>
<Form
hideRequiredMark={this.props.hideRequiredMark ?? false}
name={this.props.name ?? "new_form"}
onFinish={(e) => this.handleFinish(e)}
ref={this.ref}
{...this.props.formProps}
>
{this.renderItems(this.props.items)}
<Form.Item key="result" help={helpStatus} validateStatus={validateStatus} />
</Form>
{this.renderValidationIcon()}
</div>
}
}

View File

@ -0,0 +1,5 @@
.formWrapper {
svg {
margin: 0;
}
}

View File

@ -0,0 +1,29 @@
import React from "react"
// import icons lib
import * as lib1 from "feather-reactjs"
import * as lib2 from "react-icons/md"
import * as lib3 from "@ant-design/icons"
const marginedStyle = { width: "1em", height: "1em", marginRight: "10px", verticalAlign: "-0.125em" }
const customs = {
verifiedBadge: () => <svg style={marginedStyle} xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 24 24"> <path d="M23 12l-2.44-2.78.34-3.68-3.61-.82-1.89-3.18L12 3 8.6 1.54 6.71 4.72l-3.61.81.34 3.68L1 12l2.44 2.78-.34 3.69 3.61.82 1.89 3.18L12 21l3.4 1.46 1.89-3.18 3.61-.82-.34-3.68L23 12m-13 5l-4-4 1.41-1.41L10 14.17l6.59-6.59L18 9l-8 8z"></path></svg>,
}
export const Icons = {
...customs,
...lib1,
...lib2,
...lib3,
}
export function createIconRender(icon, props) {
if (typeof Icons[icon] !== "undefined") {
return React.createElement(Icons[icon], props)
}
return null
}
export default Icons

View File

@ -0,0 +1,6 @@
import React from "react"
import { LazyLoadImage } from "react-lazy-load-image-component"
import "react-lazy-load-image-component/src/effects/blur.css"
export default (props) => <LazyLoadImage {...props} effect="blur" />

View File

@ -0,0 +1,172 @@
import React from "react"
import { DraggableDrawer } from "components"
import EventEmitter from "@foxify/events"
import "./index.less"
export default class DrawerController extends React.Component {
constructor(props) {
super(props)
this.state = {
addresses: {},
refs: {},
drawers: [],
}
this.DrawerController = {
open: this.open,
close: this.close,
closeAll: this.closeAll,
}
window.app["DrawerController"] = this.DrawerController
}
sendEvent = (id, ...context) => {
const ref = this.state.refs[id]?.current
return ref.events.emit(...context)
}
open = (id, component, options) => {
const refs = this.state.refs ?? {}
const drawers = this.state.drawers ?? []
const addresses = this.state.addresses ?? {}
const instance = {
id,
key: id,
ref: React.createRef(),
children: component,
options,
controller: this,
}
if (typeof addresses[id] === "undefined") {
drawers.push(<Drawer {...instance} />)
addresses[id] = drawers.length - 1
refs[id] = instance.ref
} else {
const ref = refs[id].current
const isLocked = ref.state.locked
if (!isLocked) {
drawers[addresses[id]] = <Drawer {...instance} />
refs[id] = instance.ref
} else {
console.warn("Cannot update an locked drawer.")
}
}
this.setState({ refs, addresses, drawers })
}
destroy = (id) => {
let { addresses, drawers, refs } = this.state
const index = addresses[id]
if (typeof drawers[index] !== "undefined") {
drawers = drawers.filter((value, i) => i !== index)
}
delete addresses[id]
delete refs[id]
this.setState({ addresses, drawers })
}
close = (id) => {
const ref = this.state.refs[id]?.current
if (typeof ref !== "undefined") {
if (ref.state.locked && ref.state.visible) {
return console.warn("This drawer is locked and cannot be closed")
} else {
return ref.close()
}
} else {
return console.warn("This drawer not exists")
}
}
closeAll = () => {
this.state.drawers.forEach((drawer) => {
drawer.ref.current.close()
})
}
render() {
return this.state.drawers
}
}
export class Drawer extends React.Component {
options = this.props.options ?? {}
events = new EventEmitter()
state = {
visible: true,
}
componentDidMount = async () => {
if (typeof this.props.controller === "undefined") {
throw new Error(`Cannot mount an drawer without an controller`)
}
if (typeof this.props.children === "undefined") {
throw new Error(`Empty component`)
}
}
toogleVisibility = (to) => {
this.setState({ visible: to ?? !this.state.visible })
}
close = () => {
this.toogleVisibility(false)
this.events.emit("beforeClose")
setTimeout(() => {
if (typeof this.options.onClose === "function") {
this.options.onClose()
}
this.props.controller.destroy(this.props.id)
}, 500)
}
sendEvent = (...context) => {
return this.props.controller.sendEvent(this.props.id, ...context)
}
handleDone = (...context) => {
if (typeof this.options.onDone === "function") {
this.options.onDone(this, ...context)
}
}
handleFail = (...context) => {
if (typeof this.options.onFail === "function") {
this.options.onFail(this, ...context)
}
}
render() {
const drawerProps = {
...this.options.props,
ref: this.props.ref,
key: this.props.id,
onRequestClose: this.close,
open: this.state.visible,
containerElementClass: "drawer",
modalElementClass: "body",
}
const componentProps = {
...this.options.componentProps,
events: this.events,
close: this.close,
handleDone: this.handleDone,
handleFail: this.handleFail,
}
return <DraggableDrawer {...drawerProps}>
{React.createElement(this.props.children, componentProps)}
</DraggableDrawer>
}
}

View File

@ -0,0 +1,26 @@
.drawer {
.body {
position: absolute;
top: 50px;
padding: 30px 10px 10px 10px;
background-color: var(--background-color-primary);
width: 100%;
max-width: 700px;
min-height: 100%;
border-top-left-radius: 8px;
border-top-right-radius: 8px;
}
.body::before{
content: "";
background-color: var(--background-color-contrast);
width: 100px;
height: 8px;
position: absolute;
top: 10px;
left: 50%;
transform: translateX(-50%);
border-radius: 8px;
}
}

View File

@ -0,0 +1,49 @@
import React from "react"
import * as antd from "antd"
import { Icons } from "components/Icons"
import { AppSearcher } from "components"
import classnames from "classnames"
import "./index.less"
export default class Header extends React.Component {
controller = window.app["HeaderController"] = {
toggleVisibility: (to) => {
if (window.isMobile) {
to = true
}
this.setState({ visible: to ?? !this.state.visible })
},
isVisible: () => this.state.visible,
}
state = {
visible: false, // set by default to create an animation
}
componentDidMount = async () => {
setTimeout(() => {
this.controller.toggleVisibility(true)
}, 100)
}
render() {
return (
<antd.Layout.Header className={classnames(`app_header`, { ["hidden"]: !window.isMobile && !this.state.visible })}>
<div>
<antd.Button
onClick={window.app.openCreateNew}
type="primary"
shape="circle"
icon={<Icons.Plus style={{ margin: 0 }} />}
/>
</div>
{!window.isMobile &&
<div>
<AppSearcher />
</div>}
</antd.Layout.Header>
)
}
}

View File

@ -0,0 +1,32 @@
@import "theme/index.less";
.app_header {
user-select: none;
--webkit-user-select: none;
display: flex;
flex-direction: row;
align-items: center;
z-index: 100;
height: @app_header_height !important;
padding: 10px;
transition: all ease-in-out 150ms;
background-color: transparent;
background: transparent !important;
border-bottom: 1px var(--border-color) solid;
>div {
margin-right: 16px;
}
&.hidden {
opacity: 0;
height: 0 !important;
padding: 0 !important;
border: 0 !important;
}
}

View File

@ -0,0 +1,5 @@
export { default as Header } from "./header"
export { default as Drawer } from "./drawer"
export { default as Sidebar } from "./sidebar"
export { default as Sidedrawer } from "./sidedrawer"
export { default as Modal } from "./modal"

View File

@ -0,0 +1,74 @@
import React from "react"
import { Modal, Button } from "antd"
import { Icons } from "components/Icons"
import "./index.less"
export default class AppModal extends React.Component {
constructor(props) {
super(props)
this.controller = app.ModalController = {
open: this.open,
close: this.close,
modalRef: this.modalRef,
}
}
state = {
currentRender: null,
renderParams: {}
}
modalRef = React.createRef()
open = (render, params = {}) => {
this.setState({
currentRender: render,
renderParams: params
})
}
close = () => {
this.setState({
currentRender: null,
renderParams: {}
})
}
handleModalClose = () => {
this.close()
}
renderModal = () => {
return <div className="appModalWrapper">
<Button
icon={<Icons.X />}
className="closeButton"
onClick={this.handleModalClose}
shape="circle"
/>
<div className="appModal" ref={this.modalRef}>
{React.createElement(this.state.currentRender, {
...this.state.renderParams.props ?? {},
close: this.close,
})}
</div>
</div>
}
render() {
return <Modal
open={this.state.currentRender}
maskClosable={this.state.renderParams.maskClosable ?? true}
modalRender={this.renderModal}
maskStyle={{
backgroundColor: "rgba(0, 0, 0, 0.7)",
backdropFilter: "blur(5px)"
}}
destroyOnClose
centered
/>
}
}

View File

@ -0,0 +1,43 @@
.appModalWrapper {
.closeButton {
background-color: var(--background-color-primary);
pointer-events: all;
font-size: 1.2rem;
transform: translate(-25px, -10px);
svg {
margin: 0 !important;
color: var(--text-color);
}
&:hover {
background-color: var(--background-color-primary);
}
}
.appModal {
pointer-events: all;
display: flex;
flex-direction: column;
align-self: center;
border-radius: 8px;
width: fit-content;
height: fit-content;
min-height: 500px;
min-width: 600px;
padding: 30px;
background-color: var(--background-color-accent);
color: var(--text-color);
}
}

View File

@ -0,0 +1,266 @@
import React from "react"
import { Button } from "antd"
import { DragDropContext, Droppable, Draggable } from "react-beautiful-dnd"
import { ActionsBar } from "components"
import { Icons, createIconRender } from "components/Icons"
import sidebarItems from "schemas/routes.json"
import { sidebarKeys as defaultSidebarKeys } from "schemas/defaultSettings"
import Selector from "../selector"
import "./index.less"
const allItemsMap = [...sidebarItems].map((item, index) => {
item.key = index.toString()
item.index = index
return item
})
const getAllItems = () => {
let items = {}
allItemsMap.forEach((item) => {
items[item.id] = {
...item,
content: (
<>
{createIconRender(item.icon)} {item.title}
</>
),
}
})
return items
}
const allItems = getAllItems()
export default class SidebarEditor extends React.Component {
state = {
items: [],
lockedIndex: [],
}
componentDidMount() {
this.loadItems()
}
loadItems = () => {
const storagedKeys = window.app.settings.get("sidebarKeys") ?? defaultSidebarKeys
const active = []
const lockedIndex = []
// set current active items
storagedKeys.forEach((key) => {
if (typeof allItems[key] !== "undefined") {
if (allItems[key].locked) {
lockedIndex.push(allItems[key].index)
}
active.push(key)
}
})
this.setState({ items: active, lockedIndex })
}
onSave = () => {
window.app.settings.set("sidebarKeys", this.state.items)
window.app.SidebarController.toggleEdit(false)
}
onDiscard = () => {
window.app.SidebarController.toggleEdit(false)
}
onSetDefaults = () => {
window.app.settings.set("sidebarKeys", defaultSidebarKeys)
this.loadItems()
}
reorder = (list, startIndex, endIndex) => {
const result = Array.from(list)
const [removed] = result.splice(startIndex, 1)
result.splice(endIndex, 0, removed)
return result
}
onDragEnd = (result) => {
if (!result.destination) {
return false
}
if (this.state.lockedIndex.includes(result.destination.index)) {
return false
}
if (allItems[result.draggableId].locked) {
console.warn("Cannot move an locked item")
return false
}
const items = this.reorder(this.state.items, result.source.index, result.destination.index)
this.setState({ items })
}
deleteItem = (key) => {
// check if item is locked
if (allItems[key].locked) {
console.warn("Cannot delete an locked item")
return false
}
this.setState({ items: this.state.items.filter((item) => item !== key) })
}
addItem = () => {
const keys = []
// filter by active keys
allItemsMap.forEach((item) => {
if (!this.state.items.includes(item.id)) {
keys.push(item.id)
}
})
window.app.DrawerController.open("sidebar_item_selector", Selector, {
props: {
width: "65%",
},
componentProps: {
items: keys
},
onDone: (drawer, selectedKeys) => {
drawer.close()
if (Array.isArray(selectedKeys)) {
const update = this.state.items ?? []
selectedKeys.forEach((key) => {
if (update.includes(key)) {
return false
}
update.push(key)
})
this.setState({ items: update })
}
},
})
}
render() {
const grid = 6
const getItemStyle = (isDragging, draggableStyle, component, isDraggingOver) => ({
cursor: component.locked ? "not-allowed" : "grab",
userSelect: "none",
padding: grid * 2,
margin: `0 0 ${grid}px 0`,
borderRadius: "6px",
transition: "150ms all ease-in-out",
width: "100%",
border: isDraggingOver ? "2px dashed #e0e0e0" : "none",
color: component.locked ? "rgba(145,145,145,0.6)" : "#000",
background: component.locked
? "rgba(145, 145, 145, 0.2)"
: isDragging
? "rgba(145, 145, 145, 0.5)"
: "transparent",
...draggableStyle,
})
const getListStyle = (isDraggingOver) => ({
background: "transparent",
transition: "150ms all ease-in-out",
padding: grid,
width: "100%",
})
return (
<div>
<DragDropContext onDragEnd={this.onDragEnd}>
<Droppable droppableId="droppable">
{(droppableProvided, droppableSnapshot) => (
<div
ref={droppableProvided.innerRef}
style={getListStyle(droppableSnapshot.isDraggingOver)}
>
{this.state.items.map((key, index) => {
const itemComponent = allItems[key]
return (
<Draggable
isDragDisabled={itemComponent.locked}
key={key}
draggableId={key}
index={index}
>
{(draggableProvided, draggableSnapshot) => (
<div
ref={draggableProvided.innerRef}
{...draggableProvided.draggableProps}
{...draggableProvided.dragHandleProps}
style={getItemStyle(
draggableSnapshot.isDragging,
draggableProvided.draggableProps.style,
itemComponent,
droppableSnapshot.isDraggingOver,
)}
>
{!allItems[key].locked &&
<Icons.Trash
onClick={() => this.deleteItem(key)}
className="sidebar_editor_deleteBtn"
/>
}
{itemComponent.icon && createIconRender(itemComponent.icon)}
{itemComponent.title ?? itemComponent.id}
</div>
)}
</Draggable>
)
})}
{droppableProvided.placeholder}
</div>
)}
</Droppable>
</DragDropContext>
<ActionsBar
style={{ position: "absolute", bottom: 0, left: 0, width: "100%", borderRadius: "12px 12px 0 0" }}
>
<div>
<Button
style={{ lineHeight: 0 }}
icon={<Icons.Plus style={{ margin: 0, padding: 0 }} />}
onClick={this.addItem}
/>
</div>
<div>
<Button
style={{ lineHeight: 0 }}
icon={<Icons.Check />}
type="primary"
onClick={this.onSave}
>
Done
</Button>
</div>
<div>
<Button onClick={this.onDiscard} icon={<Icons.XCircle />} >Cancel</Button>
</div>
<div>
<Button type="link" onClick={this.onSetDefaults}>Set defaults</Button>
</div>
</ActionsBar>
</div>
)
}
}

View File

@ -0,0 +1,14 @@
.app_sidebar_sider_edit .ant-layout-sider-children{
margin-top: 15px!important;
.app_sidebar_menu_wrapper {
opacity: 0;
height: 0;
overflow: hidden;
}
}
.sidebar_editor_deleteBtn:hover{
color: red;
cursor: pointer;
}

View File

@ -0,0 +1 @@
export { default as SidebarEditor } from './editor';

View File

@ -0,0 +1,76 @@
import React from "react"
import { Icons, createIconRender } from "components/Icons"
import { SelectableList } from "components"
import { List } from "antd"
import sidebarItems from "schemas/routes.json"
import "./index.less"
const getStoragedKeys = () => {
return window.app.settings.get("sidebarKeys") ?? []
}
const getAllItems = () => {
const obj = {}
sidebarItems.forEach((item) => {
obj[item.id] = item
})
return obj
}
const allItems = getAllItems()
export default class SidebarItemSelector extends React.Component {
state = {
items: null,
}
componentDidMount = () => {
const source = (this.props.items ?? getStoragedKeys() ?? []).map((key) => {
return { key }
})
this.setState({ items: source })
}
handleDone = (selectedKeys) => {
if (typeof this.props.onDone === "function") {
this.props.onDone(selectedKeys)
}
}
render() {
return (
<div>
<h1>
<Icons.PlusCircle /> Select items to add
</h1>
{this.state.items && (
<SelectableList
itemLayout="vertical"
size="large"
pagination={{
pageSize: 10,
}}
onDone={this.handleDone}
items={this.state.items ?? []}
itemClassName="sidebar_selector_item"
renderItem={(i) => {
const item = allItems[i.key]
return (
<List.Item key={item.title} className="sidebar_selector_item">
{createIconRender(item.icon)}
{item.title ?? item.id}
</List.Item>
)
}}
/>
)}
</div>
)
}
}

View File

@ -0,0 +1,4 @@
.sidebar_selector_item{
height: fit-content;
padding: 0;
}

View File

@ -0,0 +1,381 @@
import React from "react"
import { Layout, Menu, Avatar } from "antd"
import classnames from "classnames"
import config from "config"
import { Icons, createIconRender } from "components/Icons"
import { sidebarKeys as defaultSidebarItems } from "schemas/defaultSettings"
import sidebarItems from "schemas/routes.json"
import { Translation } from "react-i18next"
import { SidebarEditor } from "./components"
import "./index.less"
const { Sider } = Layout
const onClickHandlers = {
settings: (event) => {
window.app.openSettings()
},
}
export default class Sidebar extends React.Component {
constructor(props) {
super(props)
this.controller = window.app["SidebarController"] = {
toggleVisibility: this.toggleVisibility,
toggleEdit: this.toggleEditMode,
toggleElevation: this.toggleElevation,
attachElement: this.attachElement,
isVisible: () => this.state.visible,
isEditMode: () => this.state.visible,
isCollapsed: () => this.state.collapsed,
}
this.state = {
editMode: false,
visible: false,
loading: true,
collapsed: window.app.settings.get("collapseOnLooseFocus") ?? false,
pathResolve: {},
menus: {},
extraItems: {
bottom: [],
top: [],
},
elevated: false,
additionalElements: [],
}
window.app.eventBus.on("edit_sidebar", () => this.toggleEditMode())
window.app.eventBus.on("settingChanged.sidebar_collapse", (value) => {
this.toggleCollapse(value)
})
// handle sidedrawer open/close
window.app.eventBus.on("sidedrawer.hasDrawers", () => {
this.toggleElevation(true)
})
window.app.eventBus.on("sidedrawer.noDrawers", () => {
this.toggleElevation(false)
})
}
collapseDebounce = null
componentDidMount = async () => {
await this.loadSidebarItems()
setTimeout(() => {
this.controller.toggleVisibility(true)
}, 100)
}
getStoragedKeys = () => {
return window.app.settings.get("sidebarKeys")
}
attachElement = (element) => {
this.setState({
additionalElements: [...this.state.additionalElements, element],
})
}
appendItem = (item = {}) => {
const { position } = item
if (typeof position === "undefined" && typeof this.state.extraItems[position] === "undefined") {
console.error("Invalid position")
return false
}
const state = this.state.extraItems
state[position].push(item)
this.setState({ extraItems: state })
}
loadSidebarItems = () => {
const items = {}
const itemsMap = []
// parse all items from schema
sidebarItems.forEach((item, index) => {
items[item.id] = {
...item,
index,
content: (
<>
{createIconRender(item.icon)} {item.title}
</>
),
}
})
// filter undefined to avoid error
let keys = (this.getStoragedKeys() ?? defaultSidebarItems).filter((key) => {
if (typeof items[key] !== "undefined") {
return true
}
})
// short items
keys.forEach((id, index) => {
const item = items[id]
if (item.locked) {
if (item.index !== index) {
keys = keys.move(index, item.index)
//update index
window.app.settings.set("sidebarKeys", keys)
}
}
})
// set items from scoped keys
keys.forEach((key, index) => {
const item = items[key]
try {
// avoid if item is duplicated
if (itemsMap.includes(item)) {
return false
}
let valid = true
if (typeof item.requireState === "object") {
const { key, value } = item.requireState
//* TODO: check global state
}
// end validation
if (!valid) {
return false
}
if (typeof item.path !== "undefined") {
let resolvers = this.state.pathResolve ?? {}
resolvers[item.id] = item.path
this.setState({ pathResolve: resolvers })
}
itemsMap.push(item)
} catch (error) {
return console.log(error)
}
})
// update states
this.setState({ items, menus: itemsMap, loading: false })
}
renderMenuItems(items) {
const handleRenderIcon = (icon) => {
if (typeof icon === "undefined") {
return null
}
return createIconRender(icon)
}
return items.map((item) => {
if (Array.isArray(item.children)) {
return (
<Menu.SubMenu
key={item.id}
icon={handleRenderIcon(item.icon)}
title={<span>
<Translation>
{t => t(item.title)}
</Translation>
</span>}
{...item.props}
>
{this.renderMenuItems(item.children)}
</Menu.SubMenu>
)
}
return (
<Menu.Item key={item.id} icon={handleRenderIcon(item.icon)} {...item.props}>
<Translation>
{t => t(item.title ?? item.id)}
</Translation>
</Menu.Item>
)
})
}
handleClick = (e) => {
if (e.item.props.overrideEvent) {
return app.eventBus.emit(e.item.props.overrideEvent, e.item.props.overrideEventProps)
}
if (typeof e.key === "undefined") {
window.app.eventBus.emit("invalidSidebarKey", e)
return false
}
if (typeof onClickHandlers[e.key] === "function") {
return onClickHandlers[e.key](e)
}
if (typeof this.state.pathResolve[e.key] !== "undefined") {
return window.app.setLocation(`/${this.state.pathResolve[e.key]}`, 150)
}
return window.app.setLocation(`/${e.key}`, 150)
}
toggleEditMode = (to) => {
if (typeof to === "undefined") {
to = !this.state.editMode
}
if (to) {
window.app.eventBus.emit("clearAllOverlays")
} else {
if (this.itemsMap !== this.getStoragedKeys()) {
this.loadSidebarItems()
}
}
this.setState({ editMode: to, collapsed: false })
}
toggleCollapse = (to) => {
if (!this.state.editMode) {
this.setState({ collapsed: to ?? !this.state.collapsed })
}
}
toggleVisibility = (to) => {
this.setState({ visible: to ?? !this.state.visible })
}
toggleElevation = (to) => {
this.setState({ elevated: to ?? !this.state.elevated })
}
onMouseEnter = () => {
if (window.app.settings.is("collapseOnLooseFocus", false)) {
return false
}
clearTimeout(this.collapseDebounce)
this.collapseDebounce = null
if (this.state.collapsed) {
this.toggleCollapse(false)
}
}
handleMouseLeave = () => {
if (window.app.settings.is("collapseOnLooseFocus", false)) {
return false
}
if (!this.state.collapsed) {
this.collapseDebounce = setTimeout(() => { this.toggleCollapse(true) }, window.app.settings.get("autoCollapseDelay") ?? 500)
}
}
renderExtraItems = (position) => {
return this.state.extraItems[position].map((item = {}) => {
if (typeof item.icon !== "undefined") {
if (typeof item.props !== "object") {
item.props = Object()
}
item.props["icon"] = createIconRender(item.icon)
}
return <Menu.Item key={item.id} {...item.props}>{item.children}</Menu.Item>
})
}
render() {
if (this.state.loading) return null
const { user } = this.props
return (
<Sider
onMouseEnter={this.onMouseEnter}
onMouseLeave={this.handleMouseLeave}
theme={this.props.theme}
width={this.state.editMode ? 400 : 200}
collapsed={this.state.editMode ? false : this.state.collapsed}
onCollapse={() => this.props.onCollapse()}
className={
classnames(
"sidebar",
{
["edit_mode"]: this.state.editMode,
["hidden"]: !this.state.visible,
["elevated"]: this.state.elevated
}
)
}
>
<div className="app_sidebar_header">
<div className={classnames("app_sidebar_header_logo", { ["collapsed"]: this.state.collapsed })}>
<img src={this.state.collapsed ? config.logo?.alt : config.logo?.full} />
</div>
</div>
{this.state.editMode && (
<div style={{ height: "100%" }}>
<SidebarEditor />
</div>
)}
{!this.state.editMode && (
<div key="menu" className="app_sidebar_menu">
<Menu selectable={true} mode="inline" theme={this.props.theme} onClick={this.handleClick}>
{this.renderMenuItems(this.state.menus)}
{this.renderExtraItems("top")}
</Menu>
</div>
)}
{!this.state.editMode && <div key="additionalElements" className="additionalElements">
{this.state.additionalElements}
</div>}
{!this.state.editMode && (
<div key="bottom" className="app_sidebar_bottom">
<Menu selectable={false} mode="inline" theme={this.props.theme} onClick={this.handleClick}>
<Menu.Item key="create" icon={<Icons.PlusCircle />} overrideEvent="app.openCreator" >
<Translation>
{(t) => t("Create")}
</Translation>
</Menu.Item>
<Menu.Item key="notifications" icon={<Icons.Bell />}>
<Translation>
{t => t("Notifications")}
</Translation>
</Menu.Item>
<Menu.Item key="settings" icon={<Icons.Settings />}>
<Translation>
{t => t("Settings")}
</Translation>
</Menu.Item>
<Menu.Item key="account">
<div className="user_avatar">
<Avatar shape="square" src={user?.avatar} />
</div>
</Menu.Item>
{this.renderExtraItems("bottom")}
</Menu>
</div>
)}
</Sider>
)
}
}

View File

@ -0,0 +1,160 @@
@import "theme/vars.less";
// SIDEBAR
.ant-layout-sider {
z-index: 50;
background: var(--sidebar-background-color) !important;
background-color: var(--sidebar-background-color) !important;
border-radius: 0 @app_sidebar_borderRadius @app_sidebar_borderRadius 0;
overflow: hidden;
border: 1px solid var(--sidebar-background-color);
transition: all 150ms ease-in-out;
&.hidden {
flex: 0 !important;
min-width: 0 !important;
background-color: transparent !important;
width: 0 !important;
}
&.elevated {
box-shadow: 0 0 5px 4px rgba(0, 0, 0, 0.1) !important;
}
}
.ant-menu-item {
color: var(--background-color-contrast);
h1,
h2,
h3,
h4,
h5,
h6,
span,
p {
color: var(--background-color-contrast);
}
}
.ant-menu,
.ant-menu ul {
background: transparent !important;
background-color: transparent !important;
border-right: 0 !important;
}
.sidebar .ant-layout-sider-children {
margin-top: 15px !important;
margin-bottom: 15px !important;
background: transparent !important;
background-color: transparent !important;
user-select: none;
--webkit-user-select: none;
transition: all 150ms ease-in-out;
height: 100%;
display: flex;
flex-direction: column;
&.edit_mode .ant-layout-sider-children {
background: transparent !important;
background-color: transparent !important;
margin-top: 15px !important;
.app_sidebar_menu_wrapper {
opacity: 0;
height: 0;
overflow: hidden;
}
}
}
.app_sidebar_menu_wrapper {
transition: all 450ms ease-in-out;
height: 100%;
width: 100%;
}
.app_sidebar_header {
background: transparent !important;
background-color: transparent !important;
user-select: none;
--webkit-user-select: none;
display: flex;
flex-direction: column;
height: 15%;
margin-top: 5%;
margin-bottom: 5%;
}
.app_sidebar_header_logo {
user-select: none;
--webkit-user-select: none;
display: flex;
align-items: center;
justify-content: center;
img {
user-select: none;
--webkit-user-select: none;
width: 80%;
max-height: 80px;
}
&.collapsed {
img {
max-width: 40px;
}
}
}
.app_sidebar_menu {
background: transparent !important;
background-color: transparent !important;
height: 65%;
overflow: overlay;
overflow-x: hidden;
}
.app_sidebar_bottom {
position: absolute;
bottom: 0;
padding-bottom: 30px;
z-index: 50;
left: 0;
background: transparent !important;
background-color: transparent !important;
backdrop-filter: blur(10px);
--webkit-backdrop-filter: blur(10px);
width: 100%;
height: fit-content;
.ant-menu,
ul {
background: transparent !important;
background-color: transparent !important;
}
}
.user_avatar {
display: flex;
align-items: center;
justify-content: center;
padding: 0 !important;
}

View File

@ -0,0 +1,226 @@
import React from "react"
import classnames from "classnames"
import "./index.less"
export const Sidedrawer = (props) => {
const sidedrawerId = props.id ?? props.key
return <div
key={sidedrawerId}
id={sidedrawerId}
className={
classnames("sidedrawer", {
"hided": !props.defaultVisible,
})
}
>
{
React.createElement(props.children, {
...props.props,
close: props.close,
})
}
</div>
}
export default class SidedrawerController extends React.Component {
state = {
drawers: [],
lockedIds: [],
}
constructor(props) {
super(props)
this.controller = window.app["SidedrawerController"] = {
open: this.open,
close: this.close,
closeAll: this.closeAll,
hasDrawers: this.state.drawers.length > 0,
}
}
componentDidMount = () => {
this.listenEscape()
}
componentDidUpdate() {
this.controller.hasDrawers = this.state.drawers.length > 0
if (this.controller.hasDrawers) {
window.app.eventBus.emit("sidedrawer.hasDrawers")
} else {
window.app.eventBus.emit("sidedrawer.noDrawers")
}
}
componentWillUnmount = () => {
this.unlistenEscape()
}
drawerIsLocked = (id) => {
return this.state.lockedIds.includes(id)
}
lockDrawerId = (id) => {
this.setState({
lockedIds: [...this.state.lockedIds, id],
})
}
unlockDrawer = (id) => {
this.setState({
lockedIds: this.state.lockedIds.filter(lockedId => lockedId !== id),
})
}
open = async (id, component, options = {}) => {
if (typeof id !== "string") {
options = component
component = id
id = component.key ?? component.id ?? Math.random().toString(36).substr(2, 9)
}
let drawers = this.state.drawers
// check if id is already in use
// but only if its allowed to be used multiple times
const existentDrawer = drawers.find((drawer) => drawer.props.id === id)
if (existentDrawer) {
if (!existentDrawer.props.allowMultiples) {
console.warn(`Sidedrawer with id "${id}" already exists.`)
return false
}
// fix id appending the corresponding array index at the end of the id
// ex ["A", "B", "C"] => ["A", "B", "C", "A-1"]
// to prevent id collisions
let index = 0
let newId = id
while (drawers.find(drawer => drawer.props.id === newId)) {
index++
newId = id + "-" + index
}
id = newId
}
drawers.push(React.createElement(
Sidedrawer,
{
key: id,
id: id,
allowMultiples: options.allowMultiples ?? false,
...options.props,
close: this.close,
escClosable: options.escClosable ?? true,
defaultVisible: false,
selfLock: () => {
this.lockDrawerId(id)
},
selfUnlock: () => {
this.unlockDrawer(id)
}
},
component
))
if (options.lock) {
this.lockDrawerId(id)
}
await this.setState({ drawers })
setTimeout(() => {
this.toggleDrawerVisibility(id, true)
}, 10)
window.app.eventBus.emit("sidedrawer.open")
}
toggleDrawerVisibility = (id, to) => {
const drawer = document.getElementById(id)
const drawerClasses = drawer.classList
if (to) {
drawerClasses.remove("hided")
} else {
drawerClasses.add("hided")
}
}
close = (id) => {
// if an id is provided filter by key
// else close the last opened drawer
let drawers = this.state.drawers
let drawerId = id ?? drawers[drawers.length - 1].props.id
// check if id is locked
if (this.drawerIsLocked(id)) {
console.warn(`Sidedrawer with id "${id}" is locked.`)
return false
}
// check if id exists
const drawer = drawers.find(drawer => drawer.props.id === drawerId)
if (!drawer) {
console.warn(`Sidedrawer with id "${id}" does not exist.`)
return false
}
// emit event
window.app.eventBus.emit("sidedrawer.close")
// toogleVisibility off
this.toggleDrawerVisibility(drawerId, false)
// await drawer transition
setTimeout(() => {
// remove drawer
drawers = drawers.filter(drawer => drawer.props.id !== drawerId)
this.setState({ drawers })
}, 500)
}
listenEscape = () => {
document.addEventListener("keydown", this.handleEscKeyPress)
}
unlistenEscape = () => {
document.removeEventListener("keydown", this.handleEscKeyPress)
}
handleEscKeyPress = (event) => {
// avoid handle keypress when is nothing to render
if (this.state.drawers.length === 0) {
return false
}
let isEscape = false
if ("key" in event) {
isEscape = event.key === "Escape" || event.key === "Esc"
} else {
isEscape = event.keyCode === 27
}
if (isEscape) {
// close the last opened drawer
this.close()
}
}
render() {
return <div
className="sidedrawers-wrapper"
>
{this.state.drawers}
</div>
}
}

View File

@ -0,0 +1,44 @@
@import "theme/vars.less";
.sidedrawers-wrapper {
display: flex;
flex-direction: row;
> div {
transform: translate(-50px, 0);
}
.sidedrawer {
position: relative;
width: 30vw; // by default
height: 100vh;
min-width: 700px;
z-index: 20;
background-color: var(--sidedrawer-background-color);
border-radius: 0 @app_sidebar_borderRadius @app_sidebar_borderRadius 0;
padding: 20px;
padding-left: 70px;
transform: translate(-50px, 0);
overflow-x: hidden;
overflow-y: overlay;
word-break: break-all;
transition: all 150ms ease-in-out;
// create shadow on the right side
box-shadow : 0 0 5px 4px rgba(0, 0, 0, 0.1) !important;
&.hided {
width: 0;
min-width: 0;
padding: 0;
}
}
}

View File

@ -0,0 +1,134 @@
import React from "react"
import * as antd from "antd"
import { FormGenerator } from "components"
import { Icons } from "components/Icons"
import config from "config"
import "./index.less"
const formInstance = [
{
id: "username",
element: {
component: "Input",
icon: "User",
placeholder: "Username",
props: {
autoCorrect: "off",
autoCapitalize: "none",
className: "login-form-username",
},
},
item: {
hasFeedback: true,
rules: [
{
required: true,
message: 'Please input your Username!',
},
],
}
},
{
id: "password",
element: {
component: "Input",
icon: "Lock",
placeholder: "Password",
props: {
type: "password"
}
},
item: {
hasFeedback: true,
rules: [
{
required: true,
message: 'Please input your Password!',
},
],
}
},
{
id: "login_btn",
withValidation: true,
element: {
component: "Button",
props: {
icon: "User",
children: "Login",
type: "primary",
htmlType: "submit"
}
}
},
]
export default class Login extends React.Component {
static pageStatement = {
bottomBarAllowed: false
}
handleFinish = async (values, ctx) => {
ctx.toogleValidation(true)
const payload = {
username: values.username,
password: values.password,
allowRegenerate: values.allowRegenerate,
}
this.props.sessionController.login(payload, (error, response) => {
ctx.toogleValidation(false)
ctx.clearErrors()
if (error) {
ctx.shake("all")
return ctx.error("result", error)
} else {
if (response.status === 200) {
this.onDone()
}
}
})
}
onDone = () => {
if (typeof this.props.onDone === "function") {
this.props.onDone()
}
if (typeof this.props.close === "function") {
this.props.close()
}
}
render() {
return <div className="login">
<div className="header">
<div className="logo">
<img src={config.logo?.full} />
</div>
</div>
{this.props.session && <div className="session_available">
<h3><Icons.AlertCircle /> You already have a valid session.</h3>
<div className="session_card">
@{this.props.session.username}
</div>
<antd.Button
type="primary"
onClick={() => window.app.setLocation(config.app?.mainPath ?? "/home")} >
Go to home
</antd.Button>
</div>}
<FormGenerator
name="normal_login"
renderLoadingIcon
className="login-form"
items={formInstance}
onFinish={this.handleFinish}
/>
</div>
}
}

View File

@ -0,0 +1,63 @@
.login {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
> div {
margin-bottom: 20px;
}
.header {
.logo {
width: 15vw;
img {
width: 100%;
height: 100%;
}
}
}
}
.login-form {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.login-form-username {
font-size: 20px!important;
input {
padding: 20px!important;
font-size: 20px!important;
}
}
.session_available {
width: fit-content;
height: fit-content;
padding: 20px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
border: 1px solid var(--border-color);
border-radius: 8px;
.session_card {
width: fit-content;
height: fit-content;
margin: 10px;
padding: 5px 10px;
border: 1px solid #e5e5e5;
border-radius: 8px;
}
}

View File

@ -0,0 +1,76 @@
import React from "react"
import * as antd from "antd"
import { Icons, createIconRender } from "components/Icons"
export default (props) => {
const [loading, setLoading] = React.useState(false)
const [options, setOptions] = React.useState([])
const [value, setValue] = React.useState(null)
const onChangeProperties = async (update) => {
if (props.eventDisable) {
return false
}
setLoading(true)
await props.onChangeProperties(update)
.then((data) => {
return setValue(update.join("-"))
})
.catch((error) => {
return
})
setLoading(false)
}
const getTagColor = () => {
if (props.colors) {
return props.colors[value]
}
return "default"
}
const handleOptionsLoad = async (fn) => {
setLoading(true)
const result = await fn()
setOptions(result)
setLoading(false)
}
const handleDefaultValueLoad = async (fn) => {
const result = await fn()
setValue(result)
}
React.useEffect(() => {
if (typeof props.options === "function") {
handleOptionsLoad(props.options)
} else {
setOptions(props.options)
}
if (typeof props.defaultValue === "function") {
handleDefaultValueLoad(props.defaultValue)
} else {
setValue(props.defaultValue)
}
}, [])
return <antd.Cascader options={options} onChange={(update) => onChangeProperties(update)} >
<antd.Tag color={getTagColor()}>
{loading ? <Icons.LoadingOutlined spin /> :
<>
{Icons[props.icon] && createIconRender(props.icon)}
<h4>
{value}
</h4>
</>
}
</antd.Tag>
</antd.Cascader>
}

View File

@ -0,0 +1,12 @@
import React from "react"
import { Result } from "antd"
export default () => {
return (
<Result
status="404"
title="404"
subTitle="Sorry, the page you visited does not exist."
/>
)
}

View File

@ -0,0 +1,91 @@
import React from "react"
import * as antd from "antd"
import { decycle } from "@corenode/utils"
import { Icons } from "components/Icons"
function parseTreeData(data, backKey) {
const keys = Object.keys(data)
let result = Array()
keys.forEach((key) => {
const value = data[key]
const valueType = typeof value
const obj = Object()
obj.key = backKey ? `${backKey}-${key}` : key
obj.title = key
obj.type = valueType
if (valueType === "object") {
obj.children = parseTreeData(value)
} else {
obj.children = [
{
key: `${obj.key}-value`,
title: "value",
icon: <Icons.Box />,
children: [
{
key: `${obj.key}-value-indicator`,
title: String(value),
icon: <Icons.Box />,
},
],
},
{
key: `${obj.key}-type`,
title: "type",
children: [
{
key: `${obj.key}-type-indicator`,
title: valueType,
},
],
},
]
}
result.push(obj)
})
return result
}
export default class ObjectInspector extends React.Component {
state = {
data: null,
expandedKeys: [],
autoExpandParent: true,
}
componentDidMount() {
const raw = decycle(this.props.data)
const data = parseTreeData(raw)
this.setState({ raw, data })
}
onExpand = (expandedKeys) => {
this.setState({
expandedKeys,
autoExpandParent: false,
})
}
render() {
const { expandedKeys, autoExpandParent } = this.state
return (
<div>
<antd.Tree
//showLine
switcherIcon={<Icons.DownOutlined />}
onExpand={this.onExpand}
expandedKeys={expandedKeys}
autoExpandParent={autoExpandParent}
treeData={this.state.data}
/>
</div>
)
}
}

View File

@ -0,0 +1,73 @@
import React from "react"
import { Result, Button, Typography } from "antd"
import { CloseCircleOutlined } from "@ant-design/icons"
import config from "config"
import "./index.less"
const { Paragraph, Text } = Typography
const ErrorEntry = (props) => {
const { error } = props
if (!error) {
return <div className="error">
<CloseCircleOutlined />
Unhandled error
</div>
}
return <div className="error">
<CloseCircleOutlined />
{error.info.toString()}
</div>
}
export default (props) => {
let errors = []
if (Array.isArray(props.error)) {
errors = props.error
} else {
errors.push(props.error)
}
const onClickGoMain = () => {
window.app.setLocation(config.app.mainPath ?? "/main")
}
const onClickReload = () => {
window.location.reload()
}
return (
<div className="app_render_error">
<Result
status="error"
title="Render Error"
subTitle="It seems that the application is having problems displaying this page, we have detected some unrecoverable errors due to a bug. (This error should be automatically reported to the developers to find a solution as soon as possible)"
extra={[
<Button type="primary" key="gomain" onClick={onClickGoMain}>
Go Main
</Button>,
<Button key="reload" onClick={onClickReload}>Reload</Button>,
]}
>
<Paragraph>
<Text
strong
style={{
fontSize: 16,
}}
>
We catch the following errors:
</Text>
<div className="errors">
{errors.map((error, index) => {
return <ErrorEntry key={index} error={error} />
})}
</div>
</Paragraph>
</Result>
</div>
)
}

View File

@ -0,0 +1,16 @@
.errors {
margin-top: 12px;
.error {
margin-bottom: 10px;
svg {
color: red;
margin-right: 10px;
}
.stack {
margin-left: 24px;
word-wrap: break-word;
}
}
}

View File

@ -0,0 +1,198 @@
import React from "react"
import ReactDOM from "react-dom"
import { Rnd } from "react-rnd"
import { Icons } from "components/Icons"
import "./index.less"
class DOMWindow {
constructor(props) {
this.props = { ...props }
this.id = this.props.id
this.key = 0
this.root = document.getElementById("app_windows")
this.element = document.getElementById(this.id)
// handle root container
if (!this.root) {
this.root = document.createElement("div")
this.root.setAttribute("id", "app_windows")
document.body.append(this.root)
}
// get all windows opened has container
const rootNodes = this.root.childNodes
// ensure this window has last key from rootNode
if (rootNodes.length > 0) {
const lastChild = rootNodes[rootNodes.length - 1]
const lastChildKey = Number(lastChild.getAttribute("key"))
this.key = lastChildKey + 1
}
this.element = document.createElement("div")
this.element.setAttribute("id", this.id)
this.element.setAttribute("key", this.key)
this.element.setAttribute("classname", this.props.className)
this.root.appendChild(this.element)
}
render = (fragment) => {
ReactDOM.render(
fragment,
this.element,
)
return this
}
create = () => {
// set render
this.render(<WindowRender {...this.props} id={this.id} key={this.key} destroy={this.destroy} />)
return this
}
destroy = () => {
this.element.remove()
return this
}
}
class WindowRender extends React.Component {
state = {
actions: [],
dimensions: {
height: this.props.height ?? 600,
width: this.props.width ?? 400,
},
position: this.props.defaultPosition,
visible: false,
}
componentDidMount = () => {
this.setDefaultActions()
if (typeof this.props.actions !== "undefined") {
if (Array.isArray(this.props.actions)) {
const actions = this.state.actions ?? []
this.props.actions.forEach((action) => {
actions.push(action)
})
this.setState({ actions })
}
}
if (!this.state.position) {
this.setState({ position: this.getCenterPosition() })
}
this.toogleVisibility(true)
}
toogleVisibility = (to) => {
this.setState({ visible: to ?? !this.state.visible })
}
getCenterPosition = () => {
const dimensions = this.state?.dimensions ?? {}
const windowHeight = dimensions.height ?? 600
const windowWidth = dimensions.width ?? 400
return {
x: window.innerWidth / 2 - windowWidth / 2,
y: window.innerHeight / 2 - windowHeight / 2,
}
}
setDefaultActions = () => {
const { actions } = this.state
actions.push({
key: "close",
render: () => <Icons.XCircle style={{ margin: 0, padding: 0 }} />,
onClick: () => {
this.props.destroy()
},
})
this.setState({ actions })
}
renderActions = () => {
const actions = this.state.actions
if (Array.isArray(actions)) {
return actions.map((action) => {
return (
<div key={action.key} onClick={action.onClick} {...action.props}>
{React.isValidElement(action.render) ? action.render : React.createElement(action.render)}
</div>
)
})
}
return null
}
getComponentRender = () => {
return React.isValidElement(this.props.children)
? React.cloneElement(this.props.children, this.props.renderProps)
: React.createElement(this.props.children, this.props.renderProps)
}
render() {
const { position, dimensions, visible } = this.state
if (!visible) {
return null
}
return (
<Rnd
default={{
...position,
...dimensions,
}}
onResize={(e, direction, ref, delta, position) => {
this.setState({
dimensions: {
width: ref.offsetWidth,
height: ref.offsetHeight,
},
position,
})
}}
dragHandleClassName="window_topbar"
minWidth={this.props.minWidth ?? "300px"}
minHeight={this.props.minHeight ?? "200px"}
>
<div
style={{
height: dimensions.height,
width: dimensions.width,
}}
className="window_wrapper"
>
<div className="window_topbar">
<div className="title">{this.props.id}</div>
<div className="actions">{this.renderActions()}</div>
</div>
<div className="window_body">{this.getComponentRender()}</div>
</div>
</Rnd>
)
}
}
export { DOMWindow, WindowRender }

View File

@ -0,0 +1,93 @@
@wrapper_background: rgba(255, 255, 255, 1);
@topbar_height: 30px;
@topbar_background: rgba(0, 0, 0, 0.4);
.window_wrapper {
border-radius: 12px;
background-color: @wrapper_background;
border: 1px solid rgba(161, 133, 133, 0.2);
overflow: hidden;
&.translucid {
border: unset;
background-color: rgba(0, 0, 0, 0.2);
backdrop-filter: blur(10px);
--webkit-backdrop-filter: blur(10px);
filter: drop-shadow(8px 8px 10px rgba(0, 0, 0, 0.5));
}
}
.window_topbar {
position: sticky;
z-index: 51;
background-color: @topbar_background;
height: @topbar_height;
width: 100%;
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
> div {
margin: 0 5px;
line-height: 0;
}
.title {
margin-left: 20px;
color: #fff - @topbar_background;
font-size: 13px;
font-style: italic;
font-family: "JetBrains Mono", monospace;
}
.actions {
display: flex;
flex-direction: row-reverse;
align-items: center;
justify-content: end;
color: #fff - @topbar_background;
> div {
transition: all 150ms ease-in-out;
margin-right: 10px;
cursor: pointer;
height: fit-content;
width: fit-content;
line-height: 0;
display: flex;
align-items: center;
justify-content: end;
}
> div:hover {
color: var(--primary-color);
}
}
}
.window_body {
z-index: 50;
padding: 10px 20px;
height: calc(100% - @topbar_height);
width: 100%;
overflow: overlay;
user-select: text !important;
--webkit-user-select: text !important;
> div {
user-select: text !important;
--webkit-user-select: text !important;
}
}

View File

@ -0,0 +1,360 @@
import React from "react"
import * as antd from "antd"
import { Button } from "antd"
import classnames from "classnames"
import _ from "lodash"
import { Translation } from "react-i18next"
import { Icons, createIconRender } from "components/Icons"
import { ActionsBar, } from "components"
import { useLongPress, Haptics } from "utils"
import "./index.less"
const ListItem = React.memo((props) => {
let { item } = props
if (!item.key) {
item.key = item._id ?? item.id
}
const doubleClickSpeed = 400
let delayedClick = null
let clickedOnce = null
const handleOnceClick = () => {
clickedOnce = null
if (typeof props.onClickItem === "function") {
return props.onClickItem(item.key)
}
}
const handleDoubleClick = () => {
if (typeof props.onDoubleClickItem === "function") {
return props.onDoubleClickItem(item.key)
}
}
const handleLongPress = () => {
if (typeof props.onLongPressItem === "function") {
return props.onLongPressItem(item.key)
}
}
const renderChildren = props.renderChildren(item)
const isDisabled = renderChildren.props.disabled
return React.createElement("div", {
id: item.key,
key: item.key,
disabled: isDisabled,
className: classnames("selectableList_item", {
["selected"]: props.selected,
["disabled"]: isDisabled,
}),
onDoubleClick: () => {
if (isDisabled) {
return false
}
handleDoubleClick()
},
...useLongPress(
// onLongPress
() => {
if (isDisabled) {
return false
}
if (props.onlyClickSelection) {
return false
}
handleLongPress()
},
// onClick
() => {
if (isDisabled) {
return false
}
if (props.onlyClickSelection) {
return handleOnceClick()
}
if (!delayedClick) {
delayedClick = _.debounce(handleOnceClick, doubleClickSpeed)
}
if (clickedOnce) {
delayedClick.cancel()
clickedOnce = false
handleDoubleClick()
} else {
clickedOnce = true
delayedClick()
}
},
{
shouldPreventDefault: true,
delay: props.longPressDelay ?? 300,
}
),
}, renderChildren)
})
export default class SelectableList extends React.Component {
state = {
selectedKeys: [],
selectionEnabled: false,
}
componentDidMount() {
if (typeof this.props.defaultSelected !== "undefined" && Array.isArray(this.props.defaultSelected)) {
this.setState({
selectedKeys: [...this.props.defaultSelected],
})
}
}
componentDidUpdate(prevProps, prevState) {
if (prevState.selectionEnabled !== this.state.selectionEnabled) {
if (this.state.selectionEnabled) {
this.handleFeedbackEvent("selectionStart")
} else {
this.handleFeedbackEvent("selectionEnd")
}
}
}
handleFeedbackEvent = (event) => {
if (typeof Haptics[event] === "function") {
return Haptics[event]()
}
}
isKeySelected = (key) => {
return this.state.selectedKeys.includes(key)
}
isAllSelected = () => {
return this.state.selectedKeys.length === this.props.items.length
}
selectAll = () => {
if (this.props.items.length > 0) {
let updatedSelectedKeys = [...this.props.items.map((item) => item.key ?? item.id ?? item._id)]
if (typeof this.props.disabledKeys !== "undefined") {
updatedSelectedKeys = updatedSelectedKeys.filter((key) => {
return !this.props.disabledKeys.includes(key)
})
}
this.handleFeedbackEvent("selectionChanged")
this.setState({
selectionEnabled: true,
selectedKeys: updatedSelectedKeys,
})
}
}
unselectAll = () => {
this.setState({
selectionEnabled: false,
selectedKeys: [],
})
}
selectKey = (key) => {
let list = this.state.selectedKeys ?? []
list.push(key)
this.handleFeedbackEvent("selectionChanged")
return this.setState({ selectedKeys: list })
}
unselectKey = (key) => {
let list = this.state.selectedKeys ?? []
list = list.filter((_key) => key !== _key)
this.handleFeedbackEvent("selectionChanged")
return this.setState({ selectedKeys: list })
}
onDone = () => {
if (typeof this.props.onDone === "function") {
this.props.onDone(this.state.selectedKeys)
}
this.unselectAll()
}
onDiscard = () => {
if (typeof this.props.onDiscard === "function") {
this.props.onDiscard(this.state.selectedKeys)
}
this.unselectAll()
}
onDoubleClickItem = (key) => {
if (typeof this.props.onDoubleClick === "function") {
this.props.onDoubleClick(key)
}
}
onClickItem = (key) => {
if (this.props.overrideSelectionEnabled || this.state.selectionEnabled) {
if (this.isKeySelected(key)) {
this.unselectKey(key)
} else {
this.selectKey(key)
}
} else {
if (typeof this.props.onClickItem === "function") {
this.props.onClickItem(key)
}
}
}
onLongPressItem = (key) => {
if (this.props.overrideSelectionEnabled) {
return false
}
if (!this.state.selectionEnabled) {
this.selectKey(key)
this.setState({ selectionEnabled: true })
}
}
renderProvidedActions = () => {
return this.props.actions.map((action) => {
return (
<div key={action.key}>
<Button
type={action.props.type}
shape={action.props.shape}
size={action.props.size}
style={{
...action.props.style,
}}
onClick={() => {
if (typeof this.props.events === "undefined") {
console.error("No events provided to SelectableList")
return false
}
if (typeof action.onClick === "function") {
action.onClick(this.state.selectedKeys)
}
if (typeof this.props.events[action.props.call] === "function") {
this.props.events[action.props.call]({
onDone: this.onDone,
onDiscard: this.onDiscard,
onCancel: this.onCancel,
selectKey: this.selectKey,
unselectKey: this.unselectKey,
selectAll: this.selectAll,
unselectAll: this.unselectAll,
isKeySelected: this.isKeySelected,
isAllSelected: this.isAllSelected,
}, this.state.selectedKeys)
}
}}
>
{action}
</Button>
</div>
)
})
}
getLongPressDelay = () => {
return window.app.settings.get("selection_longPress_timeout")
}
renderItems = (data) => {
return data.length > 0 ? data.map((item, index) => {
item.key = item.key ?? item.id ?? item._id
if (item.children && Array.isArray(item.children)) {
return <div className="selectableList_group">
<h1>
{React.isValidElement(item.icon) ? item.icon : Icons[item.icon] && createIconRender(item.icon)}
<Translation>
{t => t(item.label)}
</Translation>
</h1>
<div className="selectableList_subItems">
{this.renderItems(item.children)}
</div>
</div>
}
let selected = this.isKeySelected(item.key)
return <ListItem
item={item}
selected={selected}
longPressDelay={this.getLongPressDelay()}
onClickItem={this.onClickItem}
onDoubleClickItem={this.onDoubleClickItem}
onLongPressItem={this.onLongPressItem}
renderChildren={this.props.renderItem}
onlyClickSelection={this.props.onlyClickSelection || this.state.selectionEnabled}
/>
}) : <antd.Empty image={antd.Empty.PRESENTED_IMAGE_SIMPLE} />
}
render() {
if (!this.props.overrideSelectionEnabled && this.state.selectionEnabled && this.state.selectedKeys.length === 0) {
this.setState({ selectionEnabled: false })
this.unselectAll()
}
const isAllSelected = this.isAllSelected()
let items = this.renderItems(this.props.items)
return <div className={classnames("selectableList", { ["selectionEnabled"]: this.props.overrideSelectionEnabled ?? this.state.selectionEnabled })}>
<div className="selectableList_content">
{items}
</div>
{this.props.items.length > 0 && (this.props.overrideSelectionEnabled || this.state.selectionEnabled) && !this.props.actionsDisabled &&
<ActionsBar mode="float">
<div key="discard">
<Button
shape="round"
onClick={this.onDiscard}
{...this.props.onDiscardProps}
>
{this.props.onDiscardRender ?? <Icons.X />}
<Translation>
{(t) => t("Discard")}
</Translation>
</Button>
</div>
{this.props.bulkSelectionAction &&
<div key="allSelection">
<Button
shape="round"
onClick={() => isAllSelected ? this.unselectAll() : this.selectAll()}
>
<Translation>
{(t) => t(isAllSelected ? "Unselect all" : "Select all")}
</Translation>
</Button>
</div>}
{Array.isArray(this.props.actions) && this.renderProvidedActions()}
</ActionsBar>
}
</div>
}
}

View File

@ -0,0 +1,82 @@
@selectableList_item_borderColor_active: rgba(51, 51, 51, 1);
@selectableList_item_borderColor_normal: rgba(51, 51, 51, 0.3);
.selectableList {
.selectableList_content {
.selectableList_item {
--ignore-dragger: true;
display: inline-flex;
overflow-x: overlay;
align-items: center;
user-select: none;
--webkit-user-select: none;
width: 100%;
height: fit-content;
border: @selectableList_item_borderColor_normal 1px solid;
border-radius: 4px;
margin-bottom: 6px;
padding: 7px;
transition: all 150ms ease-in-out;
&.selected {
background-color: #f5f5f5;
transform: scale(0.98);
margin-bottom: 3px;
}
&.disabled {
opacity: 0.5;
pointer-events: none;
}
::-webkit-scrollbar {
position: absolute;
display: none;
width: 0;
height: 0;
z-index: 0;
}
}
.selectableList_item:active {
background-color: #f5f5f5;
transform: scale(0.98);
margin-bottom: 3px;
}
}
&.selectionEnabled {
.selectableList_content {
.selectableList_item {
cursor: pointer;
border: rgba(51, 51, 51, 0.3) 1px solid;
border-radius: 8px;
margin-bottom: 12px;
h1, h3 {
user-select: none;
--webkit-user-select: none;
}
}
}
}
}
.selectableList_group {
display: flex;
flex-direction: column;
.selectableList_subItems {
margin-left: 10px;
}
margin-bottom: 10px;
}

View File

@ -0,0 +1,244 @@
import React from "react"
import * as antd from "antd"
import loadable from "@loadable/component"
import { Translation } from "react-i18next"
import { Icons, createIconRender } from "components/Icons"
import { ActionsBar } from "components"
import "./index.less"
export default class StepsForm extends React.Component {
state = {
steps: [...(this.props.steps ?? []), ...(this.props.children ?? [])],
step: 0,
values: {},
canNext: true,
renderStep: null,
}
api = window.app.api.withEndpoints("main")
componentDidMount = async () => {
if (this.props.defaultValues) {
await this.setState({ values: this.props.defaultValues })
}
await this.handleNext(0)
}
next = (to) => {
if (!this.state.canNext) {
return antd.message.error("Please complete the step.")
}
return this.handleNext(to)
}
prev = () => this.handlePrev()
handleNext = (to) => {
const index = to ?? (this.state.step + 1)
this.setState({ step: index, renderStep: this.renderStep(index) })
}
handlePrev = () => {
this.handleNext(this.state.step - 1)
}
handleError = (error) => {
this.setState({ submitting: false, submittingError: error })
}
handleUpdate = (key, value) => {
this.setState({ values: { ...this.state.values, [key]: value } }, () => {
if (typeof this.props.onChange === "function") {
this.props.onChange(this.state.values)
}
})
}
handleValidation = (result) => {
this.setState({ canNext: result })
}
canSubmit = () => {
if (typeof this.props.canSubmit === "function") {
return this.props.canSubmit(this.state.values)
}
return true
}
onSubmit = async () => {
if (!this.state.canNext) {
console.warn("Cannot submit form, validation failed")
return false
}
if (typeof this.props.onSubmit === "function") {
this.setState({ submitting: true, submittingError: null })
await this.props.onSubmit(this.state.values).catch((error) => {
console.error(error)
this.handleError(error)
})
}
}
renderStep = (stepIndex) => {
const step = this.state.steps[stepIndex]
let content = step.content
let value = this.state.values[step.key]
if (typeof step.key === "undefined") {
console.error("[StepsForm] step.key is required")
return null
}
if (typeof step.required !== "undefined" && step.required) {
this.handleValidation(Boolean(value && value.length > 0))
} else {
this.setState({ canNext: true })
}
if (typeof step.stateValidation === "function") {
const validationResult = step.stateValidation(value)
this.handleValidation(validationResult)
}
const componentProps = {
handleUpdate: (to) => {
value = to
if (typeof step.onUpdateValue === "function") {
value = step.onUpdateValue(value, to)
}
let validationResult = true
if (typeof step.stateValidation === "function") {
validationResult = step.stateValidation(to)
}
if (typeof step.required !== "undefined" && step.required) {
validationResult = Boolean(to && to.length > 0)
}
this.handleUpdate(step.key, to)
this.handleValidation(validationResult)
},
handleError: (error) => {
if (typeof props.handleError === "function") {
this.handleError(error)
}
},
onPressEnter: () => this.next(),
value: value,
}
if (typeof step.content === "function") {
content = loadable(async () => {
try {
const component = React.createElement(step.content, componentProps)
return () => component
} catch (error) {
console.log(error)
antd.notification.error({
message: "Error",
description: "Error loading step content",
})
return () => <div>
<Icons.XCircle /> Error
</div>
}
}, {
fallback: <div>Loading...</div>,
})
}
return React.createElement(React.memo(content), componentProps)
}
render() {
if (this.state.steps.length === 0) {
return null
}
const steps = this.state.steps
const current = steps[this.state.step]
return (
<div className="steps_form">
<div className="steps_form steps">
<antd.Steps responsive={false} direction="horizontal" className="steps_form steps header" size="small" current={this.state.step}>
{steps.map(item => (
<antd.Steps.Step key={item.title} />
))}
</antd.Steps>
<div className="steps_form steps step">
<div className="title">
<h1>{current.icon && createIconRender(current.icon)}
<Translation>
{t => t(current.title)}
</Translation>
</h1>
<antd.Tag color={current.required ? "volcano" : "default"}>
<Translation>
{t => t(current.required ? "Required" : "Optional")}
</Translation>
</antd.Tag>
</div>
{current.description && <div className="description">
<Translation>
{t => t(current.description)}
</Translation>
</div>}
{this.state.renderStep}
</div>
</div>
{this.state.submittingError && (
<div style={{ color: "#f5222d" }}>
<Translation>
{t => t(String(this.state.submittingError))}
</Translation>
</div>
)}
<ActionsBar mode="float">
{this.state.step > 0 && (
<antd.Button style={{ margin: "0 8px" }} onClick={() => this.prev()}>
<Icons.ChevronLeft />
<Translation>
{t => t("Previous")}
</Translation>
</antd.Button>
)}
{this.state.step < steps.length - 1 && (
<antd.Button disabled={!this.state.canNext} type="primary" onClick={() => this.next()}>
<Icons.ChevronRight />
<Translation>
{t => t("Next")}
</Translation>
</antd.Button>
)}
{this.state.step === steps.length - 1 && (
<antd.Button disabled={!this.state.canNext || this.state.submitting || !this.canSubmit()} type="primary" onClick={this.onSubmit}>
{this.state.submitting && <Icons.LoadingOutlined spin />}
<Translation>
{t => t("Done")}
</Translation>
</antd.Button>
)}
</ActionsBar>
</div>
)
}
}

View File

@ -0,0 +1,91 @@
.steps_form {
.ant-steps-icon {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
svg {
margin: 0;
}
}
.steps {
display: flex;
flex-direction: column;
width: 100%;
.header {
//position: fixed;
width: 100%;
height: fit-content;
flex-direction: row;
}
.ant-select {
width: 100%;
}
.step {
padding: 0 10px;
display: inline-flex;
flex-direction: column;
width: 100%;
height: 100%;
align-items: flex-start;
h1 {
margin: 0;
}
.title {
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
width: 100%;
}
.description {
color: var(--background-color-contrast);
}
.content {
padding: 10px;
display: flex;
flex-direction: column;
align-items: center;
width: 100%;
.ant-list {
width: 100%;
}
}
.actions {
display: inline-flex;
flex-direction: row;
align-items: center;
justify-content: center;
> div {
margin-right: 10px;
}
}
> div {
margin-bottom: 0;
}
}
> div {
margin-bottom: 20px;
}
}
}

View File

@ -0,0 +1,122 @@
import React from "react"
import * as antd from "antd"
import { Translation } from "react-i18next"
import { SelectableList, Skeleton } from "components"
import { debounce } from "lodash"
import fuse from "fuse.js"
import "./index.less"
export default class UserSelector extends React.Component {
state = {
loading: true,
data: [],
searchValue: null,
}
api = window.app.api.withEndpoints("main")
componentDidMount = async () => {
this.toogleLoading(true)
await this.fetchUsers()
}
toogleLoading = (to) => {
this.setState({ loading: to ?? !this.state.loading })
}
fetchUsers = async () => {
const data = await this.api.get.users(undefined, { select: this.props.select }).catch((err) => {
console.error(err)
antd.message.error("Error fetching operators")
})
this.setState({ data: data, loading: false })
}
isExcludedId = (id) => {
if (this.props.excludedIds) {
return this.props.excludedIds.includes(id)
}
return false
}
renderItem = (item) => {
return <div disabled={this.isExcludedId(item._id)} className="user" >
<div><antd.Avatar shape="square" src={item.avatar} /></div>
<div><h1>{item.fullName ?? item.username}</h1></div>
</div>
}
search = (value) => {
if (typeof value !== "string") {
if (typeof value.target?.value === "string") {
value = value.target.value
}
}
if (value === "") {
return this.setState({ searchValue: null })
}
const searcher = new fuse(this.state.data, {
includeScore: true,
keys: ["username", "fullName"],
})
const result = searcher.search(value)
this.setState({
searchValue: result.map((entry) => {
return entry.item
}),
})
}
debouncedSearch = debounce((value) => this.search(value), 500)
onSearch = (event) => {
if (event === "" && this.state.searchValue) {
return this.setState({ searchValue: null })
}
this.debouncedSearch(event.target.value)
}
render() {
if (this.state.loading) {
return <Skeleton />
}
return <div className="users_selector">
<div className="users_selector header">
<div>
<antd.Input.Search
placeholder="Search"
allowClear
onSearch={this.onSearch}
onChange={this.onSearch}
/>
</div>
</div>
<SelectableList
onlyClickSelection
overrideSelectionEnabled
bulkSelectionAction
items={this.state.searchValue ?? this.state.data}
renderItem={this.renderItem}
actions={[
<div type="primary" call="onDone" key="done">
<Translation>
{t => t("Done")}
</Translation>
</div>
]}
events={{
onDone: (ctx, keys) => this.props.handleDone(keys),
}}
/>
</div>
}
}

View File

@ -0,0 +1,19 @@
.users_selector {
.header {
margin-bottom: 10px;
}
.user {
display: flex;
flex-direction: row;
align-items: center;
h1 {
margin: 0;
}
> div {
margin-right: 8px;
}
}
}

View File

@ -0,0 +1,17 @@
import * as Layout from "./Layout"
export { default as Footer } from "./Footer"
// COMPLEX COMPONENTS
export { default as FormGenerator } from "./FormGenerator"
export { default as NotFound } from "./NotFound"
export { default as RenderError } from "./RenderError"
export { default as SelectableList } from "./SelectableList"
export { default as ObjectInspector } from "./ObjectInspector"
export { default as ModifierTag } from "./ModifierTag"
export { default as StepsForm } from "./StepsForm"
export * as Crash from "./Crash"
export { default as Login } from "./Login"
export * as Window from "./RenderWindow"
export { Layout }

View File

@ -0,0 +1,262 @@
import Core from "evite/src/core"
import config from "config"
import { Bridge } from "linebridge/dist/client"
import { Session } from "models"
export default class ApiCore extends Core {
constructor(props) {
super(props)
this.namespaces = Object()
this.onExpiredExceptionEvent = false
this.excludedExpiredExceptionURL = ["/regenerate_session_token"]
this.ctx.registerPublicMethod("api", this)
}
async customRequest(
namepace = undefined,
payload = {
method: "GET",
},
...args
) {
if (typeof namepace === "undefined") {
throw new Error("Namespace must be defined")
}
if (typeof this.namespaces[namepace] === "undefined") {
throw new Error("Namespace not found")
}
if (typeof payload === "string") {
payload = {
url: payload,
}
}
if (typeof payload.headers !== "object") {
payload.headers = {}
}
const sessionToken = await Session.token
if (sessionToken) {
payload.headers["Authorization"] = `Bearer ${sessionToken}`
} else {
console.warn("Making a request with no session token")
}
return await this.namespaces[namepace].httpInterface(payload, ...args)
}
request = (namespace = "main", method, endpoint, ...args) => {
if (!this.namespaces[namespace]) {
throw new Error(`Namespace ${namespace} not found`)
}
if (!this.namespaces[namespace].endpoints[method]) {
throw new Error(`Method ${method} not found`)
}
if (!this.namespaces[namespace].endpoints[method][endpoint]) {
throw new Error(`Endpoint ${endpoint} not found`)
}
return this.namespaces[namespace].endpoints[method][endpoint](...args)
}
withEndpoints = (namespace = "main") => {
if (!this.namespaces[namespace]) {
throw new Error(`Namespace ${namespace} not found`)
}
return this.namespaces[namespace].endpoints
}
handleBeforeRequest = async (request) => {
if (this.onExpiredExceptionEvent) {
if (this.excludedExpiredExceptionURL.includes(request.url)) return
await new Promise((resolve) => {
app.eventBus.once("session.regenerated", () => {
console.log(`Session has been regenerated, retrying request`)
resolve()
})
})
}
}
handleRegenerationEvent = async (refreshToken, makeRequest) => {
window.app.eventBus.emit("session.expiredExceptionEvent", refreshToken)
this.onExpiredExceptionEvent = true
const expiredToken = await Session.token
// exclude regeneration endpoint
// send request to regenerate token
const response = await this.request("main", "post", "regenerateSessionToken", {
expiredToken: expiredToken,
refreshToken,
}).catch((error) => {
console.error(`Failed to regenerate token: ${error.message}`)
return false
})
if (!response) {
return window.app.eventBus.emit("session.invalid", "Failed to regenerate token")
}
// set new token
Session.token = response.token
//this.namespaces["main"].internalAbortController.abort()
this.onExpiredExceptionEvent = false
// emit event
window.app.eventBus.emit("session.regenerated")
}
connectBridge = (key, params) => {
this.namespaces[key] = this.createBridge(params)
}
createBridge(params = {}) {
const getSessionContext = async () => {
const obj = {}
const token = await Session.token
if (token) {
// append token to context
obj.headers = {
Authorization: `Bearer ${token ?? null}`,
}
}
return obj
}
const handleResponse = async (data, makeRequest) => {
// handle 401 responses
if (data instanceof Error) {
if (data.response.status === 401) {
// check if the server issue a refresh token on data
if (data.response.data.refreshToken) {
// handle regeneration event
await this.handleRegenerationEvent(data.response.data.refreshToken, makeRequest)
return await makeRequest()
} else {
return window.app.eventBus.emit("session.invalid", "Session expired, but the server did not issue a refresh token")
}
}
if (data.response.status === 403) {
return window.app.eventBus.emit("session.invalid", "Session not valid or not existent")
}
}
}
if (typeof params !== "object") {
throw new Error("Params must be an object")
}
const bridgeOptions = {
wsOptions: {
autoConnect: false,
},
onBeforeRequest: this.handleBeforeRequest,
onRequest: getSessionContext,
onResponse: handleResponse,
...params,
origin: params.httpAddress ?? config.remotes.mainApi,
}
const bridge = new Bridge(bridgeOptions)
// handle main ws events
const mainWSSocket = bridge.wsInterface.sockets["main"]
mainWSSocket.on("authenticated", () => {
console.debug("[WS] Authenticated")
})
mainWSSocket.on("authenticateFailed", (error) => {
console.error("[WS] Authenticate Failed", error)
})
mainWSSocket.on("connect", () => {
this.ctx.eventBus.emit(`api.ws.${mainWSSocket.id}.connect`)
})
mainWSSocket.on("disconnect", (...context) => {
this.ctx.eventBus.emit(`api.ws.${mainWSSocket.id}.disconnect`, ...context)
})
mainWSSocket.on("connect_error", (...context) => {
this.ctx.eventBus.emit(`api.ws.${mainWSSocket.id}.connect_error`, ...context)
})
// generate functions
bridge.listenEvent = this.generateMainWSEventListener(bridge.wsInterface)
bridge.unlistenEvent = this.generateMainWSEventUnlistener(bridge.wsInterface)
// return bridge
return bridge
}
generateMainWSEventListener(obj) {
return (to, fn) => {
if (typeof to === "undefined") {
console.error("handleWSListener: to must be defined")
return false
}
if (typeof fn !== "function") {
console.error("handleWSListener: fn must be function")
return false
}
let ns = "main"
let event = null
if (typeof to === "string") {
event = to
} else if (typeof to === "object") {
ns = to.ns
event = to.event
}
return obj.sockets[ns].on(event, async (...context) => {
return await fn(...context)
})
}
}
generateMainWSEventUnlistener(obj) {
return (to, fn) => {
if (typeof to === "undefined") {
console.error("handleWSListener: to must be defined")
return false
}
if (typeof fn !== "function") {
console.error("handleWSListener: fn must be function")
return false
}
let ns = "main"
let event = null
if (typeof to === "string") {
event = to
} else if (typeof to === "object") {
ns = to.ns
event = to.event
}
return obj.sockets[ns].removeListener(event, fn)
}
}
}

View File

@ -0,0 +1,271 @@
import Core from "evite/src/core"
import React from "react"
import { Howl } from "howler"
import { EmbbededMediaPlayer } from "components"
import { DOMWindow } from "components/RenderWindow"
export default class AudioPlayerCore extends Core {
audioMuted = false
audioVolume = 1
audioQueueHistory = []
audioQueue = []
currentAudio = null
currentDomWindow = null
preloadAudioDebounce = null
publicMethods = {
AudioPlayer: this,
}
async initialize() {
app.eventBus.on("audioPlayer.end", () => {
this.nextAudio()
})
}
toogleMute() {
this.audioMuted = !this.audioMuted
if (this.currentAudio) {
this.currentAudio.instance.mute(this.audioMuted)
}
// apply to all audio in queue
this.audioQueue.forEach((audio) => {
audio.instance.mute(this.audioMuted)
})
app.eventBus.emit("audioPlayer.muted", this.audioMuted)
return this.audioMuted
}
setVolume(volume) {
if (typeof volume !== "number") {
console.warn("Volume must be a number")
return false
}
if (volume > 1) {
volume = 1
}
if (volume < 0) {
volume = 0
}
this.audioVolume = volume
if (this.currentAudio) {
this.currentAudio.instance.volume(volume)
}
// apply to all audio in queue
this.audioQueue.forEach((audio) => {
audio.instance.volume(volume)
})
app.eventBus.emit("audioPlayer.volumeChanged", volume)
return volume
}
async preloadAudio() {
// debounce to prevent multiple preload
if (this.preloadAudioDebounce) {
clearTimeout(this.preloadAudioDebounce)
}
this.preloadAudioDebounce = setTimeout(async () => {
// load the first 2 audio in queue
const audioToLoad = this.audioQueue.slice(0, 2)
// filter undefined
const audioToLoadFiltered = audioToLoad.filter((audio) => audio.instance)
audioToLoad.forEach(async (audio) => {
const audioState = audio.instance.state()
if (audioState !== "loaded" && audioState !== "loading") {
await audio.instance.load()
}
})
}, 600)
}
startPlaylist = async (data) => {
if (typeof data === "undefined") {
console.warn("No data provided")
return false
}
if (!Array.isArray(data)) {
data = [data]
}
await this.clearAudioQueues()
this.attachEmbbededMediaPlayer()
for await (const item of data) {
const audioInstance = await this.createAudioInstance(item)
await this.audioQueue.push({
data: item,
instance: audioInstance,
})
}
await this.preloadAudio()
this.currentAudio = this.audioQueue.shift()
this.playCurrentAudio()
}
clearAudioQueues() {
if (this.currentAudio) {
this.currentAudio.instance.stop()
}
this.audioQueueHistory = []
this.audioQueue = []
this.currentAudio = null
}
async playCurrentAudio() {
if (!this.currentAudio) {
console.warn("No audio playing")
return false
}
const audioState = this.currentAudio.instance.state()
console.log(`Current Audio State: ${audioState}`)
// check if the instance is loaded
if (audioState !== "loaded") {
console.warn("Audio not loaded")
app.eventBus.emit("audioPlayer.loading", this.currentAudio)
await this.currentAudio.instance.load()
app.eventBus.emit("audioPlayer.loaded", this.currentAudio)
}
this.currentAudio.instance.play()
}
pauseAudioQueue() {
if (!this.currentAudio) {
console.warn("No audio playing")
return false
}
this.currentAudio.instance.pause()
}
previousAudio() {
// check if there is audio playing
if (this.currentAudio) {
this.currentAudio.instance.stop()
}
// check if there is audio in queue
if (!this.audioQueueHistory[0]) {
console.warn("No audio in queue")
return false
}
// move current audio to queue
this.audioQueue.unshift(this.currentAudio)
this.currentAudio = this.audioQueueHistory.pop()
this.playCurrentAudio()
}
nextAudio() {
// check if there is audio playing
if (this.currentAudio) {
this.currentAudio.instance.stop()
}
// check if there is audio in queue
if (!this.audioQueue[0]) {
console.warn("No audio in queue")
this.currentAudio = null
// if there is no audio in queue, close the embbeded media player
this.destroyPlayer()
return false
}
// move current audio to history
this.audioQueueHistory.push(this.currentAudio)
this.currentAudio = this.audioQueue.shift()
this.playCurrentAudio()
this.preloadAudio()
}
destroyPlayer() {
this.currentDomWindow.destroy()
this.currentDomWindow = null
}
async createAudioInstance(data) {
const audio = new Howl({
src: data.src,
preload: false,
//html5: true,
mute: this.audioMuted,
volume: this.audioVolume,
onplay: () => {
app.eventBus.emit("audioPlayer.playing", data)
},
onend: () => {
app.eventBus.emit("audioPlayer.end", data)
},
onload: () => {
app.eventBus.emit("audioPlayer.preloaded", data)
},
onpause: () => {
app.eventBus.emit("audioPlayer.paused", data)
},
onstop: () => {
app.eventBus.emit("audioPlayer.stopped", data)
},
onseek: () => {
app.eventBus.emit("audioPlayer.seeked", data)
},
onvolume: () => {
app.eventBus.emit("audioPlayer.volumeChanged", data)
},
})
return audio
}
attachEmbbededMediaPlayer() {
if (this.currentDomWindow) {
console.warn("EmbbededMediaPlayer already attached")
return false
}
this.currentDomWindow = new DOMWindow({
id: "mediaPlayer"
})
this.currentDomWindow.render(<EmbbededMediaPlayer />)
}
}

View File

@ -0,0 +1,71 @@
import Core from "evite/src/core"
import config from "config"
import i18n from "i18next"
import { initReactI18next } from "react-i18next"
export const SUPPORTED_LANGUAGES = config.i18n?.languages ?? {}
export const SUPPORTED_LOCALES = SUPPORTED_LANGUAGES.map((l) => l.locale)
export const DEFAULT_LOCALE = config.i18n?.defaultLocale
export function extractLocaleFromPath(path = "") {
const [_, maybeLocale] = path.split("/")
return SUPPORTED_LOCALES.includes(maybeLocale) ? maybeLocale : DEFAULT_LOCALE
}
const messageImports = import.meta.glob("./translations/*.json")
export default class I18nCore extends Core {
events = {
"changeLanguage": (locale) => {
this.loadAsyncLanguage(locale)
}
}
initialize = async () => {
let locale = app.settings.get("language") ?? DEFAULT_LOCALE
if (!SUPPORTED_LOCALES.includes(locale)) {
locale = DEFAULT_LOCALE
}
const messages = await this.importLocale(locale)
i18n
.use(initReactI18next) // passes i18n down to react-i18next
.init({
// debug: true,
resources: {
[locale]: { translation: messages.default || messages },
},
lng: locale,
//fallbackLng: DEFAULT_LOCALE,
interpolation: {
escapeValue: false, // react already safes from xss
},
})
}
importLocale = async (locale) => {
const [, importLocale] =
Object.entries(messageImports).find(([key]) =>
key.includes(`/${locale}.`)
) || []
return importLocale && importLocale()
}
loadAsyncLanguage = async function (locale) {
locale = locale ?? DEFAULT_LOCALE
try {
const result = await this.importLocale(locale)
if (result) {
i18n.addResourceBundle(locale, "translation", result.default || result)
i18n.changeLanguage(locale)
}
} catch (error) {
console.error(error)
}
}
}

View File

@ -0,0 +1,103 @@
{
"main_welcome": "Welcome back,",
"assigned_for_you": "Assigned for you",
"no_assigned_workorders": "No assigned workorders",
"new": "New",
"close": "Close",
"done": "Done",
"edit": "Edit",
"save": "Save",
"cancel": "Cancel",
"delete": "Delete",
"import": "Import",
"export": "Export",
"refresh": "Refresh",
"reload": "Reload",
"search": "Search",
"status": "Status",
"type": "Type",
"about": "About",
"current": "Current",
"statistics": "Statistics",
"name": "Name",
"username": "Username",
"email": "Email",
"password": "Password",
"sessions": "Sessions",
"compact_view": "Compact view",
"sign_in": "Sign in",
"sign_out": "Sign out",
"sign_up": "Sign up",
"all_sessions": "All sessions",
"destroy_all_sessions": "Destroy all sessions",
"account_info": "Account info",
"password_confirmation": "Password confirmation",
"new_product": "New product",
"description": "Description",
"describe_something": "Describe something",
"operations": "Operations",
"select_operation": "Select operation",
"select_operations": "Select operations",
"tasks": "Tasks",
"select_task": "Select task",
"select_tasks": "Select tasks",
"add_task": "Add task",
"add_tasks": "Add tasks",
"location": "Location",
"select_location": "Select location",
"select_locations": "Select locations",
"add_location": "Add location",
"add_locations": "Add locations",
"materials": "Materials",
"select_material": "Select material",
"select_materials": "Select materials",
"add_material": "Add material",
"add_materials": "Add materials",
"quantity": "Quantity",
"select_quantity": "Select quantity",
"select_quantities": "Select quantities",
"add_quantity": "Add quantity",
"add_quantities": "Add quantities",
"units": "Units",
"select_unit": "Select unit",
"select_units": "Select units",
"add_unit": "Add unit",
"add_units": "Add units",
"suppliers": "Suppliers",
"select_supplier": "Select supplier",
"select_suppliers": "Select suppliers",
"add_supplier": "Add supplier",
"add_suppliers": "Add suppliers",
"customers": "Customers",
"select_customer": "Select customer",
"select_customers": "Select customers",
"add_customer": "Add customer",
"add_customers": "Add customers",
"employees": "Employees",
"select_employee": "Select employee",
"select_employees": "Select employees",
"add_employee": "Add employee",
"add_employees": "Add employees",
"equipment": "Equipment",
"select_equipment": "Select equipment",
"select": "Select",
"variants": "Variants",
"select_variant": "Select variant",
"select_variants": "Select variants",
"settins_group_general": "General",
"settings_general_language": "Language",
"settings_general_language_description": "Choose language for using in application.",
"settings_general_sidebarAutoCollapse": "Sidebar auto collapse",
"settings_general_sidebarAutoCollapse_description": "Collapse sidebar when loose focus.",
"settings_group_aspect": "Aspect",
"settings_aspect_reduceAnimations": "Reduce animations",
"settings_aspect_reduceAnimations_description": "Reduce animation of the application.",
"settings_aspect_darkMode": "Dark mode",
"settings_aspect_darkMode_description": "Enable dark mode for the application.",
"settings_aspect_primaryColor": "Primary color",
"settings_aspect_primaryColor_description": "Change primary color of the application.",
"settings_aspect_resetTheme": "Reset theme",
"settings_aspect_resetTheme_description": "Reset theme to default."
}

View File

@ -0,0 +1,214 @@
{
"Dashboard": "Inicio",
"main_welcome": "Bienvenido,",
"assigned_for_you": "Asignado para usted",
"no_assigned_workorders": "No hay trabajos asignados",
"Start": "Iniciar",
"End": "Finalizar",
"Stop": "Parar",
"Started": "Iniciado",
"started": "iniciado",
"Ended": "Finalizado",
"ended": "finalizado",
"Expired": "Expirado",
"expired": "expirado",
"Stopped": "Parado",
"stopped": "parado",
"Pending": "Pendiente",
"pending": "pendiente",
"Finished": "Finalizado",
"finished": "terminado",
"Cancelled": "Cancelado",
"cancelled": "cancelado",
"Assigned": "Asignado",
"assigned": "asignado",
"Ready": "Listo",
"ready": "listo",
"No description": "Sin descripción",
"All": "Todos",
"all": "todos",
"or": "o",
"Browse": "Buscar",
"Create new": "Crear nuevo",
"New": "Nuevo",
"Close": "Cerrar",
"Done": "Listo",
"Next": "Siguiente",
"Previous": "Anterior",
"Schedule": "Plazo",
"Edit": "Modificar",
"Save": "Guardar",
"Cancel": "Cancelar",
"Delete": "Eliminar",
"State": "Estado",
"Modify": "Modificar",
"modify": "modificar",
"Notifications": "Notificaciones",
"Notification": "Notificación",
"Haptic": "Vibración",
"Haptic Feedback": "Vibración de respuesta",
"Enable haptic feedback on touch events.": "Habilitar vibración de respuesta cuando exista un evento de toque.",
"Selection press delay": "Retraso de presión de selección",
"Set the delay before the selection trigger is activated.": "Establecer el retraso antes de que el disparador de selección sea activado.",
"Force Mobile Mode": "Forzar modo móvil",
"Force the application to run in mobile mode.": "Forzar la aplicación a ejecutarse en modo móvil.",
"Manage operators": "Administrar operadores",
"Manage users": "Administrar usuarios",
"Manage groups": "Administrar grupos",
"Manage workflows": "Administrar flujos de trabajo",
"Manage roles": "Administrar roles",
"Manage permissions": "Administrar permisos",
"Disable": "Deshabilitar",
"Disabled": "Deshabilitado",
"Discard": "Descartar",
"Unselect all": "Deseleccionar todo",
"Select all": "Seleccionar todo",
"Add commit": "Añadir registro",
"Commit": "Registrar",
"Commits": "Registros",
"Assistant mode": "Modo asistente",
"View finished": "Ver terminados",
"View pending": "Ver pendientes",
"View assigned": "Ver asignados",
"View ready": "Ver listos",
"View cancelled": "Ver cancelados",
"View all": "Ver todos",
"View": "Ver",
"Mark produced quantity": "Marcar cantidad producida",
"Mark remaining amount": "Marcar cantidad restante",
"Quantity": "Cantidad",
"Quantity produced": "Cantidad producida",
"Quantity left": "Cantidad restante",
"Production target": "Objectivo de producción",
"Section": "Sección",
"Sections": "Secciones",
"Workshift": "Turno",
"workshift": "turno",
"Workshifts": "Turnos",
"workshifts": "turnos",
"Operation": "Operación",
"Operations": "Operaciones",
"Stock Target": "Stock objetivo",
"Vault item": "Artículo de bóveda",
"Stock item": "Artículo de stock",
"Vault": "Bóveda",
"Phase": "Fase",
"Variants": "Variantes",
"Variant": "Variante",
"Description": "Descripción",
"Task": "Tarea",
"Tasks": "Tareas",
"Product": "Producto",
"Products": "Productos",
"Operator": "Operador",
"Operators": "Operadores",
"Workload": "Carga de trabajo",
"workload": "carga de trabajo",
"Workloads": "Cargas de trabajo",
"workloads": "cargas de trabajo",
"Workorder": "Orden de trabajo",
"workorder": "orden de trabajo",
"Workorders": "Ordenes de trabajo",
"workorders": "ordenes de trabajo",
"Workpart": "Parte de trabajo",
"workpart": "parte de trabajo",
"Workparts": "Partes de trabajo",
"workparts": "parte de trabajo",
"Payload": "Carga",
"payload": "carga",
"Payloads": "Cargas",
"payloads": "carga",
"Commit all": "Registrar todo",
"Mark quantity": "Marcar cantidad",
"Mark": "Marcar",
"Marked": "Marcado",
"Marked quantity": "Cantidad marcada",
"Marked amount": "Cantidad marcada",
"Marked amount left": "Cantidad restante marcada",
"Marked amount produced": "Cantidad producida marcada",
"Marked amount remaining": "Cantidad restante marcada",
"Marked amount target": "Cantidad objetivo marcada",
"Marked amount stock": "Cantidad stock marcada",
"Notifications Sound": "Sonido de notificación",
"Play a sound when a notification is received.": "Reproducir un sonido cuando se recibe una notificación.",
"Vibration": "Vibración",
"Vibrate the device when a notification is received.": "Vibrar el dispositivo cuando se recibe una notificación.",
"Sound Volume": "Volumen de sonido",
"Set the volume of the sound when a notification is received.": "Establecer el volumen del sonido cuando se recibe una notificación.",
"Workorder Notifications": "Notificaciones de orden de trabajo",
"Display in-app notifications for workorders updates.": "Mostrar notificaciones para las actualizaciones de las ordenes de trabajo.",
"Accounts": "Cuentas",
"Import": "Importar",
"Export": "Exportar",
"Refresh": "Actualizar",
"Reload": "Recargar",
"Required": "Requerido",
"Optional": "Opcional",
"Search": "Buscar",
"Status": "Estado",
"Type": "Tipo",
"About": "Acerca de",
"Current": "Actual",
"Statistics": "Estadísticas",
"Name": "Nombre",
"Users": "Usuarios",
"Username": "Nombre de usuario",
"Settings": "Configuración",
"Email": "Correo electrónico",
"Password": "Contraseña",
"Sessions": "Sesiones",
"Compact view": "Vista compacta",
"Add to catalog": "Añadir al catálogo",
"Fabric": "Fabric",
"Press and hold for 2 seconds to toggle running": "Pulse y mantenga pulsado durante 2 segundos para alternar el funcionamiento",
"Production quantity already has been reached": "La cantidad de producción ya ha sido alcanzada",
"Production quantity is not enough": "La cantidad de producción no es suficiente",
"Are you sure you want to commit for this workpart?": "¿Está seguro de que desea consolidar esta parte de trabajo?",
"Are you sure you want to commit all quantity left?": "¿Está seguro de que desea consolidar toda la cantidad restante?",
"This will commit all quantity left and finish the production for this workload.": "Esto consolidará toda la cantidad restante y terminará la producción para esta carga de trabajo.",
"Are you sure you want to commit for this workorder?": "¿Está seguro de que desea consolidar esta orden de trabajo?",
"Enter the name or a reference for the workorder.": "Introduzca el nombre o una referencia para la orden de trabajo.",
"Select the section where the workorder will be deployed.": "Seleccione la sección donde se desplegará la orden de trabajo.",
"Select the schedule for the workorder.": "Seleccione el plazo para la orden de trabajo.",
"Assign the operators for the workorder.": "Asigne los operadores para la orden de trabajo.",
"Define the payloads for the workorder.": "Defina las cargas para la orden de trabajo.",
"Define the workloads for the workorder.": "Defina las cargas de trabajo para la orden de trabajo.",
"Leaving process running on background, dont forget to stop it when you are done": "Dejando el proceso en ejecución en segundo plano, no olvide detenerlo cuando haya terminado",
"Task remains opened, dont forget to stop it when you are done": "La tarea permanece abierta, no olvide detenerla cuando haya terminado",
"Select a option": "Seleccione una opción",
"Set the quantity produced": "Marque la cantidad producida",
"Experimental": "Experimental",
"New workorder assigned": "Nueva orden de trabajo asignada",
"Check the new list of workorder": "Compruebe la nueva lista de ordenes de trabajo",
"Do you want to delete these items?": "¿Desea eliminar estos elementos?",
"This action cannot be undone, and will permanently delete the selected items.": "Esta acción no se puede deshacer, y eliminará permanentemente los elementos seleccionados.",
"Assigned operators": "Operadores asignados",
"Assigments": "Asignaciones",
"Working Tasks": "Tareas en ejecución",
"You are not working on any task": "No estás trabajando en ninguna tarea",
"Update": "Actualizar",
"Update status": "Actualizar estado",
"Archived": "Archivado",
"archived": "archivado",
"Archive": "Archivar",
"archive": "archivar",
"General": "General",
"Sidebar": "Barra lateral",
"Aspect": "Aspecto",
"Language": "Idioma",
"Choose a language for the application": "Elige un idioma para la aplicación.",
"Edit Sidebar": "Editar barra lateral",
"Auto Collapse": "Auto colapsar",
"Collapse the sidebar when loose focus": "Colapsar la barra lateral cuando pierda el foco.",
"Reduce animation": "Reducir animación",
"Primary color": "Color primario",
"Change primary color of the application.": "Cambia el color primario de la aplicación.",
"Dark mode": "Modo oscuro",
"Images": "Imágenes",
"Add others": "Añadir otros",
"Export tokens": "Exportar bonos de trabajo",
"Description of the task. It should be a general description of the product. Do not include information that may vary. e.g. 'The product is a white shirt with a elastic red collar, size M'": "Descripción de la tarea. Debe ser una descripción general del producto. No incluya información que pueda variar. Por ejemplo, 'El producto es una camisa blanca con un collar de color rojo, tamaño M'",
"Define variants for this item. Only the types of variations that may exist of a product should be included. e.g. Size, Color, Material, etc.": "Defina las variantes para este artículo. Sólo deben incluirse los tipos de variaciones que pueden existir de un producto. Por ejemplo, Tamaño, Color, Material, etc.",
"Append some images to describe this item.": "Agregue algunas imágenes para describir este artículo."
}

View File

@ -0,0 +1,25 @@
import SettingsCore from "./settings"
import APICore from "./api"
import StyleCore from "./style"
import PermissionsCore from "./permissions"
import I18nCore from "./i18n"
import NotificationsCore from "./notifications"
import ShortcutsCore from "./shortcuts"
import SoundCore from "./sound"
import AudioPlayer from "./audioPlayer"
// DEFINE LOAD ORDER HERE
export default [
SettingsCore,
APICore,
PermissionsCore,
StyleCore,
I18nCore,
SoundCore,
NotificationsCore,
ShortcutsCore,
AudioPlayer,
]

View File

@ -0,0 +1,74 @@
import Core from "evite/src/core"
import React from "react"
import { notification as Notf } from "antd"
import { Icons, createIconRender } from "components/Icons"
import { Translation } from "react-i18next"
import { Haptics } from "@capacitor/haptics"
export default class NotificationCore extends Core {
events = {
"changeNotificationsSoundVolume": (value) => {
this.playAudio({ soundVolume: value })
},
"changeNotificationsVibrate": (value) => {
this.playHaptic({
vibrationEnabled: value,
})
}
}
publicMethods = {
notification: this
}
getSoundVolume = () => {
return (window.app.settings.get("notifications_sound_volume") ?? 50) / 100
}
new = (notification, options = {}) => {
this.notify(notification, options)
this.playHaptic(options)
this.playAudio(options)
}
notify = (notification, options = {}) => {
if (typeof notification === "string") {
notification = {
title: "New notification",
description: notification
}
}
Notf.open({
message: <Translation>
{(t) => t(notification.title)}
</Translation>,
description: <Translation>
{(t) => t(notification.description)}
</Translation>,
duration: notification.duration ?? 4,
icon: React.isValidElement(notification.icon) ? notification.icon : (createIconRender(notification.icon) ?? <Icons.Bell />),
})
}
playHaptic = async (options = {}) => {
const vibrationEnabled = options.vibrationEnabled ?? window.app.settings.get("notifications_vibrate")
if (vibrationEnabled) {
await Haptics.vibrate()
}
}
playAudio = (options = {}) => {
const soundEnabled = options.soundEnabled ?? window.app.settings.get("notifications_sound")
const soundVolume = options.soundVolume ? options.soundVolume / 100 : this.getSoundVolume()
if (soundEnabled) {
if (typeof window.app.sound?.play === "function") {
window.app.sound.play("notification", {
volume: soundVolume,
})
}
}
}
}

View File

@ -0,0 +1,43 @@
import Core from "evite/src/core"
import UserModel from "models/user"
export default class PermissionsCore extends Core {
publicMethods = {
permissions: this
}
isUserAdmin = "unchecked"
// this will works with a newer version of evite
async initializeBeforeRuntimeInit() {
this.isUserAdmin = await UserModel.hasAdmin()
}
hasAdmin = async () => {
return await UserModel.hasAdmin()
}
hasPermission = async (permission) => {
let query = []
if (Array.isArray(permission)) {
query = permission
} else {
query = [permission]
}
// create a promise and check if the user has all the permission in the query
const result = await Promise.all(query.map(async (permission) => {
const hasPermission = await UserModel.hasRole(permission)
return hasPermission
}))
// if the user has all the permission in the query, return true
if (result.every((hasPermission) => hasPermission)) {
return true
}
return false
}
}

View File

@ -0,0 +1,76 @@
import Core from "evite/src/core"
import store from "store"
import defaultSettings from "schemas/defaultSettings.json"
import { Observable } from "rxjs"
export default class SettingsCore extends Core {
storeKey = "app_settings"
settings = store.get(this.storeKey) ?? {}
publicMethods = {
settings: this
}
initialize() {
this.fulfillUndefinedWithDefaults()
}
fulfillUndefinedWithDefaults = () => {
Object.keys(defaultSettings).forEach((key) => {
const value = defaultSettings[key]
// Only set default if value is undefined
if (typeof this.settings[key] === "undefined") {
this.settings[key] = value
}
})
}
is = (key, value) => {
return this.settings[key] === value
}
set = (key, value) => {
this.settings[key] = value
store.set(this.storeKey, this.settings)
window.app.eventBus.emit("setting.update", { key, value })
window.app.eventBus.emit(`setting.update.${key}`, value)
return this.settings
}
get = (key) => {
if (typeof key === "undefined") {
return this.settings
}
return this.settings[key]
}
getDefaults = (key) => {
if (typeof key === "undefined") {
return defaultSettings
}
return defaultSettings[key]
}
withEvent = (listenEvent, defaultValue) => {
let value = defaultValue ?? this.settings[key] ?? false
const observable = new Observable((subscriber) => {
subscriber.next(value)
window.app.eventBus.on(listenEvent, (to) => {
value = to
subscriber.next(value)
})
})
return observable.subscribe((value) => {
return value
})
}
}

View File

@ -0,0 +1,74 @@
import Core from "evite/src/core"
export default class ShortcutsCore extends Core {
shortcuts = {}
publicMethods = {
shortcuts: this
}
initialize() {
document.addEventListener("keydown", this.handleEvent)
}
handleEvent = (event) => {
// FIXME: event.key sometimes is not defined
//event.key = event.key.toLowerCase()
const shortcut = this.shortcuts[event.key]
if (shortcut) {
if (typeof shortcut.ctrl === "boolean" && event.ctrlKey !== shortcut.ctrl) {
return
}
if (typeof shortcut.shift === "boolean" && event.shiftKey !== shortcut.shift) {
return
}
if (typeof shortcut.alt === "boolean" && event.altKey !== shortcut.alt) {
return
}
if (typeof shortcut.meta === "boolean" && event.metaKey !== shortcut.meta) {
return
}
if (shortcut.preventDefault) {
event.preventDefault()
}
if (typeof shortcut.fn === "function") {
shortcut.fn()
}
}
}
register = (keybind = {}, fn) => {
if (typeof keybind === "string") {
keybind = {
key: keybind,
}
}
this.shortcuts[keybind.key] = {
...keybind,
fn,
}
}
remove = (array) => {
if (typeof array === "string") {
array = [array]
}
array.forEach(key => {
delete this.shortcuts[key]
})
}
window = {
ShortcutsController: this
}
}

View File

@ -0,0 +1,41 @@
import Core from "evite/src/core"
import { Howl } from "howler"
import config from "config"
export default class SoundCore extends Core {
sounds = {}
publicMethods = {
sound: this,
}
async initialize() {
this.sounds = await this.getSounds()
}
getSounds = async () => {
// TODO: Load custom soundpacks manifests
let soundPack = config.defaultSoundPack ?? {}
Object.keys(soundPack).forEach((key) => {
const src = soundPack[key]
soundPack[key] = (options) => new Howl({
volume: window.app.settings.get("generalAudioVolume") ?? 0.5,
...options,
src: [src],
})
})
return soundPack
}
play = (name, options) => {
if (this.sounds[name]) {
return this.sounds[name](options).play()
} else {
console.error(`Sound [${name}] not found or is not available.`)
return false
}
}
}

View File

@ -0,0 +1,199 @@
import Core from "evite/src/core"
import config from "config"
import store from "store"
import { ConfigProvider } from "antd"
export default class StyleCore extends Core {
themeManifestStorageKey = "theme"
modificationStorageKey = "themeModifications"
theme = null
mutation = null
currentVariant = null
events = {
"style.compactMode": (value = !window.app.settings.get("style.compactMode")) => {
if (value) {
return this.update({
layoutMargin: 0,
layoutPadding: 0,
})
}
return this.update({
layoutMargin: this.getValue("layoutMargin"),
layoutPadding: this.getValue("layoutPadding"),
})
},
"style.autoDarkModeToogle": (value) => {
if (value === true) {
this.handleAutoColorScheme()
} else {
this.applyVariant(this.getStoragedVariant())
}
},
"theme.applyVariant": (value) => {
this.applyVariant(value)
this.setVariant(value)
},
"modifyTheme": (value) => {
this.update(value)
this.setModifications(this.mutation)
},
"resetTheme": () => {
this.resetDefault()
}
}
publicMethods = {
style: this
}
static get currentVariant() {
return document.documentElement.style.getPropertyValue("--themeVariant")
}
handleAutoColorScheme() {
const prefered = window.matchMedia("(prefers-color-scheme: light)")
if (!prefered.matches) {
this.applyVariant("dark")
} else {
this.applyVariant("light")
}
}
initialize = async () => {
let theme = this.getStoragedTheme()
const modifications = this.getStoragedModifications()
const variantKey = this.getStoragedVariant()
if (!theme) {
// load default theme
theme = this.getDefaultTheme()
} else {
// load URL and initialize theme
}
// set global theme
this.theme = theme
// override with static vars
if (theme.staticVars) {
this.update(theme.staticVars)
}
// override theme with modifications
if (modifications) {
this.update(modifications)
}
// apply variation
this.applyVariant(variantKey)
// handle auto prefered color scheme
window.matchMedia("(prefers-color-scheme: light)").addListener(() => {
console.log(`[THEME] Auto color scheme changed`)
if (window.app.settings.get("auto_darkMode")) {
this.handleAutoColorScheme()
}
})
if (window.app.settings.get("auto_darkMode")) {
this.handleAutoColorScheme()
}
}
getRootVariables = () => {
let attributes = document.documentElement.getAttribute("style").trim().split(";")
attributes = attributes.slice(0, (attributes.length - 1))
attributes = attributes.map((variable) => {
let [key, value] = variable.split(":")
key = key.split("--")[1]
return [key, value]
})
return Object.fromEntries(attributes)
}
getDefaultTheme = () => {
// TODO: Use evite CONSTANTS_API
return config.defaultTheme
}
getStoragedTheme = () => {
return store.get(this.themeManifestStorageKey)
}
getStoragedModifications = () => {
return store.get(this.modificationStorageKey) ?? {}
}
getStoragedVariant = () => {
return app.settings.get("themeVariant")
}
getValue = (key) => {
if (typeof key === "undefined") {
return {
...staticValues,
...storagedModifications
}
}
const storagedModifications = this.getStoragedModifications()
const staticValues = this.theme.staticVars
return storagedModifications[key] || staticValues[key]
}
setVariant = (variationKey) => {
return app.settings.set("themeVariant", variationKey)
}
setModifications = (modifications) => {
return store.set(this.modificationStorageKey, modifications)
}
resetDefault = () => {
store.remove(this.themeManifestStorageKey)
store.remove(this.modificationStorageKey)
window.app.settings.set("primaryColor", this.theme.staticVars.primaryColor)
this.initialize()
}
update = (update) => {
if (typeof update !== "object") {
return false
}
this.mutation = {
...this.theme.staticVars,
...this.mutation,
...update
}
Object.keys(this.mutation).forEach(key => {
document.documentElement.style.setProperty(`--${key}`, this.mutation[key])
})
document.documentElement.className = `theme-${this.currentVariant}`
document.documentElement.style.setProperty(`--themeVariant`, this.currentVariant)
ConfigProvider.config({ theme: this.mutation })
}
applyVariant = (variant = (this.theme.defaultVariant ?? "light")) => {
const values = this.theme.variants[variant]
if (values) {
this.currentVariant = variant
this.update(values)
}
}
}

View File

@ -0,0 +1,124 @@
import React from "react"
import * as antd from "antd"
import progressBar from "nprogress"
import config from "config"
import routes from "schemas/routes"
import Layouts from "layouts"
export default class Layout extends React.Component {
progressBar = progressBar.configure({ parent: "html", showSpinner: false })
state = {
layoutType: "default",
renderLock: true,
renderError: null,
}
events = {
"app.initialization.start": () => {
this.setState({
renderLock: true,
})
},
"app.initialization.finish": () => {
this.setState({
renderLock: false,
})
},
"router.transitionStart": () => {
this.progressBar.start()
},
"router.transitionFinish": () => {
this.progressBar.done()
},
}
componentDidMount() {
// register events
Object.keys(this.events).forEach((event) => {
window.app.eventBus.on(event, this.events[event])
})
}
componentWillUnmount() {
// unregister events
Object.keys(this.events).forEach((event) => {
window.app.eventBus.off(event, this.events[event])
})
}
componentDidCatch(info, stack) {
this.setState({ renderError: { info, stack } })
}
setLayout = (layout) => {
if (typeof Layouts[layout] === "function") {
return this.setState({
layoutType: layout,
})
}
return console.error("Layout type not found")
}
render() {
let layoutType = this.state.layoutType
const InitializationComponent = this.props.staticRenders?.Initialization ? React.createElement(this.props.staticRenders.Initialization) : null
if (this.state.renderError) {
if (this.props.staticRenders?.RenderError) {
return React.createElement(this.props.staticRenders?.RenderError, { error: this.state.renderError })
}
return JSON.stringify(this.state.renderError)
}
console.debug(`Rendering layout [${this.state.layoutType}] for current route [${window.location.pathname}]`)
// check with the current route if it's a protected route or requires some permissions
const routeDeclaration = routes.find((route) => route.path === window.location.pathname)
if (routeDeclaration) {
if (typeof routeDeclaration.requiredRoles !== "undefined") {
const isAdmin = this.props.user?.roles?.includes("admin") ?? false
if (!isAdmin && !routeDeclaration.requiredRoles.some((role) => this.props.user?.roles?.includes(role))) {
return <antd.Result
status="403"
title="403"
subTitle="Sorry, you are not authorized to access this page."
extra={<antd.Button type="primary" onClick={() => window.app.setLocation("/")}>Back Home</antd.Button>}
/>
}
}
if (typeof routeDeclaration.useLayout !== "undefined") {
layoutType = routeDeclaration.useLayout
}
if (typeof routeDeclaration.webTitleAddition !== "undefined") {
document.title = `${routeDeclaration.webTitleAddition} - ${config.app.siteName}`
} else {
document.title = config.app.siteName
}
}
const layoutComponentProps = {
...this.props.bindProps,
...this.state,
}
const Layout = Layouts[layoutType]
if (!Layout) {
return app.eventBus.emit("runtime.crash", new Error(`Layout type [${layoutType}] not found`))
}
return <Layout {...layoutComponentProps}>
{this.state.renderLock ? InitializationComponent : this.props.children}
</Layout>
}
}

View File

@ -0,0 +1,24 @@
import React from "react"
import classnames from "classnames"
import { Layout } from "antd"
import { Sidebar, Drawer, Sidedrawer, Modal } from "components/Layout"
export default (props) => {
return <>
<div className="app_background_decorator" />
<Layout className="app_layout" style={{ height: "100%" }}>
<Modal />
<Drawer />
<Sidebar user={props.user} />
<Sidedrawer />
<Layout className="content_layout">
<Layout.Content className={classnames("layout_page", ...props.layoutPageModesClassnames ?? [])}>
<div id="transitionLayer" className="fade-transverse-active">
{React.cloneElement(props.children, props)}
</div>
</Layout.Content>
</Layout>
</Layout>
</>
}

View File

@ -0,0 +1,7 @@
import Default from "./default"
import Login from "./login"
export default {
default: Default,
login: Login,
}

View File

@ -0,0 +1,13 @@
import React from "react"
import classnames from "classnames"
import * as antd from "antd"
import { Drawer, Sidedrawer } from "components/Layout"
export default (props) => {
return <antd.Layout className="app_layout" style={{ height: "100%" }}>
<Drawer />
<Sidedrawer />
{React.cloneElement(props.children, props)}
</antd.Layout>
}

View File

@ -0,0 +1,2 @@
export { default as Session } from "./session"
export { default as User } from "./user"

View File

@ -0,0 +1,127 @@
import cookies from "js-cookie"
import jwt_decode from "jwt-decode"
import config from "config"
export default class Session {
static get bridge() {
return window.app?.api.withEndpoints("main")
}
static tokenKey = config.app?.storage?.token ?? "token"
static get token() {
return cookies.get(this.tokenKey)
}
static set token(token) {
return cookies.set(this.tokenKey, token)
}
static async delToken() {
return cookies.remove(Session.tokenKey)
}
static async decodedToken() {
const token = await this.token
return token && jwt_decode(token)
}
//* BASIC HANDLERS
login = (payload, callback) => {
const body = {
username: payload.username, //window.btoa(payload.username),
password: payload.password, //window.btoa(payload.password),
}
return this.generateNewToken(body, (err, res) => {
if (typeof callback === "function") {
callback(err, res)
}
if (!err || res.status === 200) {
let token = res.data
if (typeof token === "object") {
token = token.token
}
Session.token = token
window.app.eventBus.emit("session.created")
}
})
}
logout = async () => {
await this.destroyCurrentSession()
this.forgetLocalSession()
}
//* GENERATORS
generateNewToken = async (payload, callback) => {
const request = await Session.bridge.post.login(payload, undefined, {
parseData: false
})
if (typeof callback === "function") {
callback(request.error, request.response)
}
return request
}
//* GETTERS
getAllSessions = async () => {
return await Session.bridge.get.sessions()
}
getTokenInfo = async () => {
const session = await Session.token
return await Session.bridge.post.validateSession({ session })
}
getCurrentSession = async () => {
return await Session.bridge.get.currentSession()
}
isCurrentTokenValid = async () => {
const health = await this.getTokenInfo()
return health.valid
}
forgetLocalSession = () => {
return Session.delToken()
}
destroyAllSessions = async () => {
const session = await Session.decodedToken()
if (!session) {
return false
}
const result = await Session.bridge.delete.sessions({ user_id: session.user_id })
this.forgetLocalSession()
window.app.eventBus.emit("session.destroyed")
return result
}
destroyCurrentSession = async () => {
const token = await Session.token
const session = await Session.decodedToken()
if (!session || !token) {
return false
}
const result = await Session.bridge.delete.session({ user_id: session.user_id, token: token })
this.forgetLocalSession()
window.app.eventBus.emit("session.destroyed")
return result
}
logout = this.destroyCurrentSession
}

View File

@ -0,0 +1,63 @@
import Session from "../session"
export default class User {
static get bridge() {
return window.app?.api.withEndpoints("main")
}
static async data() {
const token = await Session.decodedToken()
if (!token || !User.bridge) {
return false
}
return User.bridge.get.user(undefined, { username: token.username, _id: token.user_id })
}
static async roles() {
const token = await Session.decodedToken()
if (!token || !User.bridge) {
return false
}
return User.bridge.get.userRoles(undefined, { username: token.username })
}
static async hasRole(role) {
const roles = await User.roles()
if (!roles) {
return false
}
return Array.isArray(roles) && roles.includes(role)
}
static async selfUserId() {
const token = await Session.decodedToken()
if (!token) {
return false
}
return token.user_id
}
static async hasAdmin() {
return User.hasRole("admin")
}
getData = async (payload, callback) => {
const request = await User.bridge.get.user(undefined, { username: payload.username, _id: payload.user_id }, {
parseData: false
})
if (typeof callback === "function") {
callback(request.error, request.response)
}
return request.response.data
}
}

View File

@ -0,0 +1,49 @@
import React from "react"
import * as antd from "antd"
import { Icons, createIconRender } from "components/Icons"
import "./index.less"
const toolMap = {
userTools: {
label: "User Tools",
icon: "user",
children: [
{
label: "User List",
icon: "user",
path: "/administration/users/list",
}
]
}
}
export default (props) => {
const generateMenu = (toolMap) => {
return Object.keys(toolMap).map((tool) => {
const toolData = toolMap[tool]
return (
<antd.Menu.Item key={tool}>
{createIconRender(toolData.icon)}
<span>{toolData.label}</span>
</antd.Menu.Item>
)
})
}
return <div className="administation">
<h1>Administration</h1>
<div className="menus">
<antd.Menu
mode="inline"
defaultSelectedKeys={["userTools"]}
defaultOpenKeys={["userTools"]}
style={{ height: "100%", borderRight: 0 }}
>
{generateMenu(toolMap)}
</antd.Menu>
</div>
</div>
}

View File

@ -0,0 +1,13 @@
import React from "react"
export default (props) => {
const [roles, setRoles] = React.useState(null)
const getRoles = () => {
}
return <div>
</div>
}

View File

@ -0,0 +1,93 @@
import React from "react"
import * as antd from "antd"
import { Icons } from "components/Icons"
import { ActionsBar, SelectableList } from "components"
import "./index.less"
export default class Users extends React.Component {
state = {
data: null,
selectionEnabled: false,
}
api = window.app.api.withEndpoints("main")
componentDidMount = async () => {
await this.loadData()
}
loadData = async () => {
this.setState({ data: null })
const data = await this.api.get.users()
this.setState({ data })
}
toogleSelection = (to) => {
this.setState({ selectionEnabled: to ?? !this.state.selectionEnabled })
}
openUser(username) {
if (this.state.selectionEnabled) {
return false
}
window.app.setLocation(`/@${username}`)
}
renderRoles(roles) {
return roles.map((role) => {
return <antd.Tag key={role}> {role} </antd.Tag>
})
}
renderItem = (item) => {
return (
<div
key={item._id}
onDoubleClick={() => this.openUser(item.username)}
className="user_item"
>
<div>
<antd.Avatar shape="square" src={item.avatar} />
</div>
<div className="title">
<div className="line">
<div>
<h1>{item.fullName ?? item.username}</h1>
</div>
<div>
<h3>#{item._id}</h3>
</div>
</div>
<div>{this.renderRoles(item.roles)}</div>
</div>
</div>
)
}
render() {
return (
<div>
<div className="users_list">
<ActionsBar mode="float">
<div>
<antd.Button shape="round" icon={this.state.selectionEnabled ? <Icons.Check /> : <Icons.MousePointer />} type={this.state.selectionEnabled ? "default" : "primary"} onClick={() => this.toogleSelection()}>
{this.state.selectionEnabled ? "Done" : "Select"}
</antd.Button>
</div>
<div>
<antd.Button type="primary" icon={<Icons.Plus />}>New User</antd.Button>
</div>
</ActionsBar>
{!this.state.data ? <antd.Skeleton active /> :
<SelectableList
selectionEnabled={this.state.selectionEnabled}
items={this.state.data}
renderItem={this.renderItem}
/>}
</div>
</div>
)
}
}

View File

@ -0,0 +1,52 @@
.users_list {
display: flex;
flex-direction: column;
> div {
margin-bottom: 20px;
}
.selectableList_item {
padding: 0;
}
}
.user_item {
display: flex;
> div {
margin: 7px;
}
.title {
width: 100%;
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
h1 {
cursor: text;
margin: 0;
font-size: 16px;
user-select: all;
}
h3 {
font-family: "Roboto Mono", monospace !important;
cursor: text;
margin: 0;
font-size: 13px;
user-select: all;
}
.line {
display: flex;
flex-direction: row;
align-items: center;
> div {
margin-right: 8px;
}
}
}
}

View File

@ -0,0 +1,154 @@
import React from "react"
import { Switch, Route, BrowserRouter, withRouter } from "react-router-dom"
const NotFoundRender = () => {
return <div>Not found</div>
}
const JSXRoutes = import.meta.glob("/src/pages/**/[a-z[]*.jsx")
const TSXRoutes = import.meta.glob("/src/pages/**/[a-z[]*.tsx")
const scriptRoutes = {
...JSXRoutes,
...TSXRoutes,
}
const routes = Object.keys(scriptRoutes).map((route) => {
const path = route
.replace(/\/src\/pages|index|\.jsx$/g, "")
.replace(/\[\.{3}.+\]/, "*")
.replace(/\[(.+)\]/, ":$1")
return { path, component: React.lazy(scriptRoutes[route]) }
})
export function BindContexts(component) {
let contexts = {
main: {},
app: {},
}
if (typeof component.bindApp === "string") {
if (component.bindApp === "all") {
Object.keys(app).forEach((key) => {
contexts.app[key] = app[key]
})
}
} else {
if (Array.isArray(component.bindApp)) {
component.bindApp.forEach((key) => {
contexts.app[key] = app[key]
})
}
}
if (typeof component.bindMain === "string") {
if (component.bindMain === "all") {
Object.keys(main).forEach((key) => {
contexts.main[key] = main[key]
})
}
} else {
if (Array.isArray(component.bindMain)) {
component.bindMain.forEach((key) => {
contexts.main[key] = main[key]
})
}
}
return (props) => React.createElement(component, { ...props, contexts })
}
export const Router = withRouter((props) => {
const defaultTransitionDelay = 150
const forceUpdate = React.useReducer(() => ({}))[1]
React.useEffect(() => {
props.history.listen((event) => {
if (typeof props.onTransitionFinish === "function") {
props.onTransitionFinish(event)
}
window.app.eventBus.emit("router.transitionFinish", event)
})
props.history.setLocation = (to, state = {}, delay = 150) => {
// clean double slashes
to = to.replace(/\/{2,}/g, "/")
// if state is a number, it's a delay
if (typeof state !== "object") {
delay = state
state = {}
}
const lastLocation = props.history.lastLocation
if (typeof lastLocation !== "undefined" && lastLocation?.pathname === to && lastLocation?.state === state) {
return false
}
if (typeof props.onTransitionStart === "function") {
props.onTransitionStart(delay)
}
window.app.eventBus.emit("router.transitionStart", delay)
setTimeout(() => {
props.history.push({
pathname: to,
}, state)
props.history.lastLocation = window.location
}, delay ?? defaultTransitionDelay)
}
window.app.eventBus.on(`router.forceUpdate`, forceUpdate)
props.history.lastLocation = window.location
window.app.setLocation = props.history.setLocation
}, [])
const router = {
history: props.history,
lastLocation: props.history.lastLocation,
forceUpdate,
}
// return children with router in props
return React.cloneElement(props.children, { router })
})
export const InternalRouter = (props) => {
return <BrowserRouter>
<Router {...props} />
</BrowserRouter>
}
export const PageRender = (props) => {
return <React.Suspense fallback={props.staticRenders?.PageLoad ? React.createElement(props.staticRenders?.PageLoad) : "Loading..."}>
<Switch>
{routes.map(({ path, component: Component = React.Fragment }) => (
<Route
key={path}
path={path}
component={(_props) => React.createElement(BindContexts(Component), {
...props,
..._props,
history: props.history,
})}
exact={true}
/>
))}
<Route path="*" component={props.staticRenders?.NotFound ?? NotFoundRender} />
</Switch>
</React.Suspense>
}
export default {
routes,
BindContexts,
InternalRouter,
PageRender,
}

View File

@ -0,0 +1,53 @@
.fade-transverse-active {
transition: all 250ms;
height: fit-content;
width: 100%;
}
.fade-transverse-enter {
opacity: 0;
transform: translateX(-30px);
}
.fade-transverse-leave {
opacity: 0;
transform: translateX(30px);
}
.fade-scale-leave-active,
.fade-scale-enter-active {
transition: all 0.3s;
}
.fade-scale-enter {
opacity: 0;
transform: scale(1.2);
}
.fade-scale-leave {
opacity: 0;
transform: scale(0.8);
}
.fade-opacity-active {
transition: all 250ms;
opacity: 1;
}
.fade-opacity-leave {
opacity: 0;
}
.fade-opacity-enter {
opacity: 1;
}
@keyframes fadeOut {
from {
opacity: 1;
}
to {
opacity: 0;
}
}

View File

@ -0,0 +1,168 @@
// Fixments
.ant-btn {
display: flex;
align-items: center;
justify-content: center;
user-select: none;
--webkit-user-select: none;
}
.ant-result-extra {
display: flex;
align-items: center;
justify-content: center;
}
.ant-modal-confirm-btns {
display: flex;
}
.ant-message {
svg {
margin: 0;
}
}
.ant-avatar-square {
border-radius: 12px;
}
// fix results
.ant-result {
.ant-result-content {
display: inline-flex;
flex-direction: column;
align-items: center;
justify-content: center;
text-align: center;
padding: 10px;
background-color: var(--background-color-accent);
color: var(--background-color-primary);
h1,
h2,
h3,
h4,
h5,
p,
span {
margin: 0;
}
}
}
// fix colors for select & dropdown
.ant-select:not(.ant-select-customize-input) .ant-select-selector {
background-color: var(--background-color-primary);
}
.ant-select-dropdown {
background-color: var(--background-color-primary) !important;
color: var(--text-color) !important;
.ant-select-item-option:not(.ant-select-item-option-disabled) {
background-color: var(--background-color-primary) !important;
color: var(--text-color) !important;
}
.ant-select-item-option-selected:not(.ant-select-item-option-disabled) {
background-color: var(--background-color-primary2) !important;
color: var(--text-color) !important;
}
}
// fix buttons
.ant-btn {
display: inline-flex;
align-items: center;
justify-content: center;
svg {
margin: 0 10px 0 0 !important;
}
span {
margin: 0;
line-height: 1rem;
}
}
.ant-btn-primary {
svg {
color: var(--background-color-primary) !important;
}
span {
color: var(--background-color-primary) !important;
margin: 0;
}
}
.ant-btn-primary[disabled] {
svg {
color: unset !important;
}
span {
color: unset !important;
margin: 0;
}
}
.ant-btn-default {
color: var(--text-color);
background: var(--background-color-primary);
border-color: var(--background-color-primary2) !important;
&:hover {
color: var(--text-color);
background: var(--background-color-primary2);
border-color: var(--background-color-primary2) !important;
}
&:active {
color: var(--text-color);
background: var(--background-color-primary2);
border-color: var(--background-color-primary2) !important;
}
&:focus {
color: var(--text-color);
background: var(--background-color-primary2);
border-color: var(--background-color-contrast) !important;
}
}
// fix sliders colors
.ant-slider-rail {
background-color: var(--background-color-primary2);
&:hover {
background-color: var(--background-color-primary);
}
}
// fix menu colors
.ant-menu-item {
color: var(--text-color);
}
.ant-menu:not(.ant-menu-horizontal) .ant-menu-item-selected {
color: var(--text-color);
background-color: var(--background-color-primary) !important;
}
.ant-menu-item:active {
background-color: var(--background-color-primary2) !important;
}
// fix uploader drag
.ant-upload-drag {
color: var(--text-color) !important;
background: var(--background-color-primary) !important;
border-color: var(--background-color-primary2) !important;
}

View File

@ -0,0 +1,13 @@
@import url('https://fonts.googleapis.com/css2?family=Roboto+Mono:wght@200;300;400;500;700&display=swap');
@import url('https://fonts.googleapis.com/css?family=Alata&display=swap');
@import url('https://fonts.googleapis.com/css?family=Poppins:300,300i,500,500i,700');
@import url('https://fonts.googleapis.com/css?family=Source+Sans+Pro&display=swap');
@import url('https://fonts.googleapis.com/css?family=Kulim+Park&display=swap');
@import url('https://fonts.googleapis.com/css?family=Nunito&display=swap');
@import url("https://fonts.googleapis.com/css?family=Manrope:300,400,500,600,700&display=swap&subset=latin-ext");
@import url('https://fonts.googleapis.com/css2?family=Varela+Round&display=swap');
@import url('https://fonts.googleapis.com/css2?family=Space+Mono&display=swap');
@import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:ital,wght@0,300;0,400;1,300;1,400&display=swap');
@import url('https://fonts.googleapis.com/css2?family=DM+Mono:ital,wght@0,300;0,400;0,500;1,300;1,400;1,500&display=swap');
@import url('https://fonts.googleapis.com/css2?family=Recursive:wght@300;400;500;600;700;800;900&display=swap');
@import url('https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@300;400;600&display=swap');

View File

@ -0,0 +1,294 @@
@import "antd/dist/antd.variable.less";
@import "theme/animations.less";
@import "theme/vars.less";
@import "theme/fonts.css";
@import "theme/fixments.less";
html {
overflow: hidden;
height: 100%;
-webkit-overflow-scrolling: touch;
background-color: var(--background-color-primary) !important;
h1,
h2,
h3,
h4,
h5,
h6,
p,
span {
color: var(--text-color);
}
svg {
color: var(--text-color);
margin-right: 10px;
vertical-align: -0.125em;
}
body {
overflow: hidden;
-webkit-overflow-scrolling: touch;
-webkit-app-region: no-drag;
height: 100%;
user-select: none;
--webkit-user-select: none;
scroll-behavior: smooth;
text-rendering: optimizeLegibility !important;
background-color: var(--background-color-primary) !important;
font-family: var(--fontFamily);
}
*:not(input):not(textarea) {
-webkit-user-select: none;
/* disable selection/Copy of UIWebView */
-webkit-touch-callout: none;
/* disable the IOS popup when long-press on a link */
}
::-webkit-scrollbar {
display: none;
width: 0;
height: 0;
z-index: 0;
}
::-webkit-scrollbar-thumb {
position: absolute;
z-index: 200;
height: 6px;
margin: 5px 10px 5px 5px;
transition: all 200ms ease-in-out;
border: 4px solid rgba(0, 0, 0, 0);
background-color: rgba(0, 0, 0, 0.15);
background-clip: padding-box;
-webkit-border-radius: 7px;
}
::-webkit-scrollbar-button {
width: 0;
height: 0;
display: none;
}
::-webkit-scrollbar-corner {
background-color: transparent;
}
#root {
-webkit-overflow-scrolling: touch;
position: fixed;
overflow: hidden;
width: 100%;
height: 100%;
background-color: var(--layoutBackgroundColor) !important;
&.electron {
.layout_page {
padding-top: 35px;
}
.ant-layout-sider {
padding-top: 0px;
}
}
}
#nprogress {
position: absolute;
top: 0;
width: 100vw;
.bar {
height: 2px;
background: #48acf0;
}
}
}
.ant-layout,
.content_layout {
width: 100%;
height: 100%;
max-height: 100vh;
background-color: transparent;
}
.app_layout {
background-color: rgba(var(--layoutBackgroundColor), var(--backgroundColorTransparency)) !important;
backdrop-filter: blur(var(--backgroundBlur));
position: relative;
-webkit-overflow-scrolling: touch;
width: 100%;
height: 100%;
max-height: 100vh;
overflow: hidden;
transition: all 150ms ease-in-out;
::-webkit-scrollbar {
display: block;
position: absolute;
width: 14px;
height: 18px;
z-index: 200;
transition: all 200ms ease-in-out;
}
&.mobile {
//padding-top: 20px;
::-webkit-scrollbar {
display: none !important;
width: 0;
height: 0;
z-index: 0;
}
}
}
.layout_page {
position: relative;
-webkit-overflow-scrolling: touch;
height: 100%;
padding: 10px;
overflow-x: hidden;
overflow-y: overlay;
transition: all 150ms ease-in-out;
margin: var(--layoutMargin);
padding: var(--layoutPadding);
}
.app_background_decorator {
background-image: var(--backgroundImage);
background-size: cover;
background-position: center;
background-repeat: no-repeat;
background-attachment: fixed;
position: absolute;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
transition: all 150ms ease-in-out;
}
.app_render_error {
position: relative;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
width: 100vw;
height: 100vh;
.ant-result {
background-color: var(--background-color-primary);
border-radius: 8px;
}
}
.app_splash_wrapper {
position: absolute;
top: 0;
left: 0;
overflow: hidden;
backdrop-filter: blur(10px);
--webkit-backdrop-filter: blur(10px);
width: 100%;
height: 100%;
z-index: 1000;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
>div {
margin-bottom: 40px;
}
svg {
color: var(--text-color) !important;
}
.splash_logo {
width: 200px;
height: 200px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
img {
width: 100%;
filter: drop-shadow(14px 10px 10px rgba(128, 128, 128, 0.5));
}
}
.splash_label {
font-size: 2rem;
svg {
margin: 0 !important;
}
}
}
@media (max-width: 768px) {
.layout_page {
padding: 10px;
margin: 0;
}
h1,
h2,
h3,
h4,
h5,
h6,
span,
p {
user-select: none;
-webkit-user-select: none;
}
.postCard {
min-width: 30px;
}
}

View File

@ -0,0 +1,17 @@
//* Now this only works as an fallback for unset dynamic theme values
// borders & radius
@app_sidebar_borderRadius: 18px;
// SIZES
@app_header_height: 5vh;
@fixedHeader100VH: @app_header_height - 100vh;
@app_menuItemSize: 100px;
@app_menuItemIconSize: 30px;
@app_menuItemTextSize: 12px;
// TRANSITIONS
@transition-ease-in: all 0.3s ease-out;
@transition-ease-out: all 0.3s ease-out;
@transition-ease-inout: all 150ms ease-in-out;

View File

@ -0,0 +1,14 @@
import path from "path"
import getConfig from "./.config.js"
import { defineConfig } from "vite"
import react from "@vitejs/plugin-react"
//import electron, { onstart } from "vite-plugin-electron"
export default defineConfig({
plugins: [
react(),
],
...getConfig(),
})

View File

@ -1,6 +1,6 @@
{ {
"name": "comty", "name": "comty",
"version": "0.20.1", "version": "0.20.2",
"license": "MIT", "license": "MIT",
"main": "electron/main", "main": "electron/main",
"author": "RageStudio", "author": "RageStudio",

View File

@ -1,6 +1,6 @@
{ {
"name": "@comty/server", "name": "@comty/server",
"version": "0.20.1", "version": "0.20.2",
"main": "dist/index.js", "main": "dist/index.js",
"scripts": { "scripts": {
"build": "corenode-cli build", "build": "corenode-cli build",

View File

@ -1,7 +1,7 @@
{ {
"name": "@comty/streaming-server", "name": "@comty/streaming-server",
"author": "RageStudio", "author": "RageStudio",
"version": "0.20.1", "version": "0.20.2",
"main": "dist/index.js", "main": "dist/index.js",
"scripts": { "scripts": {
"dev": "nodemon --ignore dist/ --exec corenode-node ./src/index.js", "dev": "nodemon --ignore dist/ --exec corenode-node ./src/index.js",