Author SHA1 Message Date
Christopher d5b9f78fa8 inital share modal for notes 2021-03-16 23:51:27 +01:00
Christopher 11b9caf611 add Fab 2021-03-16 12:02:07 +01:00
Christopher 8c3a17e672 renaming 2021-03-16 11:35:59 +01:00
Christopher 28711c7c5d tweak(phone): overall changes for notes > documents 2021-03-16 11:32:47 +01:00
Christopher 42447e544b update apps configs 2021-03-16 11:32:10 +01:00
Christopher 0f2cc6da35 feat(phone): Doucment list component 2021-03-16 11:31:26 +01:00
Christopher b7ff65f74e update en json 2021-03-16 11:30:52 +01:00
Christopher 65c7f46d5f tweak(phone): rename notes > documents 2021-03-16 11:30:30 +01:00
Christopher 2499358f5f tweak(phone): update translation 2021-03-16 11:06:32 +01:00
421 changed files with 14109 additions and 20087 deletions

No files matched your search

+11 -19
View File
@@ -1,6 +1,6 @@
name: Test Suite
on: [push, pull_request]
on: [push]
jobs:
nui_preformatting_tests:
@@ -13,6 +13,11 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v2
with:
# Make sure the actual branch is checked out when running on pull requests
ref: ${{ github.head_ref }}
# This is important to fetch the changes to the previous commit
fetch-depth: 0
- name: Get yarn cache directory path
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn config get cacheFolder)"
@@ -31,8 +36,6 @@ jobs:
run: yarn --frozen-lockfile
- name: Run Enzyme Tests
run: yarn test
- name: Check build status
run: yarn build
env:
CI: true
@@ -46,6 +49,11 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v2
with:
# Make sure the actual branch is checked out when running on pull requests
ref: ${{ github.head_ref }}
# This is important to fetch the changes to the previous commit
fetch-depth: 0
- name: Use Node.js
uses: actions/setup-node@v1
with:
@@ -54,21 +62,5 @@ jobs:
run: yarn --frozen-lockfile
- name: Run Jest Tests
run: yarn test
- name: Check build status
run: yarn build
env:
CI: true
lint:
name: Lint Lua scripts
runs-on: ubuntu-latest
defaults:
run:
working-directory: resources
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Lint
uses: GoatG33k/fivem-lua-lint-action@v1
-57
View File
@@ -1,57 +0,0 @@
name: Prerelease Publisher
on:
push:
branches:
- master
jobs:
pre-release-build:
name: 'Build & Create Pre-Release'
runs-on: ubuntu-latest
steps:
- name: Checkout source code
uses: actions/checkout@v2
with:
fetch-depth: 0
ref: ${{ github.ref }}
- name: Setup Node and Yarn Cache
uses: actions/setup-node@v2
with:
node-version: '14'
cache: 'yarn'
# Get zip util
- name: Install archive tools
run: sudo apt install zip
- name: Get variables
id: get_vars
run: |
echo "::set-output name=SHORT_SHA::$(git rev-parse --short HEAD)"
echo "::set-output name=DATE::$(date +'%D')"
- name: Install Deps
run: yarn --frozen-lockfile
- name: Run build
run: yarn build
- name: Bundle and Zip files
run: |
mkdir -p ./temp/npwd/resources
cp ./{LICENSE,README.md,config.json,import.sql,fxmanifest.lua} ./temp/npwd/
cp -r ./resources/{dist,html} ./temp/npwd/resources
cd ./temp && zip -r npwd-pre-${{ steps.get_vars.outputs.SHORT_SHA }}.zip ./npwd
- name: Create Release & Changelog
uses: "marvinpinto/[email protected]"
with:
repo_token: "${{ secrets.GITHUB_TOKEN }}"
title: Pre-Release Build (${{ steps.get_vars.outputs.SHORT_SHA }}) | ${{ steps.get_vars.outputs.DATE }}
prerelease: true
automatic_release_tag: "unstable"
files: ./temp/npwd-pre-${{ steps.get_vars.outputs.SHORT_SHA }}.zip
env:
CI: false
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
-107
View File
@@ -1,107 +0,0 @@
name: Tagged Release Publisher
on:
push:
tags:
- "*"
jobs:
bump-version:
name: Bump Version
runs-on: ubuntu-latest
outputs:
VERSION_TAG: ${{ steps.get_version_tag.outputs.VERSION_TAG }}
steps:
- name: Checkout source code
uses: actions/checkout@v2
with:
ref: ${{ github.ref }}
- name: Get Version Tag
id: get_version_tag
run: echo ::set-output name=VERSION_TAG::${GITHUB_REF/refs\/tags\//}
- name: Setup Node
uses: actions/setup-node@v2
with:
node-version: 14.x
- name: Bump package shells
run: |
cd phone && npm version ${{ needs.bump-version.outputs.VERSION_TAG }}
cd resources && npm version ${{ needs.bump-version.outputs.VERSION_TAG }}
git status
- name: Commit and push
uses: EndBug/[email protected]
with:
message: Bump version to v${{ needs.bump-version.outputs.VERSION_TAG }}
default_author: github_actions
branch: master
add: |
phone/package.json
resources/package.json
create-tagged-release:
name: Build and Create Tagged Release
runs-on: ubuntu-latest
needs: bump-version
steps:
- name: Install archive tools
run: sudo apt install zip
- name: Checkout source code
uses: actions/checkout@v2
with:
fetch-depth: 0
ref: ${{ github.ref }}
- name: Install dependencies
run: yarn
- name: Run build
run: yarn build
- name: Create Sentry Release (NPWD)
uses: tclindner/[email protected]
env:
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
SENTRY_ORG: 'project-error'
SENTRY_PROJECT: 'npwd'
SENTRY_URL: https://sentry.projecterror.dev/
SENTRY_LOG_LEVEL: debug
with:
environment: production
tagName: ${{ needs.bump-version.outputs.VERSION_TAG }}
sourceMapOptions: './resources/html/static/js'
- name: Create Sentry Release (NodeJS)
uses: tclindner/[email protected]
env:
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
SENTRY_ORG: 'project-error'
SENTRY_PROJECT: 'npwd-s'
SENTRY_URL: https://sentry.projecterror.dev/
with:
environment: production
tagName: ${{ steps.get_vars.outputs.VERSION_TAG }}
sourceMapOptions: './resources/html/static/js'
- name: Bundle built files
run: |
mkdir -p ./temp/npwd/resources
cp ./{LICENSE,README.md,config.json,import.sql,fxmanifest.lua} ./temp/npwd/
cp -r ./resources/{dist,html} ./temp/npwd/resources
cd ./temp && zip -r npwd-${{ needs.bump-version.outputs.VERSION_TAG }}.zip ./npwd
- name: Create Release
uses: "marvinpinto/[email protected]"
id: auto_release
with:
repo_token: "${{ secrets.GITHUB_TOKEN }}"
title: NPWD Release | ${{ needs.bump-version.outputs.VERSION_TAG }}
prerelease: false
files: npwd-${{ needs.bump-version.outputs.VERSION_TAG }}.zip
env:
CI: false
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+1 -8
View File
@@ -1,12 +1,8 @@
# No IDE Folders
.idea
npwd_temp
resources/html
phone/.eslintcache
# Node Modules and Built Folders
node_modules
build
@@ -21,7 +17,4 @@ yarn-error.log*
.DS_Store
# Debug logs
sv_npwd.log
# FXServer Yarn
.yarn.installed
sv_npwd.log
+30
View File
@@ -0,0 +1,30 @@
#!/bin/sh
if [ -z "$husky_skip_init" ]; then
debug () {
[ "$HUSKY_DEBUG" = "1" ] && echo "husky (debug) - $1"
}
readonly hook_name="$(basename "$0")"
debug "starting $hook_name..."
if [ "$HUSKY" = "0" ]; then
debug "HUSKY env variable is set to 0, skipping hook"
exit 0
fi
if [ -f ~/.huskyrc ]; then
debug "sourcing ~/.huskyrc"
. ~/.huskyrc
fi
export readonly husky_skip_init=1
sh -e "$0" "$@"
exitCode="$?"
if [ $exitCode != 0 ]; then
echo "husky - $hook_name hook exited with code $exitCode (error)"
exit $exitCode
fi
exit 0
fi
-4
View File
@@ -1,4 +0,0 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npx --no-install commitlint --edit ""
File renamed without changes.
+12 -12
View File
@@ -1,9 +1,9 @@
# New-Phone-Who-Dis (NPWD)
<img src="https://i.file.glass/zVkK7.png" width="500" height="300" />
<img src="https://beta.iodine.gg/zVkK7.png" width="500" height="300" />
NPWD is our flagship and current running project. The team has been working on the project since August, 2020. This resource isn’t complete yet and currently has a pre-release. There is however no ETA for a stable release, yet. Feel free to test it out in a dev environment by following the installation guide.
NPWD is our current running project. Our team has been working on the project since Auguest, 2020. This resource isn’t complete yet and currently has no ETA for release. Feel free to test it out in a dev enviorment by following the installation guide.
Written completely by the Project Error Dev Team in [React](https://reactjs.org/) with a [TypeScript](https://www.typescriptlang.org/) client/server environment.
@@ -36,13 +36,13 @@ We do not want issues opened that are due to the phone being **WIP** as this slo
Most of these apps have UI that does **not** represent the final product and are subject to change.
- [**Bank**](https://i.file.glass/Eh53X.png)
- [**Calculator**](https://i.file.glass/s6VQV.png)
- [**Camera**](https://i.file.glass/vW0y9.png)
- [**Contacts**](https://i.file.glass/3fujR.png)
- [**Marketplace**](https://i.file.glass/5bUa8.png)
- [**Messages**](https://i.file.glass/S4Lia.png)
- [**Notes**](https://i.file.glass/qTkBb.png)
- [**Phone**](https://i.file.glass/z0ii9.png)
- [**Settings**](https://i.file.glass/mZAIt.png)
- [**Twitter**](https://i.file.glass/rQZFR.png)
- [**Bank**](https://beta.iodine.gg/Eh53X.png)
- [**Calculator**](https://beta.iodine.gg/s6VQV.png)
- [**Camera**](https://beta.iodine.gg/vW0y9.png)
- [**Contacts**](https://beta.iodine.gg/3fujR.png)
- [**Marketplace**](https://beta.iodine.gg/5bUa8.png)
- [**Messages**](https://beta.iodine.gg/S4Lia.png)
- [**Notes**](https://beta.iodine.gg/qTkBb.png)
- [**Phone**](https://beta.iodine.gg/z0ii9.png)
- [**Settings**](https://beta.iodine.gg/mZAIt.png)
- [**Twitter**](https://beta.iodine.gg/rQZFR.png)
-3
View File
@@ -1,3 +0,0 @@
module.exports = {
extends: ['@commitlint/config-conventional'],
};
+14 -19
View File
@@ -1,23 +1,23 @@
{
"Locale": "en",
"PhoneAsItem": {
"enabled": false,
"exportResource": "my-core-resource",
"exportName": "myCheckerFunction"
"KeyTogglePhone": 288,
"KeyTakeCall": 38,
"PhoneAsItem": false,
"SwimDestroy": false,
"RunRate": 10,
"DestoryChance": 100,
"DestroyPhoneReCheck": 3,
"notificationPosition": {
"horizontal": "right",
"vertical": "top"
},
"general": {
"useDashNumber": true,
"enableMultiChar": false
},
"database": {
"useIdentifierPrefix": false,
"playerTable": "users",
"identifierColumn": "identifier"
"useDashNumber": true
},
"twitter": {
"showNotifications": true,
"generateProfileNameFromUsers": true,
"allowEditableProfileName": true,
"allowEdtiableProfileName": true,
"allowDeleteTweets": true,
"allowReportTweets": true,
"characterLimit": 160,
@@ -27,16 +27,11 @@
"enableImages": true,
"maxImages": 3
},
"match": {
"generateProfileNameFromUsers": true,
"allowEditableProfileName": true
},
"bank": {
"showNotifications": true
},
"debug": {
"level": "silly",
"enabled": true,
"sentryEnabled": true
"level": "debug",
"enabled": true
}
}
+4 -5
View File
@@ -3,9 +3,8 @@ game "gta5"
description 'js runtime monkaW'
authors { "itschip", "erik-sn", "TasoOneAsia", "kidz", "RockySouthpaw"}
client_scripts {
'resources/dist/client/*.client.js',
'resources/client/*.lua'
client_script {
'resources/dist/client/*.client.js'
}
server_script {
@@ -15,7 +14,7 @@ server_script {
ui_page 'resources/html/index.html'
files {
'config.json',
'resources/html/index.html',
'resources/html/**/*',
'resources/html/*.js',
'resources/html/media/**/*'
}
+64 -70
View File
@@ -1,13 +1,15 @@
# comment this out if your server has a different table/location for phone_number
# or if it already exists in the users table
ALTER TABLE `users` ADD COLUMN `phone_number` VARCHAR(20) DEFAULT NULL;
INSERT INTO `items` (`name`, `label`, `weight`, `rare`, `can_remove`) VALUES ('phone', 'Phone', 1, 0, 1);
INSERT INTO `items` (`name`, `label`, `weight`, `rare`, `can_remove`) VALUES ('dphone', 'Destroyed Phone', 1, 0, 1);
CREATE TABLE IF NOT EXISTS `npwd_phone_contacts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`identifier` varchar(48) DEFAULT NULL,
`avatar` varchar(512) DEFAULT NULL,
`number` varchar(12) DEFAULT NULL,
`display` varchar(255) NOT NULL DEFAULT '',
CREATE TABLE IF NOT EXISTS npwd_phone_contacts (
id int(11) NOT NULL AUTO_INCREMENT,
identifier varchar(60) DEFAULT NULL,
avatar varchar(512) DEFAULT NULL,
number varchar(10) DEFAULT NULL,
display varchar(60) NOT NULL DEFAULT '',
PRIMARY KEY (id)
);
@@ -17,7 +19,7 @@ CREATE TABLE IF NOT EXISTS `npwd_twitter_tweets` (
`createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`likes` int NOT NULL DEFAULT '0',
`identifier` varchar(48) NOT NULL,
`identifier` varchar(40) NOT NULL,
`visible` tinyint NOT NULL DEFAULT '1',
`images` varchar(1000) DEFAULT '',
`retweet` int DEFAULT NULL,
@@ -28,9 +30,9 @@ CREATE TABLE IF NOT EXISTS `npwd_twitter_tweets` (
CREATE TABLE IF NOT EXISTS `npwd_twitter_profiles` (
`id` int NOT NULL AUTO_INCREMENT,
`profile_name` varchar(90) NOT NULL,
`identifier` varchar(48) NOT NULL,
`identifier` varchar(40) NOT NULL,
# Default Profile avatar can be set here
`avatar_url` varchar(255) DEFAULT 'https://i.file.glass/QrEvq.png',
`avatar_url` varchar(255) DEFAULT 'https://beta.iodine.gg/QrEvq.png',
`bio` varchar(512) DEFAULT NULL,
`location` varchar(45) DEFAULT NULL,
`job` varchar(45) DEFAULT NULL,
@@ -52,62 +54,44 @@ CREATE TABLE IF NOT EXISTS `npwd_twitter_likes` (
CONSTRAINT `tweet` FOREIGN KEY (`tweet_id`) REFERENCES `npwd_twitter_tweets` (`id`) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS `npwd_match_profiles` (
`id` int NOT NULL AUTO_INCREMENT,
`identifier` varchar(48) NOT NULL,
`name` varchar(90) NOT NULL,
`image` varchar(255) NOT NULL,
`bio` varchar(512) DEFAULT NULL,
`location` varchar(45) DEFAULT NULL,
`job` varchar(45) DEFAULT NULL,
`tags` varchar(255) NOT NULL DEFAULT '',
`createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `name_UNIQUE` (`name`),
UNIQUE KEY `identifier_UNIQUE` (`identifier`)
);
CREATE TABLE IF NOT EXISTS `npwd_match_views` (
`id` int NOT NULL AUTO_INCREMENT,
`identifier` varchar(48) NOT NULL,
`profile` int NOT NULL,
`liked` tinyint DEFAULT '0',
`createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `match_profile_idx` (`profile`),
CONSTRAINT `match_profile` FOREIGN KEY (`profile`) REFERENCES `npwd_match_profiles` (`id`)
);
CREATE TABLE IF NOT EXISTS `npwd_notes` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`identifier` varchar(48) NOT NULL,
`title` varchar(255) NOT NULL,
`content` varchar(255) NOT NULL,
CREATE TABLE IF NOT EXISTS npwd_notes (
id int(11) NOT NULL AUTO_INCREMENT,
identifier varchar(255) NOT NULL,
title varchar(255) NOT NULL,
content varchar(255) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE IF NOT EXISTS `npwd_marketplace_listings` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`identifier` varchar(48) DEFAULT NULL,
`username` varchar(255) DEFAULT NULL,
`name` varchar(50) DEFAULT NULL,
`number` varchar(255) NOT NULL,
`title` varchar(255) DEFAULT NULL,
`url` varchar(255) DEFAULT NULL,
`description` varchar(255) NOT NULL,
`createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
CREATE TABLE IF NOT EXISTS npwd_sellout_listings (
id int(11) NOT NULL AUTO_INCREMENT,
identifier varchar(255) DEFAULT NULL,
username varchar(255) DEFAULT NULL,
name varchar(50) DEFAULT NULL,
number varchar(255) NOT NULL,
title varchar(255) DEFAULT NULL,
url varchar(255) DEFAULT NULL,
description varchar(255) NOT NULL,
createdAt timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
updatedAt timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id)
)
ENGINE = INNODB,
AUTO_INCREMENT = 31,
AVG_ROW_LENGTH = 2048,
CHARACTER SET utf8mb4,
COLLATE utf8mb4_general_ci;
);
CREATE TABLE IF NOT EXISTS `npwd_marketplace_reports` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`listing_id` int(11) DEFAULT NULL,
`profile` varchar(255) DEFAULT NULL,
CREATE TABLE IF NOT EXISTS npwd_marketplace_reports (
id int(11) NOT NULL AUTO_INCREMENT,
listing_id int(11) DEFAULT NULL,
profile varchar(255) DEFAULT NULL,
PRIMARY KEY (id)
);
)
ENGINE = INNODB,
CHARACTER SET utf8mb4,
COLLATE utf8mb4_general_ci;
CREATE TABLE IF NOT EXISTS `npwd_twitter_reports` (
`id` int NOT NULL AUTO_INCREMENT,
@@ -123,20 +107,30 @@ CREATE TABLE IF NOT EXISTS `npwd_twitter_reports` (
CREATE TABLE IF NOT EXISTS `npwd_messages_groups` (
`id` int NOT NULL AUTO_INCREMENT,
`user_identifier` varchar(48) NOT NULL,
`user_identifier` varchar(40) NOT NULL,
`createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`group_id` varchar(512) NOT NULL,
`participant_identifier` varchar(48) NOT NULL,
`participant_identifier` varchar(40) NOT NULL,
`label` varchar(60) DEFAULT '',
`unreadCount` int(11) NOT NULL DEFAULT 0,
PRIMARY KEY (`id`)
);
CREATE TABLE IF NOT EXISTS `npwd_messages_labels` (
`id` int NOT NULL AUTO_INCREMENT,
`user_identifier` varchar(40) NOT NULL,
`label` varchar(60) NOT NULL,
`createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`group_id` varchar(512) NOT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE IF NOT EXISTS `npwd_messages` (
`id` int NOT NULL AUTO_INCREMENT,
`message` varchar(512) NOT NULL,
`user_identifier` varchar(48) NOT NULL,
`user_identifier` varchar(40) NOT NULL,
`group_id` varchar(512) NOT NULL,
`isRead` tinyint NOT NULL DEFAULT '0',
`createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
@@ -145,20 +139,20 @@ CREATE TABLE IF NOT EXISTS `npwd_messages` (
PRIMARY KEY (`id`)
);
CREATE TABLE IF NOT EXISTS `npwd_calls` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`identifier` varchar(48) DEFAULT NULL,
`transmitter` varchar(255) NOT NULL,
`receiver` varchar(255) NOT NULL,
`is_accepted` tinyint(4) DEFAULT 0,
`start` varchar(255) DEFAULT NULL,
CREATE TABLE IF NOT EXISTS npwd_calls (
id int(11) NOT NULL AUTO_INCREMENT,
identifier varchar(255) DEFAULT NULL,
transmitter varchar(255) NOT NULL,
receiver varchar(255) NOT NULL,
is_accepted tinyint(4) DEFAULT 0,
start varchar(255) DEFAULT NULL,
end varchar(255) DEFAULT NULL,
PRIMARY KEY (id)
);
CREATE TABLE IF NOT EXISTS npwd_phone_gallery (
`id` int(11) NOT NULL AUTO_INCREMENT,
`identifier` varchar(48) DEFAULT NULL,
`image` varchar(255) DEFAULT NULL,
id int(11) NOT NULL AUTO_INCREMENT,
identifier varchar(255) DEFAULT NULL,
image varchar(255) DEFAULT NULL,
PRIMARY KEY (id)
);
+3 -13
View File
@@ -1,29 +1,19 @@
{
"name": "npwd",
"version": "0.1.0",
"description": "A FiveM phone resource, made in React & TypeScript",
"repository": "https://github.com/project-error/new-phone-who-dis",
"license": "CC-BY-NC-SA-4.0",
"devDependencies": {
"@commitlint/cli": "^12.1.1",
"@commitlint/config-conventional": "^12.1.1",
"@octokit/core": "^3.4.0",
"husky": "^5.1.3",
"lerna": "^3.22.1",
"prettier": "^2.2.1",
"pretty-quick": "^3.1.0"
},
"scripts": {
"build": "lerna run test && lerna run build",
"build": "lerna run build --concurrency 1",
"prepare": "husky install",
"bootstrap": "lerna bootstrap",
"format:staged": "pretty-quick --staged",
"postinstall": "husky install && yarn bootstrap",
"test": "lerna run test"
"format": "pretty-quick"
},
"husky": {
"hooks": {
"pre-commit": "npx run format:staged"
"pre-commit": "pretty-quick --staged"
}
}
}
+12
View File
@@ -0,0 +1,12 @@
{
"presets": [
[
"@babel/preset-env",
{
"modules": false
}
],
"@babel/preset-react"
],
"plugins": ["@babel/plugin-proposal-class-properties", "@babel/plugin-syntax-dynamic-import"]
}
-1
View File
@@ -1 +0,0 @@
REACT_APP_VERSION=$npm_package_version
-70
View File
@@ -1,70 +0,0 @@
const path = require('path');
const {
addAfterLoader,
removeLoaders,
loaderByName,
getLoaders,
throwUnexpectedConfigError,
} = require('@craco/craco');
const throwError = (message) =>
throwUnexpectedConfigError({
packageName: 'craco',
githubRepo: 'gsoft-inc/craco',
message,
githubIssueQuery: 'webpack',
});
module.exports = {
webpack: {
configure: (webpackConfig, { paths }) => {
const { hasFoundAny, matches } = getLoaders(webpackConfig, loaderByName('babel-loader'));
if (!hasFoundAny) throwError('failed to find babel-loader');
const { hasRemovedAny, removedCount } = removeLoaders(
webpackConfig,
loaderByName('babel-loader'),
);
if (!hasRemovedAny) throwError('no babel-loader to remove');
if (removedCount !== 2) throwError('had expected to remove 2 babel loader instances');
webpackConfig.resolve.plugins = webpackConfig.resolve.plugins.filter(
({ constructor: c }) => !c || c.name !== 'ModuleScopePlugin',
);
const tsLoader = {
test: /\.tsx?$/,
loader: require.resolve('ts-loader'),
options: { transpileOnly: true },
};
const { isAdded: tsLoaderIsAdded } = addAfterLoader(
webpackConfig,
loaderByName('url-loader'),
tsLoader,
);
if (!tsLoaderIsAdded) throwError('failed to add ts-loader');
const { isAdded: babelLoaderIsAdded } = addAfterLoader(
webpackConfig,
loaderByName('ts-loader'),
matches[1].loader, // babel-loader
);
if (!babelLoaderIsAdded) throwError('failed to add back babel-loader for non-application JS');
paths.appBuild = webpackConfig.output.path = path.resolve('../resources/html');
if (webpackConfig.mode === 'development') {
webpackConfig.devtool = 'eval-source-map';
}
return webpackConfig;
},
},
devServer: (devServerConfig) => {
devServerConfig.writeToDisk = true;
return devServerConfig;
},
};
+1 -1
View File
@@ -4,7 +4,7 @@ console.log(args);
const path = './src/locale/';
const langs = ['bs', 'no', 'es', 'fr', 'pt', 'ptbr', 'sv', 'tr', "hu"];
const langs = ['bs', 'no', 'es', 'fr', 'pt', 'ptbr', 'sv', 'tr'];
const defaultLang = 'en';
+68 -36
View File
@@ -2,57 +2,89 @@
"name": "npwd-nui",
"version": "0.1.0",
"repository": "https://github.com/project-error/new-phone-who-dis",
"private": true,
"private": false,
"license": "CC-BY-NC-SA-4.0",
"homepage": "/resources/html",
"dependencies": {
"@material-ui/core": "^4.11.3",
"@material-ui/icons": "^4.11.2",
"@babel/polyfill": "^7.4.4",
"@fortawesome/fontawesome-svg-core": "^1.2.32",
"@fortawesome/free-brands-svg-icons": "^5.15.1",
"@fortawesome/free-solid-svg-icons": "^5.15.1",
"@fortawesome/react-fontawesome": "^0.1.11",
"@material-ui/core": "^4.11.0",
"@material-ui/icons": "^4.9.1",
"@material-ui/lab": "^4.0.0-alpha.56",
"dayjs": "^1.10.4",
"dompurify": "^2.2.6",
"emoji-mart": "^3.0.1",
"enzyme": "^3.11.0",
"fivem-nui-react-lib": "^2.2.8",
"howler": "^2.2.1",
"i18next": "^20.3.4",
"jsonschema": "^1.4.0",
"parse-url": "^5.0.7",
"qs": "^6.9.6",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-i18next": "^11.7.1",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.3",
"recoil": "^0.3.1"
},
"devDependencies": {
"@craco/craco": "^6.1.1",
"@sentry/integrations": "^6.10.0",
"@sentry/webpack-plugin": "^1.16.0",
"@popperjs/core": "^2.5.3",
"@sentry/react": "^5.29.2",
"@sentry/tracing": "^5.29.2",
"core-js": "^3.8.3",
"dayjs": "^1.10.4",
"dompurify": "^2.2.6",
"emoji-mart": "^3.0.0",
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.5",
"howler": "^2.2.1",
"i18next": "^19.7.0",
"parse-url": "^5.0.2",
"qs": "^6.9.6",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-hotkeys": "^2.0.0",
"react-i18next": "^11.7.1",
"react-popper": "^2.2.3",
"react-router-dom": "^5.2.0",
"react-scripts": "3.4.3",
"recoil": "^0.1.2"
},
"devDependencies": {
"@babel/cli": "^7.4.4",
"@babel/core": "^7.4.5",
"@babel/plugin-proposal-class-properties": "^7.4.4",
"@babel/plugin-syntax-dynamic-import": "^7.2.0",
"@babel/preset-env": "^7.4.5",
"@babel/preset-react": "^7.0.0",
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.5.0",
"@testing-library/user-event": "^7.2.1",
"@types/enzyme": "^3.10.7",
"@types/howler": "^2.2.1",
"@types/jest": "^26.0.14",
"@types/node": "^14.11.5",
"@types/qs": "^6.9.5",
"@types/react": "^16.9.51",
"@types/react-dom": "^16.9.8",
"@types/react-router-dom": "^5.1.7",
"@welldone-software/why-did-you-render": "^6.1.1",
"@wojtekmaj/enzyme-adapter-react-17": "^0.6.1",
"cross-env": "^7.0.3",
"dotenv": "^10.0.0",
"ts-loader": "^8.3.0",
"typescript": "^4.3.2"
"babel-eslint": "^10.0.1",
"babel-loader": "^8.1.0",
"babel-plugin-styled-components": "^1.10.0",
"babel-plugin-transform-react-remove-prop-types": "^0.4.24",
"copy-webpack-plugin": "6.2.1",
"cp-cli": "^2.0.0",
"cra-build-watch": "^3.2.0",
"cross-env": "^7.0.2",
"css-loader": "^2.1.1",
"file-loader": "^3.0.1",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^4.3.0",
"react-devtools": "^4.10.1",
"react-test-renderer": "^16.13.1",
"style-loader": "^0.23.1",
"svg-url-loader": "^2.3.2",
"terser-webpack-plugin": "^1.3.0",
"ts-loader": "^8.0.4",
"typescript": "3.9.7",
"url-loader": "^1.1.2",
"webpack-cli": "^3.3.12"
},
"scripts": {
"i18n:missing": "node --experimental-json-modules i18n.missingKeys.js",
"start": "cross-env PUBLIC_URL=/ craco start",
"watch": "cross-env REACT_APP_IN_GAME=1 craco start",
"build:release": "cross-env SENTRY_RELEASE=true craco build",
"build": "craco build",
"test": "craco test --watchAll=false --testMatch **/src/**/*.test.{ts,js,tsx}"
"copy:config": "cp-cli ../config.json ./src/config.autogen.json",
"start": "yarn copy:config && react-scripts start",
"watch": "cra-build-watch --disable-chunks --build-path ../resources/html --output-filename dev.js",
"build": "yarn copy:config && cross-env NODE_ENV=production webpack --config webpack/prod.config.js --color -p --progress --hide-modules --display-optimization-bailout",
"build:dev": "cross-env NODE_ENV=development webpack --config webpack/dev.config.js --color -p --progress --hide-modules --display-optimization-bailout --analyze",
"test": "react-scripts test --watchAll=false --testMatch **/src/**/*.test.{ts,js,tsx}",
"test:watch": "react-scripts test --watchAll --testMatch **/src/**/*.test.{ts,js,tsx}",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
-96
View File
@@ -1,96 +0,0 @@
customElements.define(
'x-frame-bypass',
class extends HTMLIFrameElement {
static get observedAttributes() {
return ['src'];
}
constructor() {
super();
}
attributeChangedCallback() {
this.load(this.src);
}
connectedCallback() {
this.sandbox =
'' + this.sandbox ||
'allow-forms allow-modals allow-pointer-lock allow-same-origin allow-scripts allow-top-navigation-by-user-activation'; // all except allow-top-navigation
}
load(url, options) {
if (!url || !url.startsWith('http'))
throw new Error(`Unable to load src ${url} does not start with http(s)://`);
this.srcdoc = `<html>
<head>
<style>
.loader {
position: absolute;
top: calc(50% - 25px);
left: calc(50% - 25px);
width: 50px;
height: 50px;
background-color: #333;
border-radius: 50%;
animation: loader 1s infinite ease-in-out;
}
@keyframes loader {
0% {
transform: scale(0);
}
100% {
transform: scale(1);
opacity: 0;
}
}
</style>
</head>
<body>
<div class="loader"></div>
</body>
</html>`;
this.fetchProxy(url, options, 0)
.then((res) => res.text())
.then((data) => {
if (data)
this.srcdoc = data.replace(
/<head([^>]*)>/i,
`<head$1>
<base href="${url}">
<script>
// X-Frame-Bypass navigation event handlers
document.addEventListener('click', e => {
if (frameElement && document.activeElement && document.activeElement.href) {
e.preventDefault()
frameElement.load(document.activeElement.href)
}
})
document.addEventListener('submit', e => {
if (frameElement && document.activeElement && document.activeElement.form && document.activeElement.form.action) {
e.preventDefault()
if (document.activeElement.form.method === 'post')
frameElement.load(document.activeElement.form.action, {method: 'post', body: new FormData(document.activeElement.form)})
else
frameElement.load(document.activeElement.form.action + '?' + new URLSearchParams(new FormData(document.activeElement.form)))
}
})
</script>`,
);
})
.catch((e) => console.error('Unable to load proxy iframe service', e));
}
fetchProxy(url, options, i) {
const proxies = (options || {}).proxies || [
'https://cors-anywhere.herokuapp.com/',
'https://api.codetabs.com/v1/proxy/?quest=',
];
return fetch(proxies[i] + url, options)
.then((res) => {
if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);
return res;
})
.catch((error) => {
if (i === proxies.length - 1) throw error;
return this.fetchProxy(url, options, i + 1);
});
}
},
{ extends: 'iframe' },
);
-2
View File
@@ -8,8 +8,6 @@
/>
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!-- Enable experimental proxy custom iframe webcomp -->
<!-- <script type="module" src="./iframe.webcomp.js"></script>-->
<title>Project Error - New Phone Who Dis</title>
</head>
<body>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.
+2 -2
View File
@@ -1,12 +1,12 @@
import React from 'react';
import { RecoilRoot } from 'recoil';
import { shallow } from 'enzyme';
import { PhoneProviders } from './PhoneProviders';
import Phone from './Phone';
it('renders Phone', () => {
shallow(
<RecoilRoot>
<PhoneProviders />
<Phone />
</RecoilRoot>,
);
});
+83 -68
View File
@@ -1,124 +1,139 @@
import React, { useEffect } from 'react';
import React from 'react';
import './Phone.css';
import './i18n';
import { Route } from 'react-router-dom';
import { CallModal } from './os/call/components/CallModal';
import { HomeApp } from './apps/home/components/Home';
import { Box, Paper, Slide, Typography } from '@material-ui/core';
import { useKeyboardService } from './os/keyboard/hooks/useKeyboardService';
import { NotificationBar } from './os/notifications/components/NotificationBar';
import { Navigation } from './os/navigation-bar/components/Navigation';
import { useNuiService } from './os/nui-events/hooks/useNuiService';
import { useSimcardService } from './os/simcard/hooks/useSimcardService';
import { usePhoneService } from './os/phone/hooks/usePhoneService';
import { useApps } from './os/apps/hooks/useApps';
import { useContactsService } from './apps/contacts/hooks/useContactsService';
import { useTwitterService } from './apps/twitter/hooks/useTwitterService';
import { useMarketplaceService } from './apps/marketplace/hooks/useMarketplaceService';
import { useSelloutService } from './apps/sellout/hooks/useSelloutService';
import { useBankService } from './apps/bank/hooks/useBankService';
import { useMessagesService } from './apps/messages/hooks/useMessageService';
import { isSettingsSchemaValid, useSettings } from './apps/settings/hooks/useSettings';
import { useNotesService } from './apps/notes/hooks/useNotesService';
import { usePhotoService } from './apps/camera/hooks/usePhotoService';
import { useSettings } from './apps/settings/hooks/useSettings';
import { useCallService } from './os/call/hooks/useCallService';
import { useDialService } from './apps/dialer/hooks/useDialService';
import InjectDebugData from './os/debug/InjectDebugData';
import { usePhoneVisibility } from './os/phone/hooks/usePhoneVisibility';
import { PhoneSnackbar } from './ui/components/PhoneSnackbar';
import { NotificationAlert } from './os/notifications/components/NotificationAlert';
import { useCallModal } from './os/call/hooks/useCallModal';
import WindowSnackbar from './ui/components/WindowSnackbar';
import { usePhone } from './os/phone/hooks/usePhone';
import { useTranslation } from 'react-i18next';
import { useSnackbar } from './ui/hooks/useSnackbar';
import { PhoneEvents } from '../../typings/phone';
import { useKeyboardService } from './os/keyboard/hooks/useKeyboardService';
import PhoneWrapper from './PhoneWrapper';
import dayjs from 'dayjs';
import DefaultConfig from '../../config.json';
import { TopLevelErrorComponent } from './ui/components/TopLevelErrorComponent';
import { useConfig } from './os/phone/hooks/useConfig';
function Phone() {
const { t, i18n } = useTranslation();
const { t } = useTranslation();
const { apps } = useApps();
const [settings] = useSettings();
const { addAlert } = useSnackbar();
// Set language from local storage
// This will only trigger on first mount & settings changes
useEffect(() => {
i18n.changeLanguage(settings.language.value).catch((e) => console.error(e));
}, [i18n, settings.language]);
useEffect(() => {
if (!isSettingsSchemaValid()) {
addAlert({
message: t('SETTINGS.MESSAGES.INVALID_SETTINGS'),
type: 'error',
});
}
// We only want to run this on first mount of the phone,
// so we leave an empty dep array. Otherwise, we hit a max depth error.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useConfig();
useNuiService();
useKeyboardService();
usePhoneService();
useSimcardService();
useContactsService();
useTwitterService();
useMarketplaceService();
useSelloutService();
useBankService();
useMessagesService();
/*usePhotoService();*/
useNotesService();
usePhotoService();
useCallService();
useDialService();
const { modal: callModal } = useCallModal();
const { bottom, visibility } = usePhoneVisibility();
const { isPhoneReady } = usePhone();
return (
<div>
<TopLevelErrorComponent>
<WindowSnackbar />
<PhoneWrapper>
<NotificationBar />
<div className="PhoneAppContainer">
<>
<Route exact path="/" component={HomeApp} />
{callModal && <Route exact path="/call" component={CallModal} />}
{apps.map((App) => (
<App.Route key={App.id} />
))}
</>
<NotificationAlert />
<PhoneSnackbar />
<WindowSnackbar />
<Slide direction="up" timeout={{ enter: 500, exit: 500 }} in={visibility}>
<div className="PhoneWrapper">
<div
className="Phone"
style={{
position: 'fixed',
transformOrigin: 'right bottom',
transform: `scale(${settings.zoom.value}`,
bottom,
}}
>
<div
className="PhoneFrame"
style={{
backgroundImage: `url(./media/frames/${settings.frame.value})`,
}}
/>
<div
id="phone"
className="PhoneScreen"
style={{
backgroundImage: `url(./media/backgrounds/${settings.wallpaper.value})`,
}}
>
{isPhoneReady ? (
<>
<NotificationBar />
<div className="PhoneAppContainer">
<>
<Route exact path="/" component={HomeApp} />
{callModal && <Route exact path="/call" component={CallModal} />}
{apps.map((App) => (
<App.Route key={App.id} />
))}
</>
<NotificationAlert />
<PhoneSnackbar />
</div>
<Navigation />
</>
) : (
<Box
component={Paper}
height="100%"
width="100%"
display="flex"
flexDirection="column"
alignItems="center"
justifyContent="center"
>
<Typography paragraph variant="h6">
NPWD {t('INITIALIZING')}
</Typography>
<Typography paragraph>{t('GENERIC_WAIT')}</Typography>
</Box>
)}
</div>
</div>
<Navigation />
</PhoneWrapper>
</TopLevelErrorComponent>
</div>
</Slide>
</div>
);
}
export default Phone;
InjectDebugData<any>([
InjectDebugData([
{
app: 'PHONE',
method: PhoneEvents.SET_VISIBILITY,
method: 'setVisibility',
data: true,
},
{
app: 'PHONE',
method: PhoneEvents.SET_PHONE_READY,
method: 'setPhoneReady',
data: true,
},
{
app: 'PHONE',
method: PhoneEvents.SET_TIME,
data: dayjs().format('hh:mm'),
},
{
app: 'PHONE',
method: PhoneEvents.SET_CONFIG,
data: DefaultConfig,
},
]);
@@ -4,22 +4,19 @@ import { NotificationsProvider } from './os/notifications/providers/Notification
import { usePhoneTheme } from './os/phone/hooks/usePhoneTheme';
import SnackbarProvider from './ui/providers/SnackbarProvider';
import Phone from './Phone';
import { NuiProvider } from 'fivem-nui-react-lib';
import { SoundProvider } from './os/sound/providers/SoundProvider';
export const PhoneProviders = () => {
export const PhoneContainer = () => {
const currentTheme = usePhoneTheme();
return (
<NuiProvider resource="npwd">
<ThemeProvider theme={currentTheme}>
<SoundProvider>
<NotificationsProvider>
<SnackbarProvider>
<Phone />
</SnackbarProvider>
</NotificationsProvider>
</SoundProvider>
</ThemeProvider>
</NuiProvider>
<ThemeProvider theme={currentTheme}>
<SoundProvider>
<NotificationsProvider>
<SnackbarProvider>
<Phone />
</SnackbarProvider>
</NotificationsProvider>
</SoundProvider>
</ThemeProvider>
);
};
-46
View File
@@ -1,46 +0,0 @@
import React from 'react';
import { isDefaultWallpaper } from './apps/settings/utils/isDefaultWallpaper';
import { useSettings } from './apps/settings/hooks/useSettings';
import { usePhoneVisibility } from './os/phone/hooks/usePhoneVisibility';
import { Slide } from '@material-ui/core';
const PhoneWrapper: React.FC = ({ children }) => {
const [settings] = useSettings();
const { bottom, visibility } = usePhoneVisibility();
return (
<Slide direction="up" timeout={{ enter: 500, exit: 500 }} in={visibility}>
<div className="PhoneWrapper">
<div
className="Phone"
style={{
position: 'fixed',
transformOrigin: 'right bottom',
transform: `scale(${settings.zoom.value}`,
bottom,
}}
>
<div
className="PhoneFrame"
style={{
backgroundImage: `url(media/frames/${settings.frame.value})`,
}}
/>
<div
id="phone"
className="PhoneScreen"
style={{
backgroundImage: !isDefaultWallpaper(settings.wallpaper.value)
? `url(${settings.wallpaper.value})`
: `url(media/backgrounds/${settings.wallpaper.value})`,
}}
>
{children}
</div>
</div>
</div>
</Slide>
);
};
export default PhoneWrapper;
@@ -3,7 +3,8 @@ import React, { useState } from 'react';
import { Link } from 'react-router-dom';
import { BottomNavigation, BottomNavigationAction } from '@material-ui/core';
import { makeStyles } from '@material-ui/core/styles';
import { Home, List, Payment } from '@material-ui/icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faHome, faList, faMoneyCheck } from '@fortawesome/free-solid-svg-icons';
const useStyles = makeStyles((theme) => ({
root: {
@@ -29,9 +30,21 @@ export const NavigationBar = () => {
showLabels
className={classes.root}
>
<BottomNavigationAction component={Link} icon={<Home />} to="/bank" />
<BottomNavigationAction component={Link} icon={<Payment />} to="/bank/account" />
<BottomNavigationAction component={Link} icon={<List />} to="/bank/transactions" />
<BottomNavigationAction
component={Link}
icon={<FontAwesomeIcon icon={faHome} />}
to="/bank"
/>
<BottomNavigationAction
component={Link}
icon={<FontAwesomeIcon icon={faMoneyCheck} />}
to="/bank/account"
/>
<BottomNavigationAction
component={Link}
icon={<FontAwesomeIcon icon={faList} />}
to="/bank/transactions"
/>
</BottomNavigation>
);
};
@@ -49,6 +49,16 @@ export const TransactionList = () => {
</div>
</div>
))}
<TablePagination
rowsPerPageOptions={[3, 5]}
className={classes.pagination}
component="div"
count={transactionList.length}
rowsPerPage={rowsPerPage}
page={page}
onChangePage={handleChangePage}
onChangeRowsPerPage={handleChangeRowsPerPage}
/>
</div>
</div>
);
@@ -1,10 +1,10 @@
import React, { useState } from 'react';
import Modal from '../../../../ui/components/Modal';
import { Button, List, ListItem, makeStyles } from '@material-ui/core';
import { Button, List, ListItem, TextField, makeStyles } from '@material-ui/core';
import Nui from '../../../../os/nui-events/utils/Nui';
import { useBankModal } from '../../hooks/useBankModal';
import { BankEvents } from '../../../../../../typings/bank';
import { useNuiRequest } from 'fivem-nui-react-lib';
import { TextField } from '../../../../ui/components/Input';
const useStyles = makeStyles((theme) => ({
input: {
@@ -29,7 +29,6 @@ const useStyles = makeStyles((theme) => ({
}));
export const TransferModal = () => {
const Nui = useNuiRequest();
const classes = useStyles();
const [targetID, setTargetID] = useState('');
@@ -44,7 +43,7 @@ export const TransferModal = () => {
const addTransfer = () => {
const transferAmount = parseInt(amount);
Nui.send(BankEvents.ADD_TRANSFER, {
Nui.send('phone:addTransfer', {
targetID,
transferAmount,
message,
+5 -6
View File
@@ -1,4 +1,4 @@
import { useNuiEvent } from 'fivem-nui-react-lib';
import { useNuiEvent } from '../../../os/nui-events/hooks/useNuiEvent';
import { bankState } from './state';
import { useTransactions } from './useTransactions';
import { useCredentials } from './useCredentials';
@@ -6,7 +6,6 @@ import { useSetRecoilState } from 'recoil';
import { useBankNotification } from './useBankNotification';
import { IAlert, useSnackbar } from '../../../ui/hooks/useSnackbar';
import { useTranslation } from 'react-i18next';
import { BankEvents } from '../../../../../typings/bank';
export const useBankService = () => {
const setTransaction = useSetRecoilState(bankState.transactions);
@@ -22,9 +21,9 @@ export const useBankService = () => {
});
};
useNuiEvent('BANK', BankEvents.SEND_TRANSFERS, setTransaction);
useNuiEvent('BANK', BankEvents.SEND_CREDENTIALS, setCredentials);
useNuiEvent('BANK', BankEvents.SEND_ALERT, handleAddAlert);
useNuiEvent('BANK', BankEvents.SEND_NOTIFICATION, setNotification);
useNuiEvent('BANK', 'setTransaction', setTransaction);
useNuiEvent('BANK', 'setCredentials', setCredentials);
useNuiEvent('BANK', 'setAlert', handleAddAlert);
useNuiEvent('BANK', 'setNotification', setNotification);
return { useTransactions, useCredentials, useBankNotification };
};
@@ -1,108 +0,0 @@
import { AppWrapper } from '../../../ui/components';
import React, { Reducer, useReducer, useRef } from 'react';
import { AppContent } from '../../../ui/components/AppContent';
import { Box, makeStyles } from '@material-ui/core';
import { BrowserURLBar } from './BrowserURLBar';
import { promiseTimeout } from '../../../utils/promiseTimeout';
import { usePhoneConfig } from '../../../config/hooks/usePhoneConfig';
const useStyles = makeStyles(() => ({
iframe: {
height: '100%',
width: '100%',
zoom: 0.5,
border: 'none',
},
root: {
height: '100%',
display: 'flex',
flexDirection: 'column',
},
}));
interface BrowserState {
browserUrl: string;
browserHistory: string[];
}
interface ReducerAction {
payload: any;
type: ReducerActionsType;
}
enum ReducerActionsType {
SET_URL,
ADD_HISTORY,
RELOAD,
}
const browserReducer: Reducer<BrowserState, ReducerAction> = (state, action) => {
switch (action.type) {
case ReducerActionsType.ADD_HISTORY:
if (action.payload === 'about:blank') return state;
return { ...state, browserHistory: state.browserHistory.concat(action.payload) };
case ReducerActionsType.SET_URL:
return { ...state, browserUrl: action.payload };
default:
throw new Error('Invalid reducer action type');
}
};
export const BrowserApp: React.FC = () => {
const classes = useStyles();
const [{ appSettings }] = usePhoneConfig();
const [browserState, dispatch] = useReducer(browserReducer, {
browserUrl: appSettings.browserHomePage,
browserHistory: [appSettings.browserHomePage],
});
const { browserHistory, browserUrl } = browserState;
const iframeRef = useRef<HTMLIFrameElement | null>(null);
const _setBrowserUrl = (newUrl: string) => {
const formattedUrl = newUrl.match(/^(http|https):\/\//) ? newUrl : 'https://' + newUrl;
dispatch({ payload: browserUrl, type: ReducerActionsType.ADD_HISTORY });
dispatch({ payload: formattedUrl, type: ReducerActionsType.SET_URL });
};
const handleGoBack = () => {
if (browserHistory.length <= 1) return;
// Get last page from history
const lastPage = browserHistory[browserHistory.length - 1];
// Bail if last page is same as current
if (lastPage === browserUrl) return;
_setBrowserUrl(lastPage);
};
const reloadPage = async () => {
const strCopy = browserUrl.slice();
dispatch({ payload: 'about:blank', type: ReducerActionsType.SET_URL });
await promiseTimeout(100);
dispatch({ payload: strCopy, type: ReducerActionsType.SET_URL });
};
return (
<AppWrapper id="browser">
<AppContent className={classes.root}>
<BrowserURLBar
browserUrl={browserUrl}
browserHasHistory={browserHistory.length > 1}
setBrowser={_setBrowserUrl}
goBack={handleGoBack}
reloadPage={reloadPage}
/>
<Box flexGrow={1}>
<iframe
is="x-frame-bypass"
src={browserUrl}
// @ts-ignore
className={classes.iframe}
title="npwd-browser"
ref={iframeRef}
/>
</Box>
</AppContent>
</AppWrapper>
);
};
@@ -1,92 +0,0 @@
import React, { FocusEventHandler, useRef, useState } from 'react';
import { makeStyles, Theme, Box, IconButton } from '@material-ui/core';
import { Cached, KeyboardArrowLeft } from '@material-ui/icons';
import { InputBase } from '../../../ui/components/Input';
const useStyles = makeStyles((theme: Theme) => ({
urlInput: {
borderRadius: 18,
borderWidth: 1,
borderStyle: 'solid',
paddingRight: 10,
paddingLeft: 10,
marginLeft: 5,
borderColor: '#787878FF',
color: '#909090',
transition: 'color 0.1s ease',
},
urlInputFocused: {
color: '#fff',
},
root: {},
}));
interface BrowserControlsProps {
setBrowser: (url: string) => void;
browserUrl: string;
reloadPage: () => void;
browserHasHistory: boolean;
goBack: () => void;
}
export const BrowserURLBar: React.FC<BrowserControlsProps> = ({
goBack,
reloadPage,
browserHasHistory,
browserUrl,
setBrowser,
}) => {
const classes = useStyles();
const inputRef = useRef<HTMLInputElement>(null);
const [inputState, setInputState] = useState('');
const [isFocused, setFocus] = useState(false);
const handleFocus: FocusEventHandler = (e) => {
setInputState(browserUrl);
setFocus(true);
};
const handleFocusOut: FocusEventHandler = (e) => {
setFocus(false);
setInputState(browserUrl);
};
const handleChange: React.ChangeEventHandler<HTMLInputElement> = (e) => {
setInputState(e.target.value);
};
const onEnter: React.KeyboardEventHandler<HTMLInputElement> = (e) => {
if ((e as any).code !== 'Enter') return;
setBrowser(inputState);
e.currentTarget.blur();
};
const styledUrl = browserUrl.replace(/(^\w+:|^)\/\//, '');
const transformedUrl = isFocused ? inputState : styledUrl;
return (
<Box display="flex" py={1} className={classes.root} px={1}>
<IconButton size="small" onClick={() => reloadPage()}>
<Cached />
</IconButton>
{browserHasHistory && (
<IconButton size="small" onClick={() => goBack()}>
<KeyboardArrowLeft />
</IconButton>
)}
<InputBase
className={classes.urlInput}
ref={inputRef}
fullWidth
onChange={handleChange}
onKeyDown={onEnter}
value={transformedUrl}
classes={{ focused: classes.urlInputFocused }}
onFocus={handleFocus}
spellCheck={false}
onBlur={handleFocusOut}
/>
</Box>
);
};
+28 -11
View File
@@ -3,20 +3,37 @@ import { AppWrapper } from '../../../ui/components';
import { AppContent } from '../../../ui/components/AppContent';
import { GalleryGrid } from './grid/GalleryGrid';
import { GalleryModal } from './modal/GalleryModal';
import InjectDebugData from '../../../os/debug/InjectDebugData';
import { Route, Switch } from 'react-router-dom';
import { LoadingSpinner } from '../../../ui/components/LoadingSpinner';
const CameraApp: React.FC = () => (
<AppWrapper id="camera-app">
<AppContent>
<Switch>
<React.Suspense fallback={<LoadingSpinner />}>
InjectDebugData([
{
app: 'CAMERA',
method: 'setPhotos',
data: [
{
id: 1,
image: 'https://beta.iodine.gg/noDcb.jpeg',
},
{
id: 2,
image: 'https://beta.iodine.gg/teUcY.jpeg',
},
],
},
]);
const CameraApp = () => {
return (
<AppWrapper id="camera-app">
<AppContent>
<Switch>
<Route path="/camera" exact component={GalleryGrid} />
<Route path="/camera/image" exact component={GalleryModal} />
</React.Suspense>
</Switch>
</AppContent>
</AppWrapper>
);
</Switch>
</AppContent>
</AppWrapper>
);
};
export default CameraApp;
@@ -1,55 +1,36 @@
import React, { useState } from 'react';
import { Box, Button, CircularProgress } from '@material-ui/core';
import React from 'react';
import { Box, Button } from '@material-ui/core';
import useStyles from './grid.styles';
import { usePhotos } from '../../hooks/usePhotos';
import AddIcon from '@material-ui/icons/Add';
import Nui from '../../../../os/nui-events/utils/Nui';
import { useHistory } from 'react-router-dom';
import { useQueryParams } from '../../../../common/hooks/useQueryParams';
import { addQueryToLocation } from '../../../../common/utils/addQueryToLocation';
import { getLocationFromUrl } from '../../../../common/utils/getLocationFromUrl';
import { fetchNui } from '../../../../utils/fetchNui';
import { ServerPromiseResp } from '../../../../../../typings/common';
import { GalleryPhoto, PhotoEvents } from '../../../../../../typings/photo';
import { usePhotoActions } from '../../hooks/usePhotoActions';
import { usePhotosValue } from '../../hooks/state';
import { useSnackbar } from '../../../../ui/hooks/useSnackbar';
import { useTranslation } from 'react-i18next';
export const GalleryGrid = () => {
const classes = useStyles();
const history = useHistory();
const query = useQueryParams();
const { addAlert } = useSnackbar();
const { t } = useTranslation();
const photos = usePhotosValue();
const { takePhoto } = usePhotoActions();
const [isLoading, setIsLoading] = useState<boolean>(false);
const referal = query.referal ? decodeURIComponent(query.referal) : '/camera/image';
const handlePhotoOpen = (photo) => {
history.push(addQueryToLocation(getLocationFromUrl(referal), 'image', photo.image));
const photos = usePhotos();
const handleCamera = () => {
Nui.send('phone:TakePhoto', {});
};
const handleTakePhoto = () => {
setIsLoading(true);
fetchNui<ServerPromiseResp<GalleryPhoto>>(PhotoEvents.TAKE_PHOTO).then((serverResp) => {
if (serverResp.status !== 'ok') {
return addAlert({
message: t('APPS_CAMERA_FAILED_TO_TAKE_PHOTO'),
type: 'error',
});
}
takePhoto(serverResp.data);
setIsLoading(false);
});
const handlePhotoOpen = (photo) => {
history.push(addQueryToLocation(getLocationFromUrl(referal), 'image', photo.image));
};
if (!photos)
return (
<Box display="flex" flexWrap="wrap" alignContent="flex-start" className={classes.root}>
<Box>
<Button onClick={takePhoto} style={{ borderRadius: 0 }} className={classes.photo}>
<Button onClick={handleCamera} style={{ borderRadius: 0 }} className={classes.photo}>
<AddIcon fontSize="large" />
</Button>
</Box>
@@ -60,13 +41,8 @@ export const GalleryGrid = () => {
<div>
<Box display="flex" flexWrap="wrap" alignContent="flex-start" className={classes.root}>
<Box>
<Button
disabled={isLoading}
onClick={handleTakePhoto}
style={{ borderRadius: 0 }}
className={classes.photo}
>
{!isLoading ? <AddIcon fontSize="large" /> : <CircularProgress />}
<Button onClick={handleCamera} style={{ borderRadius: 0 }} className={classes.photo}>
<AddIcon fontSize="large" />
</Button>
</Box>
{photos.map((photo) => (
@@ -4,30 +4,22 @@ import { Button, Paper } from '@material-ui/core';
import ArrowBackIcon from '@material-ui/icons/ArrowBack';
import DeleteIcon from '@material-ui/icons/Delete';
import ShareIcon from '@material-ui/icons/Share';
import Nui from '../../../../os/nui-events/utils/Nui';
import { useHistory } from 'react-router-dom';
import { useQueryParams } from '../../../../common/hooks/useQueryParams';
import { ICameraPhoto } from '../../hooks/usePhotos';
import { ShareModal } from './ShareModal';
import { GalleryPhoto, PhotoEvents } from '../../../../../../typings/photo';
import { usePhotoActions } from '../../hooks/usePhotoActions';
import { fetchNui } from '../../../../utils/fetchNui';
import { ServerPromiseResp } from '../../../../../../typings/common';
import { useTranslation } from 'react-i18next';
import { useSnackbar } from '../../../../ui/hooks/useSnackbar';
export const GalleryModal = () => {
const [shareOpen, setShareOpen] = useState(null);
const classes = useStyles();
const history = useHistory();
const query = useQueryParams();
const { deletePhoto } = usePhotoActions();
const { addAlert } = useSnackbar();
const { t } = useTranslation();
const referal = query.referal || '/camera';
const meta: GalleryPhoto = useMemo(
() => ({ id: parseInt(query.id), image: query.image as string }),
const [shareOpen, setShareOpen] = useState(null);
const meta: ICameraPhoto = useMemo(
() => ({ id: query.id as string, image: query.image as string }),
[query],
);
@@ -36,17 +28,10 @@ export const GalleryModal = () => {
};
const handleDeletePhoto = () => {
fetchNui<ServerPromiseResp<GalleryPhoto>>(PhotoEvents.DELETE_PHOTO, {
Nui.send('photo:deletePhoto', {
image: meta.image,
}).then((serverResp) => {
if (serverResp.status !== 'ok') {
return addAlert({ message: t('APPS_CAMERA_FAILED_TO_DELETE_PHOTO'), type: 'error' });
}
deletePhoto(meta.image);
history.push(referal);
});
history.push(referal);
};
const handleSharePhoto = useCallback(() => {
@@ -5,11 +5,11 @@ import MessageIcon from '@material-ui/icons/Message';
import { setClipboard } from '../../../../os/phone/hooks/useClipboard';
import useStyles from './modal.styles';
import { ICameraPhoto } from '../../hooks/usePhotos';
import { useHistory } from 'react-router-dom';
import { GalleryPhoto } from '../../../../../../typings/photo';
interface IShareModalProps {
meta: GalleryPhoto;
meta: ICameraPhoto;
referal: string;
onClose(): void;
}
+3 -28
View File
@@ -1,33 +1,8 @@
import { atom, selector, useRecoilState, useRecoilValue, useSetRecoilState } from 'recoil';
import { ServerPromiseResp } from '../../../../../typings/common';
import { GalleryPhoto, PhotoEvents } from '../../../../../typings/photo';
import { fetchNui } from '../../../utils/fetchNui';
import LogDebugEvent from '../../../os/debug/LogDebugEvents';
import { isEnvBrowser } from '../../../utils/misc';
import { MockPhotoData } from '../utils/constants';
import { atom } from 'recoil';
export const photoState = {
photos: atom<GalleryPhoto[]>({
photos: atom({
key: 'galleryPhotos',
default: selector({
key: 'defaultGalleryPhotos',
get: async () => {
try {
const resp = await fetchNui<ServerPromiseResp<GalleryPhoto[]>>(PhotoEvents.FETCH_PHOTOS);
LogDebugEvent({ action: 'PhotosFetched', data: resp.data });
return resp.data;
} catch (e) {
if (isEnvBrowser()) {
return MockPhotoData;
}
console.error(e);
return [];
}
},
}),
default: null,
}),
};
export const useSetPhotos = () => useSetRecoilState(photoState.photos);
export const usePhotos = () => useRecoilState(photoState.photos);
export const usePhotosValue = () => useRecoilValue(photoState.photos);
-61
View File
@@ -1,61 +0,0 @@
import { useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { SetterOrUpdater, useRecoilState } from 'recoil';
import { GalleryPhoto, PhotoEvents } from '../../../../../typings/photo';
import { useNuiEvent, useNuiCallback } from 'fivem-nui-react-lib/';
import { useSnackbar } from '../../../ui/hooks/useSnackbar';
import { photoState } from './state';
interface IUseCamera {
photos: GalleryPhoto[];
setPhotos: SetterOrUpdater<GalleryPhoto[]>;
takePhoto: () => void;
isLoading: boolean;
}
export const useCamera = (): IUseCamera => {
const { t } = useTranslation();
const { addAlert } = useSnackbar();
const [photos, setPhotos] = useRecoilState<GalleryPhoto[]>(photoState.photos);
const [isUploading, setUploading] = useState(false);
const onPhotoSuccess = useCallback(
(photo) => {
setUploading(false);
if (!photo?.image) return;
setPhotos((curr) => [photo, ...curr]);
},
[setPhotos],
);
const onPhotoError = useCallback(
(i18nKey) => {
setUploading(false);
addAlert({ type: 'error', message: t(i18nKey) });
},
[addAlert, t],
);
const [_takePhoto] = useNuiCallback<void, GalleryPhoto>(
'CAMERA',
PhotoEvents.TAKE_PHOTO,
onPhotoSuccess,
onPhotoError,
);
useNuiEvent('CAMERA', PhotoEvents.UPLOAD_PHOTO, () => setUploading(true));
const takePhoto = () => {
// Timeout at 1 minute
_takePhoto(undefined, { timeout: 60000 });
};
return {
photos,
setPhotos,
takePhoto,
isLoading: isUploading,
};
};
@@ -1,22 +0,0 @@
import { useSetPhotos } from './state';
import { useCallback } from 'react';
export const usePhotoActions = () => {
const setPhotos = useSetPhotos();
const takePhoto = useCallback(
(photo) => {
setPhotos((curPhotos) => [photo, ...curPhotos]);
},
[setPhotos],
);
const deletePhoto = useCallback(
(image: string) => {
setPhotos((curPhotos) => [...curPhotos].filter((meta) => meta.image !== image));
},
[setPhotos],
);
return { takePhoto, deletePhoto };
};
@@ -0,0 +1,8 @@
import { useSetRecoilState } from 'recoil';
import { useNuiEvent } from '../../../os/nui-events/hooks/useNuiEvent';
import { photoState } from './state';
export const usePhotoService = () => {
const setPhotos = useSetRecoilState(photoState.photos);
useNuiEvent('CAMERA', 'setPhotos', setPhotos);
};
+11
View File
@@ -0,0 +1,11 @@
import { useRecoilValue } from 'recoil';
import { photoState } from './state';
export interface ICameraPhoto {
id: string;
image: string;
}
export const usePhotos = (): ICameraPhoto[] | null => {
return useRecoilValue<ICameraPhoto[] | null>(photoState.photos);
};
-10
View File
@@ -1,10 +0,0 @@
export const MockPhotoData = [
{
id: 1,
image: 'https://beta.iodine.gg/noDcb.jpeg',
},
{
id: 2,
image: 'https://beta.iodine.gg/teUcY.jpeg',
},
];
@@ -3,47 +3,55 @@ import { AppWrapper } from '../../../ui/components';
import { AppTitle } from '../../../ui/components/AppTitle';
import { AppContent } from '../../../ui/components/AppContent';
import { useApp } from '../../../os/apps/hooks/useApps';
import InjectDebugData from '../../../os/debug/InjectDebugData';
import { Route } from 'react-router-dom';
import ContactsInfoPage from './views/ContactInfo';
import { ContactPage } from './views/ContactsPage';
import { ContactsThemeProvider } from '../providers/ContactsThemeProvider';
import PersonAddIcon from '@material-ui/icons/PersonAdd';
import Fab from '@material-ui/core/Fab';
import { useHistory } from 'react-router';
import { makeStyles, Theme } from '@material-ui/core/styles';
import { LoadingSpinner } from '../../../ui/components/LoadingSpinner';
const useStyles = makeStyles((theme: Theme) => ({
absolute: {
position: 'absolute',
right: theme.spacing(3),
bottom: theme.spacing(2),
},
}));
export const ContactsApp = () => {
const contacts = useApp('CONTACTS');
const history = useHistory();
const classes = useStyles();
return (
<ContactsThemeProvider>
<AppWrapper id="contact-app">
<AppTitle app={contacts} />
<AppContent>
<React.Suspense fallback={<LoadingSpinner />}>
<Route path="/contacts/" exact component={ContactPage} />
<Route path="/contacts/:id" exact component={ContactsInfoPage} />
</React.Suspense>
<Route path="/contacts/" exact component={ContactPage} />
<Route path="/contacts/:id" exact component={ContactsInfoPage} />
</AppContent>
<Fab
color="primary"
onClick={() => history.push('/contacts/-1')}
className={classes.absolute}
>
<PersonAddIcon />
</Fab>
</AppWrapper>
</ContactsThemeProvider>
);
};
InjectDebugData([
{
app: 'CONTACTS',
method: 'setContacts',
data: [
{
id: 1,
display: 'Ruqen',
number: '555-15196',
},
{
id: 2,
display: 'Taso',
number: '215-8139',
avatar: 'http://i.tasoagc.dev/i9Ig',
},
{
id: 3,
display: 'Chip',
number: '111-1111',
},
{
id: 4,
display: 'Kidz',
number: '444-4444',
},
],
},
]);
@@ -1,19 +1,21 @@
import React from 'react';
import ListItemText from '@material-ui/core/ListItemText';
import { Button, ListItemAvatar, Avatar as MuiAvatar, List, ListItem } from '@material-ui/core';
import { useFilteredContacts } from '../../hooks/useFilteredContacts';
import PhoneIcon from '@material-ui/icons/Phone';
import ChatIcon from '@material-ui/icons/Chat';
import MoreVertIcon from '@material-ui/icons/MoreVert';
import { useContacts } from '../../hooks/useContacts';
import Nui from '../../../../os/nui-events/utils/Nui';
import { SearchContacts } from './SearchContacts';
import { useHistory } from 'react-router-dom';
import LogDebugEvent from '../../../../os/debug/LogDebugEvents';
import { useFilteredContacts } from '../../hooks/state';
import { useCall } from '../../../../os/call/hooks/useCall';
export const ContactList = () => {
const filteredContacts = useFilteredContacts();
const { filteredContacts } = useFilteredContacts();
const history = useHistory();
const { initializeCall } = useCall();
const { contacts } = useContacts();
const openContactInfo = (contactId: number) => {
history.push(`/contacts/${contactId}`);
@@ -25,7 +27,9 @@ export const ContactList = () => {
level: 2,
data: true,
});
initializeCall(number);
Nui.send('phone:beginCall', {
number,
});
};
const handleMessage = (phoneNumber: string) => {
@@ -37,31 +41,38 @@ export const ContactList = () => {
history.push(`/messages/new/${phoneNumber}`);
};
const filteredRegEx = new RegExp(filteredContacts, 'gi');
return (
<>
<SearchContacts />
<List>
{filteredContacts.map((contact) => (
<ListItem key={contact.id} divider>
<ListItemAvatar>
{contact.avatar ? (
<MuiAvatar src={contact.avatar} />
) : (
<MuiAvatar>{contact.display.slice(0, 1).toUpperCase()}</MuiAvatar>
)}
</ListItemAvatar>
<ListItemText primary={contact.display} secondary={contact.number} />
<Button onClick={() => startCall(contact.number)}>
<PhoneIcon />
</Button>
<Button onClick={() => handleMessage(contact.number)}>
<ChatIcon />
</Button>
<Button style={{ margin: -15 }} onClick={() => openContactInfo(contact.id)}>
<MoreVertIcon />
</Button>
</ListItem>
))}
{contacts
.filter(
(contact) =>
contact.display.match(filteredRegEx) || contact.number.match(filteredRegEx),
)
.map((contact) => (
<ListItem key={contact.id} divider>
<ListItemAvatar>
{contact.avatar ? (
<MuiAvatar src={contact.avatar} />
) : (
<MuiAvatar>{contact.display.slice(0, 1).toUpperCase()}</MuiAvatar>
)}
</ListItemAvatar>
<ListItemText primary={contact.display} secondary={contact.number} />
<Button onClick={() => startCall(contact.number)}>
<PhoneIcon />
</Button>
<Button onClick={() => handleMessage(contact.number)}>
<ChatIcon />
</Button>
<Button style={{ margin: -15 }} onClick={() => openContactInfo(contact.id)}>
<MoreVertIcon />
</Button>
</ListItem>
))}
</List>
</>
);
@@ -1,29 +1,21 @@
import React, { useEffect, useState } from 'react';
import React from 'react';
import { Box } from '@material-ui/core';
import { useTranslation } from 'react-i18next';
import { useFilteredContacts } from '../../hooks/useFilteredContacts';
import { SearchField } from '../../../../ui/components/SearchField';
import { useDebounce } from '../../../../os/phone/hooks/useDebounce';
import { useSetContactFilterInput } from '../../hooks/state';
export const SearchContacts = () => {
const { setFilteredContacts, filteredContacts } = useFilteredContacts();
const { t } = useTranslation();
const setFilterVal = useSetContactFilterInput();
const [inputVal, setInputVal] = useState('');
const debouncedVal = useDebounce<string>(inputVal, 500);
useEffect(() => {
setFilterVal(debouncedVal);
}, [debouncedVal, setFilterVal]);
return (
<Box>
<SearchField
onChange={(e) => setInputVal(e.target.value)}
onChange={(e) => setFilteredContacts(e.target.value)}
placeholder={t('APPS_CONTACT_PLACEHOLDER_SEARCH_CONTACTS')}
value={inputVal}
value={filteredContacts}
/>
</Box>
);
@@ -1,17 +1,13 @@
import React, { useEffect, useState } from 'react';
import { Avatar as MuiAvatar, Box, Button, Paper } from '@material-ui/core';
import { Avatar as MuiAvatar, Box, Button, Paper, TextField } from '@material-ui/core';
import { makeStyles } from '@material-ui/core/styles';
import { useTranslation } from 'react-i18next';
import { useHistory, useParams } from 'react-router-dom';
import { useContactActions } from '../../hooks/useContactActions';
import { useContacts } from '../../hooks/useContacts';
import Nui from '../../../../os/nui-events/utils/Nui';
import ArrowBackIcon from '@material-ui/icons/ArrowBack';
import LogDebugEvent from '../../../../os/debug/LogDebugEvents';
import { useQueryParams } from '../../../../common/hooks/useQueryParams';
import { Contact, ContactEvents, ContactsDatabaseLimits } from '../../../../../../typings/contact';
import { TextField } from '../../../../ui/components/Input';
import { fetchNui } from '../../../../utils/fetchNui';
import { ServerPromiseResp } from '../../../../../../typings/common';
import { useSnackbar } from '../../../../ui/hooks/useSnackbar';
interface ContactInfoRouteParams {
mode: string;
@@ -52,11 +48,10 @@ const useStyles = makeStyles({
const ContactsInfoPage = () => {
const classes = useStyles();
const history = useHistory();
const { getContact, addContact, updateContact, deleteContact } = useContactActions();
const { addAlert } = useSnackbar();
const { getContact } = useContacts();
const { id } = useParams<ContactInfoRouteParams>();
const { addNumber, referal } = useQueryParams<ContactInfoRouteQuery>({
@@ -72,24 +67,6 @@ const ContactsInfoPage = () => {
const { t } = useTranslation();
const handleNumberChange: React.ChangeEventHandler<HTMLInputElement> = (e) => {
const inputVal = e.target.value;
if (inputVal.length === ContactsDatabaseLimits.number) return;
setNumber(e.target.value);
};
const handleDisplayChange: React.ChangeEventHandler<HTMLInputElement> = (e) => {
const inputVal = e.target.value;
if (inputVal.length === ContactsDatabaseLimits.display) return;
setName(e.target.value);
};
const handleAvatarChange: React.ChangeEventHandler<HTMLInputElement> = (e) => {
const inputVal = e.target.value;
if (inputVal.length === ContactsDatabaseLimits.avatar) return;
setAvatar(e.target.value);
};
useEffect(() => {
if (addNumber) {
setNumber(addNumber);
@@ -102,27 +79,12 @@ const ContactsInfoPage = () => {
data: contact,
level: 2,
});
fetchNui<ServerPromiseResp<Contact>>(ContactEvents.ADD_CONTACT, {
Nui.send('phone:addContacts', {
display: name,
number,
avatar,
}).then((serverResp) => {
if (serverResp.status !== 'ok') {
return addAlert({
message: t('APPS_CONTACT_ADD_FAILED'),
type: 'error',
});
}
// Sanity checks maybe?
addContact(serverResp.data);
addAlert({
message: t('APPS_CONTACT_ADD_SUCCESS'),
type: 'success',
});
history.replace(referal);
});
history.replace(referal);
};
const handleContactSave = () => {
@@ -131,33 +93,13 @@ const ContactsInfoPage = () => {
data: contact,
level: 2,
});
fetchNui<ServerPromiseResp>(ContactEvents.UPDATE_CONTACT, {
Nui.send('phone:updateContact', {
id: contact.id,
display: name,
number,
avatar,
}).then((resp) => {
if (resp.status !== 'ok') {
return addAlert({
message: t('APPS_CONTACT_UPDATE_FAILED'),
type: 'error',
});
}
updateContact({
id: contact.id,
display: name,
number,
avatar,
});
addAlert({
message: t('APPS_CONTACT_UPDATE_SUCCESS'),
type: 'success',
});
history.goBack();
});
history.goBack();
};
const handleContactDelete = () => {
@@ -166,20 +108,10 @@ const ContactsInfoPage = () => {
data: contact,
level: 2,
});
fetchNui<ServerPromiseResp>(ContactEvents.DELETE_CONTACT, { id: contact.id }).then((resp) => {
if (resp.status !== 'ok') {
return addAlert({
message: t('APPS_CONTACT_DELETE_FAILED'),
type: 'error',
});
}
history.goBack();
deleteContact(contact.id);
addAlert({
message: t('APPS_CONTACT_DELETE_SUCCESS'),
type: 'error',
});
Nui.send('phone:deleteContact', {
id: contact.id,
});
history.goBack();
};
return (
@@ -191,10 +123,9 @@ const ContactsInfoPage = () => {
<MuiAvatar className={classes.avatar} src={avatar} />
<TextField
autoFocus
error={name.length === ContactsDatabaseLimits.display}
className={classes.input}
value={name}
onChange={handleDisplayChange}
onChange={(e) => setName(e.target.value)}
label={t('APPS_CONTACT_FORM_NAME')}
fullWidth
inputProps={{
@@ -203,9 +134,8 @@ const ContactsInfoPage = () => {
/>
<TextField
className={classes.input}
error={number.length === ContactsDatabaseLimits.number}
value={number}
onChange={handleNumberChange}
onChange={(e) => setNumber(e.target.value)}
label={t('APPS_CONTACT_FORM_NUMBER')}
fullWidth
inputProps={{
@@ -213,12 +143,11 @@ const ContactsInfoPage = () => {
}}
/>
<TextField
error={avatar.length === ContactsDatabaseLimits.avatar}
className={classes.input}
label={t('APPS_CONTACT_FORM_AVATAR')}
fullWidth
value={avatar}
onChange={handleAvatarChange}
onChange={(e) => setAvatar(e.target.value)}
inputProps={{
className: classes.inputProps,
}}
@@ -1,10 +1,37 @@
import React from 'react';
import Fab from '@material-ui/core/Fab';
import PersonAddIcon from '@material-ui/icons/PersonAdd';
import { useHistory } from 'react-router-dom';
import { makeStyles, Theme } from '@material-ui/core/styles';
import { ContactList } from '../List/ContactList';
const useStyles = makeStyles((theme: Theme) => ({
absolute: {
position: 'absolute',
bottom: theme.spacing(2),
right: theme.spacing(2),
},
icon: {
color: '#fff',
fontSize: 30,
},
}));
export const ContactPage = () => {
const history = useHistory();
const classes = useStyles();
return (
<div style={{ paddingBottom: 60 }}>
<>
<ContactList />
</div>
<Fab
color="primary"
onClick={() => history.push('/contacts/-1')}
className={classes.absolute}
>
<PersonAddIcon />
</Fab>
</>
);
};
+16 -49
View File
@@ -1,57 +1,24 @@
import { atom, selector, useRecoilState, useRecoilValue, useSetRecoilState } from 'recoil';
import { Contact, ContactEvents } from '../../../../../typings/contact';
import { fetchNui } from '../../../utils/fetchNui';
import { ServerPromiseResp } from '../../../../../typings/common';
import { isEnvBrowser } from '../../../utils/misc';
import LogDebugEvent from '../../../os/debug/LogDebugEvents';
import { BrowserContactsState } from '../utils/constants';
import { atom } from 'recoil';
export const contactsState = {
contacts: atom<Contact[]>({
contacts: atom({
key: 'contactsList',
default: selector({
key: 'contactsListDefault',
get: async () => {
try {
const resp = await fetchNui<ServerPromiseResp<Contact[]>>(ContactEvents.GET_CONTACTS);
LogDebugEvent({ action: 'ContactsFetched', data: resp.data });
return resp.data;
} catch (e) {
if (isEnvBrowser()) {
return BrowserContactsState;
}
console.error(e);
return [];
}
},
}),
default: [],
}),
filterInput: atom<string>({
key: 'filterInput',
showModal: atom({
key: 'showModal',
default: false,
}),
filterContacts: atom({
key: 'filterContacts',
default: '',
}),
filteredContacts: selector({
key: 'filteredContacts',
get: ({ get }) => {
const filterInputVal: string = get(contactsState.filterInput);
const contacts: Contact[] = get(contactsState.contacts);
if (!filterInputVal) return contacts;
const regExp = new RegExp(filterInputVal, 'gi');
return contacts.filter(
(contact) => contact.display.match(regExp) || contact.number.match(regExp),
);
},
showContactsModal: atom({
key: 'showContactModal',
default: false,
}),
contactDetail: atom({
key: 'contactDetail',
default: null,
}),
};
export const useSetContacts = () => useSetRecoilState(contactsState.contacts);
export const useContacts = () => useRecoilState(contactsState.contacts);
export const useContactsValue = () => useRecoilValue(contactsState.contacts);
export const useFilteredContacts = () => useRecoilValue(contactsState.filteredContacts);
export const useContactFilterInput = () => useRecoilState(contactsState.filterInput);
export const useSetContactFilterInput = () => useSetRecoilState(contactsState.filterInput);
@@ -1,92 +0,0 @@
import { useContacts } from './state';
import { Contact } from '../../../../../typings/contact';
import { useCallback } from 'react';
interface UseContactsValue {
getDisplayByNumber: (number: string) => string;
getContactByNumber: (number: string) => Contact | null;
getContact: (id: number) => Contact | null;
getPictureByNumber: (number: string) => string | null;
deleteContact: (id: number) => void;
addContact: (contact: Contact) => void;
updateContact: (contact: Contact) => void;
}
export const useContactActions = (): UseContactsValue => {
const [contacts, setContacts] = useContacts();
const getDisplayByNumber = useCallback(
(number: string) => {
const found = contacts.find((contact) => contact.number === number);
return found ? found.display : number;
},
[contacts],
);
const getPictureByNumber = useCallback(
(number: string) => {
const found = contacts.find((contact) => contact.number === number);
return found ? found.avatar : null;
},
[contacts],
);
const getContactByNumber = useCallback(
(number: string): Contact | null => {
for (const contact of contacts) {
if (contact.number === number) return contact;
}
return null;
},
[contacts],
);
const getContact = useCallback(
(id: number): Contact | null => {
for (const contact of contacts) {
if (contact.id === id) return contact;
}
return null;
},
[contacts],
);
const deleteContact = useCallback(
(id: number): void => {
setContacts((curContacts) => [...curContacts].filter((contact) => contact.id !== id));
},
[setContacts],
);
const addContact = useCallback(
(contact: Contact) => {
setContacts((curContacts) => [...curContacts, contact]);
},
[setContacts],
);
const updateContact = useCallback(
(updatedContact: Contact) => {
setContacts((curContacts) => {
const targetContactIndex = curContacts.findIndex(
(contact) => contact.id === updatedContact.id,
);
const newContactsArray = [...curContacts];
newContactsArray[targetContactIndex] = updatedContact;
return newContactsArray;
});
},
[setContacts],
);
return {
getDisplayByNumber,
getContact,
getContactByNumber,
getPictureByNumber,
deleteContact,
updateContact,
addContact,
};
};
@@ -0,0 +1,46 @@
import { useRecoilValue } from 'recoil';
import { contactsState } from './state';
import { Contact } from '../../../../../typings/contact';
import { useCallback } from 'react';
interface IUseContacts {
contacts: Contact[];
getDisplayByNumber: (number: string) => string;
getContactByNumber: (number: string) => Contact | null;
getContact: (id: number) => Contact | null;
}
export const useContacts = (): IUseContacts => {
const contacts = useRecoilValue(contactsState.contacts);
const getDisplayByNumber = useCallback(
(number: string) => {
const found = contacts.find((contact) => contact.number === number);
return found ? found.display : number;
},
[contacts],
);
const getContactByNumber = useCallback(
(number: string): Contact | null => {
for (const contact of contacts) {
if (contact.number === number) return contact;
}
return null;
},
[contacts],
);
const getContact = useCallback(
(id: number): Contact | null => {
for (const contact of contacts) {
if (contact.id === id) return contact;
}
return null;
},
[contacts],
);
return { contacts, getDisplayByNumber, getContact, getContactByNumber };
};
@@ -0,0 +1,23 @@
import { useNuiEvent } from '../../../os/nui-events/hooks/useNuiEvent';
import { useSetRecoilState } from 'recoil';
import { contactsState } from './state';
import { useContacts } from './useContacts';
import { IAlert, useSnackbar } from '../../../ui/hooks/useSnackbar';
import { useTranslation } from 'react-i18next';
export const useContactsService = () => {
const setContacts = useSetRecoilState(contactsState.contacts);
const { addAlert } = useSnackbar();
const { t } = useTranslation();
const handleAddAlert = ({ message, type }: IAlert) => {
addAlert({
message: t(`APPS_${message}`),
type,
});
};
useNuiEvent('CONTACTS', 'setContacts', setContacts);
useNuiEvent('CONTACTS', 'setAlert', handleAddAlert);
return useContacts();
};
@@ -0,0 +1,12 @@
import { useRecoilState } from 'recoil';
import { contactsState } from './state';
interface FilterdContactsProps {
filteredContacts: string;
setFilteredContacts: (contact: any) => void;
}
export const useFilteredContacts = (): FilterdContactsProps => {
const [filteredContacts, setFilteredContacts] = useRecoilState(contactsState.filterContacts);
return { filteredContacts, setFilteredContacts };
};
+12
View File
@@ -0,0 +1,12 @@
import { useRecoilState } from 'recoil';
import { contactsState } from './state';
interface ModalProps {
showModal: boolean;
setShowModal: (show: boolean) => void;
}
export const useModal = (): ModalProps => {
const [showModal, setShowModal] = useRecoilState(contactsState.showModal);
return { showModal, setShowModal };
};
@@ -1,24 +0,0 @@
export const BrowserContactsState = [
{
id: 1,
display: 'Ruqen',
number: '555-15196',
},
{
id: 2,
display: 'Taso',
number: '215-8139',
avatar: 'http://i.tasoagc.dev/i9Ig',
},
{
id: 3,
display: 'Chip',
number: '603-275-8373',
avatar: 'http://i.tasoagc.dev/2QYV',
},
{
id: 4,
display: 'Kidz',
number: '444-4444',
},
];
+25 -11
View File
@@ -7,17 +7,14 @@ import { useApp } from '../../../os/apps/hooks/useApps';
import { Switch, Route } from 'react-router-dom';
import DialPage from './views/DialPage';
import DialerNavBar from './DialerNavBar';
import { useDialHistory } from '../hooks/useDialHistory';
import InjectDebugData from '../../../os/debug/InjectDebugData';
import { ContactList } from '../../contacts/components/List/ContactList';
import { DialerThemeProvider } from '../providers/DialerThemeProvider';
import { Box, CircularProgress } from '@material-ui/core';
const LoadingSpinner: React.FC = () => (
<Box>
<CircularProgress />
</Box>
);
export const DialerApp = () => {
const history = useDialHistory();
const dialer = useApp('DIALER');
return (
<DialerThemeProvider>
@@ -29,11 +26,9 @@ export const DialerApp = () => {
<DialPage />
</Route>
<Route exact path="/phone">
<React.Suspense fallback={<LoadingSpinner />}>
<DialerHistory />
</React.Suspense>
<DialerHistory calls={history} />
</Route>
<Route path="/phone/contacts" component={ContactList} />
<Route path="/phone/contacts" component={ContactList}></Route>
</Switch>
</AppContent>
<DialerNavBar />
@@ -41,3 +36,22 @@ export const DialerApp = () => {
</DialerThemeProvider>
);
};
InjectDebugData([
{
app: 'DAILER',
method: 'setHistory',
data: [
{
id: 1,
transmitter: '636-6496',
start: 1612301545782,
},
{
id: 2,
transmitter: '777-7777',
start: 1612301545782,
},
],
},
]);
@@ -1,13 +1,11 @@
import React, { useContext } from 'react';
import { Box, IconButton, Paper } from '@material-ui/core';
import { Box, IconButton, InputBase, Paper } from '@material-ui/core';
import { makeStyles, Theme } from '@material-ui/core/styles';
import PhoneIcon from '@material-ui/icons/Phone';
import PersonAddIcon from '@material-ui/icons/PersonAdd';
import { DialInputCtx, IDialInputCtx } from '../context/InputContext';
import { DialInputCtx } from '../context/InputContext';
import Nui from '../../../os/nui-events/utils/Nui';
import { useHistory } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { InputBase } from '../../../ui/components/Input';
import { useCall } from '../../../os/call/hooks/useCall';
const useStyles = makeStyles((theme: Theme) => ({
root: {
@@ -31,13 +29,13 @@ const useStyles = makeStyles((theme: Theme) => ({
export const DialerInput = () => {
const classes = useStyles();
const history = useHistory();
const { t } = useTranslation();
const { initializeCall } = useCall();
const { inputVal, set } = useContext<IDialInputCtx>(DialInputCtx);
const { inputVal } = useContext(DialInputCtx);
const handleCall = (number: string) => {
initializeCall(number);
Nui.send('phone:beginCall', {
number,
});
};
const handleNewContact = (number: string) => {
@@ -46,13 +44,8 @@ export const DialerInput = () => {
return (
<Box component={Paper} className={classes.root}>
<InputBase
placeholder={t('APPS_DIALER_INPUT_PLACEHOLDER')}
className={classes.input}
value={inputVal}
onChange={(e) => set(e.target.value)}
/>
<IconButton color="primary" className={classes.iconBtn} disabled={inputVal <= ''}>
<InputBase placeholder="Enter a number" className={classes.input} value={inputVal} />
<IconButton color="primary" className={classes.iconBtn}>
<PhoneIcon fontSize="large" onClick={() => handleCall(inputVal)} />
</IconButton>
<IconButton className={classes.iconBtn}>
@@ -5,7 +5,6 @@ import { makeStyles, Theme } from '@material-ui/core/styles';
import PhoneIcon from '@material-ui/icons/Phone';
import PersonIcon from '@material-ui/icons/Person';
import HistoryIcon from '@material-ui/icons/History';
import { useTranslation } from 'react-i18next';
const useStyles = makeStyles((theme: Theme) => ({
root: {
@@ -21,7 +20,6 @@ const DialerNavBar = () => {
const classes = useStyles();
const { pathname } = useLocation();
const [page, setPage] = useState(pathname);
const { t } = useTranslation();
const handleChange = (_e, newPage) => {
setPage(newPage);
@@ -30,14 +28,14 @@ const DialerNavBar = () => {
return (
<BottomNavigation value={page} onChange={handleChange} showLabels className={classes.root}>
<BottomNavigationAction
label={t('APPS_DIALER_NAVBAR_HISTORY')}
label="History"
value="/phone"
component={NavLink}
icon={<HistoryIcon />}
to="/phone"
/>
<BottomNavigationAction
label={t('APPS_DIALER_NAVBAR_DIAL')}
label="Dial"
value="/phone/dial"
color="secondary"
component={NavLink}
@@ -45,7 +43,7 @@ const DialerNavBar = () => {
to="/phone/dial"
/>
<BottomNavigationAction
label={t('APPS_DIALER_NAVBAR_CONTACTS')}
label="Contacts"
value="/phone/contacts"
color="secondary"
component={NavLink}
@@ -28,7 +28,6 @@ const DialPage = () => {
add: (val: string) => setInputVal(inputVal + val),
removeOne: () => setInputVal(inputVal.slice(0, -1)),
clear: () => setInputVal(''),
set: (val: string) => setInputVal(val),
}}
>
<DialerInput />
@@ -5,16 +5,15 @@ import PhoneIcon from '@material-ui/icons/Phone';
import PersonAddIcon from '@material-ui/icons/PersonAdd';
import { List } from '../../../../ui/components/List';
import { ListItem } from '../../../../ui/components/ListItem';
import { useContactActions } from '../../../contacts/hooks/useContactActions';
import { CallHistoryItem } from '../../../../../../typings/call';
import Nui from '../../../../os/nui-events/utils/Nui';
import { useSimcard } from '../../../../os/simcard/hooks/useSimcard';
import { useContacts } from '../../../contacts/hooks/useContacts';
import { ICall } from '../../../../../../typings/call';
import dayjs from 'dayjs';
import { useTranslation } from 'react-i18next';
import { Box, IconButton, ListItemIcon, ListItemText } from '@material-ui/core';
import { useHistory } from 'react-router-dom';
import { makeStyles, Theme } from '@material-ui/core/styles';
import dayjs from 'dayjs';
import { useMyPhoneNumber } from '../../../../os/simcard/hooks/useMyPhoneNumber';
import { useDialHistory } from '../../hooks/useDialHistory';
import { useCall } from '../../../../os/call/hooks/useCall';
const useStyles = makeStyles((theme: Theme) => ({
callForward: {
@@ -25,26 +24,29 @@ const useStyles = makeStyles((theme: Theme) => ({
},
}));
export const DialerHistory: React.FC = () => {
const myNumber = useMyPhoneNumber();
const { getDisplayByNumber } = useContactActions();
const { initializeCall } = useCall();
const calls = useDialHistory();
export const DialerHistory = ({ calls }) => {
const { number } = useSimcard();
const { getDisplayByNumber } = useContacts();
const classes = useStyles();
const history = useHistory();
const { t } = useTranslation();
const handleCall = (phoneNumber) => {
initializeCall(phoneNumber);
Nui.send('phone:beginCall', {
number: phoneNumber,
});
};
if (!calls?.length) {
return (
<Box display="flex" justifyContent="center" alignItems="center" paddingTop={35}>
<p>
{t('APPS_DIALER_NO_HISTORY')}
<span role="img" aria-label="sad">
😞
You got no friends!
<span role="img" aria-label="deal with it">
😎
</span>
</p>
</Box>
@@ -53,58 +55,46 @@ export const DialerHistory: React.FC = () => {
return (
<List disablePadding>
{calls.map((call: CallHistoryItem) =>
call.transmitter === myNumber ? (
{calls.map((call: ICall) =>
call.transmitter === number ? (
<ListItem key={call.id} divider>
<ListItemIcon>
<PhoneForwardedIcon className={classes.callForward} />
</ListItemIcon>
<ListItemIcon>{<PhoneForwardedIcon className={classes.callForward} />}</ListItemIcon>
<ListItemText
primary={getDisplayByNumber(call.receiver)}
secondary={
// TODO: Locale changes are pending #168 merge
dayjs().to(dayjs.unix(parseInt(call.start)))
}
secondary={dayjs.unix(call.start).format(t('DATE_TIME_FORMAT'))}
/>
<IconButton onClick={() => handleCall(call.receiver)}>{<PhoneIcon />}</IconButton>
{getDisplayByNumber(call.receiver) === call.receiver && (
<IconButton
onClick={() =>
history.push(`/contacts/-1?addNumber=${call.receiver}&referal=/phone/contacts`)
}
>
<PersonAddIcon />
</IconButton>
)}
</ListItem>
) : (
<ListItem key={call.id} divider>
<ListItemIcon>
<PhoneCallbackIcon className={classes.callBack} />
</ListItemIcon>
<ListItemText
primary={getDisplayByNumber(call.transmitter)}
secondary={
// TODO: Locale changes are pending #168 merge
dayjs().to(dayjs.unix(parseInt(call.start)))
}
/>
<IconButton onClick={() => handleCall(call.transmitter)}>
<PhoneIcon />
</IconButton>
{getDisplayByNumber(call.transmitter) === call.transmitter && (
{getDisplayByNumber(call.transmitter) === call.transmitter ? (
<IconButton
onClick={() =>
history.push(`/contacts/-1?addNumber=${call.transmitter}&referal=/phone/contacts`)
}
>
<PersonAddIcon />
{<PersonAddIcon />}
</IconButton>
)}
) : null}
</ListItem>
) : (
<ListItem key={call.id} divider>
<ListItemIcon>{<PhoneCallbackIcon className={classes.callBack} />}</ListItemIcon>
<ListItemText
primary={getDisplayByNumber(call.transmitter)}
secondary={dayjs.unix(call.start).format(t('DATE_TIME_FORMAT'))}
/>
<IconButton onClick={() => handleCall(call.transmitter)}>{<PhoneIcon />}</IconButton>
{getDisplayByNumber(call.transmitter) === call.transmitter ? (
<IconButton
onClick={() =>
history.push(`/contacts/-1?addNumber=${call.transmitter}&referal=/phone/contacts`)
}
>
{<PersonAddIcon />}
</IconButton>
) : null}
</ListItem>
),
)}
@@ -5,7 +5,6 @@ export interface IDialInputCtx {
add: (char: string | number) => void;
removeOne: () => void;
clear: () => void;
set: (val) => void;
}
export const DialInputCtx = createContext(null);
+3 -24
View File
@@ -1,29 +1,8 @@
import { atom, selector } from 'recoil';
import { CallEvents, CallHistoryItem } from '../../../../../typings/call';
import { fetchNui } from '../../../utils/fetchNui';
import { ServerPromiseResp } from '../../../../../typings/common';
import LogDebugEvent from '../../../os/debug/LogDebugEvents';
import { isEnvBrowser } from '../../../utils/misc';
import { MockHistoryData } from '../utils/constants';
import { atom } from 'recoil';
export const dialState = {
history: atom<CallHistoryItem[]>({
history: atom({
key: 'dialHistory',
default: selector({
key: 'dialHistoryDefault',
get: async () => {
try {
const resp = await fetchNui<ServerPromiseResp<CallHistoryItem[]>>(CallEvents.FETCH_CALLS);
LogDebugEvent({ action: 'ContactsFetched', data: resp.data });
return resp.data;
} catch (e) {
if (isEnvBrowser()) {
return MockHistoryData;
}
console.error(e);
return [];
}
},
}),
default: [],
}),
};
@@ -1,4 +1,11 @@
import { useRecoilValue } from 'recoil';
import { ICall } from '../../../../../typings/call';
import { dialState } from './state';
interface ICallUI {
history: ICall[];
}
export const useDialHistory = () => useRecoilValue(dialState.history);
export const useDialHistory = (): ICallUI[] => {
const history = useRecoilValue(dialState.history);
return history;
};
+5 -15
View File
@@ -1,18 +1,8 @@
import { useNuiEvent } from 'fivem-nui-react-lib';
import { CallEvents } from '../../../../../typings/call';
import { IAlert, useSnackbar } from '../../../ui/hooks/useSnackbar';
import { useTranslation } from 'react-i18next';
import { useSetRecoilState } from 'recoil';
import { useNuiEvent } from '../../../os/nui-events/hooks/useNuiEvent';
import { dialState } from './state';
export const useDialService = () => {
const { addAlert } = useSnackbar();
const { t } = useTranslation();
const handleAddAlert = ({ message, type }: IAlert) => {
addAlert({
message: t(`APPS_${message}`),
type,
});
};
useNuiEvent('DIALER', CallEvents.SEND_ALERT, handleAddAlert);
const setHistory = useSetRecoilState(dialState.history);
useNuiEvent('DAILER', 'setHistory', setHistory);
};
-22
View File
@@ -1,22 +0,0 @@
import { CallHistoryItem } from '../../../../../typings/call';
export const MockHistoryData: CallHistoryItem[] = [
{
id: 1,
identifier: 'ca839e8c-ef9d-40bd-b6a3-d531ee58149f',
transmitter: '704-1549',
receiver: '704-1549',
is_accepted: true,
start: '1615939174',
end: null,
},
{
id: 2,
identifier: 'b8080a50-ad30-4ee9-84cb-00688e2bf167',
transmitter: '704-1549',
receiver: '704-1549',
is_accepted: false,
start: '1615939850',
end: null,
},
];
@@ -16,7 +16,7 @@ export const ExampleApp = () => {
const exampleString = useExample();
const example = useApp('EXAMPLE');
const [soundName, setSound] = useState('pixel.ogg');
const { play, playing, stop } = useSound('media/ringtones/' + soundName);
const { play, playing, stop } = useSound('./media/ringtones/' + soundName);
const toggleSound = () => {
if (soundName === 'pixel.ogg') {
@@ -1,4 +1,4 @@
import { useNuiEvent } from 'fivem-nui-react-lib';
import { useNuiEvent } from '../../../os/nui-events/hooks/useNuiEvent';
import { useSetRecoilState } from 'recoil';
import { exampleState } from './state';
import { useExample } from './useExample';
@@ -1,29 +0,0 @@
import React from 'react';
import { AppWrapper } from '../../../ui/components';
import { AppContent } from '../../../ui/components/AppContent';
import { MarketplaceListContainer } from './MarketplaceList/MarketplaceListContainer';
import { NavigationBar } from './navigation/NavigationBar';
import { Switch, Route } from 'react-router-dom';
import { ListingFormContainer } from './form/ListingFormContainer';
import { MarketplaceThemeProvider } from '../providers/MarketplaceThemeProvider';
import { AppTitle } from '../../../ui/components/AppTitle';
import { useApp } from '../../../os/apps/hooks/useApps';
export const MarketplaceApp = () => {
const marketplaceApp = useApp('MARKETPLACE');
return (
<MarketplaceThemeProvider>
<AppWrapper id="marketplace-app">
<AppTitle app={marketplaceApp} />
<AppContent>
<Switch>
<Route path="/marketplace" exact component={MarketplaceListContainer} />
<Route path="/marketplace/new" component={ListingFormContainer} />
</Switch>
</AppContent>
<NavigationBar />
</AppWrapper>
</MarketplaceThemeProvider>
);
};
@@ -1,16 +0,0 @@
import React from 'react';
import { List } from '../../../../ui/components/List';
import { useListingValue } from '../../hooks/state';
import { MarketplaceItem } from './MarketplaceItem';
export const MarketplaceList: React.FC = () => {
const listings = useListingValue();
return (
<List>
{listings.map((listing) => (
<MarketplaceItem key={listing.id} {...listing} />
))}
</List>
);
};
@@ -1,11 +0,0 @@
import React from 'react';
import { MarketplaceList } from './MarketplaceList';
import { LoadingSpinner } from '../../../../ui/components/LoadingSpinner';
export const MarketplaceListContainer: React.FC = () => {
return (
<React.Suspense fallback={<LoadingSpinner />}>
<MarketplaceList />
</React.Suspense>
);
};
@@ -1,160 +0,0 @@
import React, { useEffect, useState, useCallback } from 'react';
import { makeStyles, Button, Box } from '@material-ui/core';
import { MarketplaceEvents, MarketplaceListing } from '../../../../../../typings/marketplace';
import { useSnackbar } from '../../../../ui/hooks/useSnackbar';
import { useTranslation } from 'react-i18next';
import ImageIcon from '@material-ui/icons/Image';
import { useHistory, useLocation } from 'react-router-dom';
import qs from 'qs';
import { useQueryParams } from '../../../../common/hooks/useQueryParams';
import { deleteQueryFromLocation } from '../../../../common/utils/deleteQueryFromLocation';
import { TextField } from '../../../../ui/components/Input';
import { fetchNui } from '../../../../utils/fetchNui';
import { ServerPromiseResp } from '../../../../../../typings/common';
const useStyles = makeStyles((theme) => ({
root: {
width: '100%',
margin: 'auto',
textAlign: 'center',
},
input: {
marginBottom: 25,
},
textFieldInput: {
fontSize: 22,
},
multilineFieldInput: {
fontSize: 20,
},
postButton: {
display: 'block',
margin: 'auto',
background: theme.palette.primary.main,
width: '80%',
fontSize: 20,
},
}));
export const ListingForm = () => {
const classes = useStyles();
const { t } = useTranslation();
const { addAlert } = useSnackbar();
const history = useHistory();
const { pathname, search } = useLocation();
const query = useQueryParams();
const [title, setTitle] = useState('');
const [url, setUrl] = useState('');
const [description, setDescription] = useState('');
const addListing = () => {
if (title !== '' && description !== '') {
fetchNui<ServerPromiseResp<MarketplaceListing[]>>(MarketplaceEvents.ADD_LISTING, {
title,
description,
url,
}).then((resp) => {
if (resp.status !== 'ok') {
return addAlert({
message: t('APPS_MARKETPLACE_CREATE_LISTING_FAILED'),
type: 'error',
});
}
addAlert({
message: t('APPS_MARKETPLACE_CREATE_LISTING_SUCCESS'),
type: 'success',
});
history.push('/marketplace');
});
} else {
addAlert({
message: t('APPS_MARKETPLACE_REQUIRED_FIELDS'),
type: 'error',
});
}
};
/*const handleChooseImage = () => {
history.push(`/camera?${qs.stringify({
referal: encodeURIComponent(pathname + search),
})}`)
}*/
const handleChooseImage = useCallback(() => {
history.push(
`/camera?${qs.stringify({
referal: encodeURIComponent(pathname + search),
})}`,
);
}, [history, pathname, search]);
useEffect(() => {
if (!query?.image) return;
setUrl(query?.image);
history.replace(deleteQueryFromLocation({ pathname, search }, 'image'));
}, [query?.image, history, pathname, search]);
return (
<div className={classes.root}>
<h1>New Listing</h1>
<TextField
className={classes.input}
onChange={(e) => setTitle(e.target.value)}
label={t('GENERIC_REQUIRED')}
placeholder={t('APPS_MARKETPLACE_FORM_TITLE')}
inputProps={{
className: classes.textFieldInput,
maxLength: 25,
}}
style={{ width: '80%' }}
size="medium"
InputLabelProps={{
shrink: true,
}}
/>
<Box display="flex" alignItems="center" paddingLeft={5}>
<div>
<ImageIcon />
</div>
<div>
<Button onClick={handleChooseImage}>Choose a image</Button>
</div>
</Box>
<TextField
className={classes.input}
placeholder={t('APPS_MARKETPLACE_FORM_IMAGE')}
value={url}
onChange={(e) => setUrl(e.currentTarget.value)}
inputProps={{ className: classes.textFieldInput }}
style={{ width: '80%' }}
size="medium"
variant="outlined"
/>
<TextField
className={classes.input}
onChange={(e) => setDescription(e.target.value)}
label={t('GENERIC_REQUIRED')}
placeholder={t('APPS_MARKETPLACE_FORM_DESCRIPTION')}
inputProps={{
className: classes.multilineFieldInput,
maxLength: 130,
}}
style={{ width: '80%' }}
size="medium"
InputLabelProps={{
shrink: true,
}}
multiline
rows={4}
variant="outlined"
/>
<Button onClick={addListing} className={classes.postButton}>
Post
</Button>
</div>
);
};
-53
View File
@@ -1,53 +0,0 @@
import { atom, selector, useRecoilState, useRecoilValue, useSetRecoilState } from 'recoil';
import { ServerPromiseResp } from '../../../../../typings/common';
import { MarketplaceEvents, MarketplaceListing } from '../../../../../typings/marketplace';
import { fetchNui } from '../../../utils/fetchNui';
import { isEnvBrowser } from '../../../utils/misc';
const defaultData: MarketplaceListing[] = [
{
id: 1,
name: 'Some guy',
number: '111-1134',
username: 'Taso',
title: 'eeeeeeeeeeeeeeeeeeeeeeeee',
description:
'skldfsdEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE',
url: 'https://i.file.glass/706Y3.jpeg',
},
{
id: 2,
name: 'Some other dude',
number: '666-6666',
username: 'Taso',
title: 'Material',
description: 'Selling my wife',
url: '',
},
];
export const listingState = atom<MarketplaceListing[]>({
key: 'listings',
default: selector({
key: 'defaultListings',
get: async () => {
try {
const resp = await fetchNui<ServerPromiseResp<MarketplaceListing[]>>(
MarketplaceEvents.FETCH_LISTING,
);
return resp.data;
} catch (e) {
if (isEnvBrowser()) {
return defaultData;
}
console.error(e);
return [];
}
},
}),
});
export const useListingValue = () => useRecoilValue(listingState);
export const useSetListings = () => useSetRecoilState(listingState);
export const useListings = () => useRecoilState(listingState);
@@ -1,38 +0,0 @@
import { useCallback } from 'react';
import { listingState, useSetListings } from './state';
import { MarketplaceListing } from '../../../../../typings/marketplace';
import { useRecoilValueLoadable } from 'recoil';
interface MarketplaceActionValues {
deleteListing: (id: number) => void;
addListing: (listing: MarketplaceListing) => void;
}
export const useMarketplaceActions = (): MarketplaceActionValues => {
const { state: valueLoading, contents } = useRecoilValueLoadable(listingState);
const setListings = useSetListings();
const deleteListing = useCallback(
(id: number) => {
// Make sure our atom is actually loaded before we attempt a dispatch
if (valueLoading !== 'hasValue') return;
// Tts possible for the init fetch to fail and empty array is passed. In that case
// block dispatch
if (!contents.length) return;
setListings((curListings) => [...curListings].filter((listing) => listing.id !== id));
},
[setListings, valueLoading, contents],
);
const addListing = useCallback(
(listing: MarketplaceListing) => {
// Make sure our atom is actually loaded before we attempt a dispatch
if (valueLoading !== 'hasValue') return;
setListings((curListings) => [...curListings, listing]);
},
[setListings, valueLoading],
);
return { deleteListing, addListing };
};
@@ -1,38 +0,0 @@
import { useNuiEvent } from 'fivem-nui-react-lib';
import {
MarketplaceBroadcastAddDTO,
MarketplaceDeleteDTO,
MarketplaceEvents,
} from '../../../../../typings/marketplace';
import { useMarketplaceActions } from './useMarketplaceActions';
import { useCallback } from 'react';
export const useMarketplaceService = () => {
const { addListing, deleteListing } = useMarketplaceActions();
const addListingHandler = useCallback(
(resp: MarketplaceBroadcastAddDTO) => {
addListing(resp.listing);
},
[addListing],
);
const deleteListingHandler = useCallback(
(listing: MarketplaceDeleteDTO) => {
deleteListing(listing.id);
},
[deleteListing],
);
useNuiEvent<MarketplaceBroadcastAddDTO>(
'MARKETPLACE',
MarketplaceEvents.BROADCAST_ADD,
addListingHandler,
);
useNuiEvent<MarketplaceDeleteDTO>(
'MARKETPLACE',
MarketplaceEvents.BROADCAST_DELETE,
deleteListingHandler,
);
};
@@ -1,18 +0,0 @@
import { common, red } from '@material-ui/core/colors';
export const MARKETPLACE_APP_PRIMARY_COLOR = red[500];
export const MARKETPLACE_APP_ICON_COLOR = common.white;
export const MARKETPLACE_APP_TEXT_COLOR = common.black;
const theme = {
palette: {
primary: {
main: MARKETPLACE_APP_PRIMARY_COLOR,
dark: red[700],
light: red[200],
contrastText: MARKETPLACE_APP_TEXT_COLOR,
},
},
};
export default theme;
@@ -1,5 +0,0 @@
import { createAppThemeProvider } from '../../../os/apps/utils/createAppThemeProvider';
import marketplaceTheme from '../marketplace.theme';
export const MarketplaceThemeProvider = createAppThemeProvider(marketplaceTheme);
@@ -1,163 +0,0 @@
import React, { useState, useRef } from 'react';
import { Card, Fab, Box, Tooltip } from '@material-ui/core';
import CancelIcon from '@material-ui/icons/Clear';
import FireIcon from '@material-ui/icons/Whatshot';
import { makeStyles } from '@material-ui/core/styles';
import { useTranslation } from 'react-i18next';
import { FormattedProfile } from '../../../../../typings/match';
import Draggable from './Draggable';
import StatusDisplay from './StatusDisplay';
import Profile from './profile/Profile';
const useStyles = makeStyles({
root: {
position: 'absolute',
margin: '15px 15px 25px 15px',
height: 'calc(100% - 90px)',
width: 'calc(100% - 30px)',
overflow: 'hidden',
cursor: 'pointer',
},
media: {
height: '60%',
},
content: {
height: '40%',
},
status: {
position: 'absolute',
zIndex: 20,
padding: '5px 15px',
top: 40,
fontSize: '28px',
fontWeight: 'bold',
},
statusVisible: {
transition: 'opacity 0.25s ease-in-out',
},
// when a user swipes on a profile we need to hide the transition
// otherwise the status will be transitioning out when the next
// profile shows up
statusNull: {
transition: 'opacity 0s',
},
like: {
color: 'green',
border: '6px solid green',
left: 30,
transform: 'rotate(-18deg)',
},
nope: {
color: 'red',
border: '6px solid red',
right: 30,
transform: 'rotate(18deg)',
},
buttons: {
position: 'absolute',
bottom: '3px',
width: '100%',
height: '55px',
},
button: {
margin: '0px 15px',
},
});
interface IProps {
profile: FormattedProfile;
onSwipe: (id: number, liked: boolean) => void;
}
// this represents how far from the original mouse
// click a user has to drag the profile in order for
// it to be registered as a like or dislike
const DECISION_THRESHOLD_X_px = 150;
const ActiveProfile = ({ profile, onSwipe }: IProps) => {
const c = useStyles();
const { t } = useTranslation();
const [status, setStatus] = useState(null);
const statusRef = useRef(null);
const idRef = useRef(null);
// we are reading mutated state from the Draggable element so we
// keep track of it using a ref. Without this ref it will appear
// from React's point of view that the state is not updating
statusRef.current = status;
idRef.current = profile.id;
function onDrag(deltaX: number): void {
const hasDecision = status !== null;
if (!hasDecision && deltaX > DECISION_THRESHOLD_X_px) {
setStatus(true);
} else if (!hasDecision && deltaX < -DECISION_THRESHOLD_X_px) {
setStatus(false);
} else if (deltaX > -DECISION_THRESHOLD_X_px && deltaX < DECISION_THRESHOLD_X_px) {
setStatus(null);
}
}
// handles when user uses mouse to "swipe", or
// more specifically drag the card to one side or the other
const handleSwipe = () => {
onSwipe(idRef.current, statusRef.current);
setStatus(null);
};
// these handlers are explicit and used for when the
// user clicks on buttons
const handleLike = () => {
onSwipe(idRef.current, true);
setStatus(null);
};
const handleNope = () => {
onSwipe(idRef.current, false);
setStatus(null);
};
const isLiked = status === true;
const notLiked = status === false;
const likeClass = `${c.status} ${isLiked ? c.statusVisible : c.statusNull} ${c.like}`;
const nopeClass = `${c.status} ${notLiked ? c.statusVisible : c.statusNull} ${c.nope}`;
return (
<>
<Draggable id="active-profile" onDrag={onDrag} onDrop={handleSwipe}>
<Card raised className={c.root}>
<StatusDisplay className={likeClass} text={t('APPS_MATCH_LIKED')} visible={isLiked} />
<StatusDisplay className={nopeClass} text={t('APPS_MATCH_NOPE')} visible={notLiked} />
<Profile profile={profile} />
</Card>
</Draggable>
<Box className={c.buttons} display="flex" justifyContent="center">
<Tooltip title={t('APPS_MATCH_DISLIKE')} aria-label="dislike">
<Fab
size="large"
color="secondary"
aria-label="dislike"
onClick={handleNope}
className={c.button}
>
<CancelIcon />
</Fab>
</Tooltip>
<Tooltip title={t('APPS_MATCH_LIKE')} aria-label="like">
<Fab
size="large"
color="primary"
aria-label="like"
onClick={handleLike}
className={c.button}
>
<FireIcon />
</Fab>
</Tooltip>
</Box>
</>
);
};
export default ActiveProfile;
@@ -1,27 +0,0 @@
import React from 'react';
import { Link } from 'react-router-dom';
import { makeStyles } from '@material-ui/core/styles';
import { BottomNavigation, BottomNavigationAction } from '@material-ui/core';
import HomeIcon from '@material-ui/icons/Whatshot';
import GroupIcon from '@material-ui/icons/Group';
import ProfileIcon from '@material-ui/icons/Person';
const useStyles = makeStyles({
root: {
width: '100%',
},
});
export function MatchBottomNavigation({ activePage, handleChange }) {
const classes = useStyles();
return (
<BottomNavigation value={activePage} onChange={handleChange} className={classes.root}>
<BottomNavigationAction component={Link} to="/match" icon={<HomeIcon />} />
<BottomNavigationAction component={Link} to="/match/matches" icon={<GroupIcon />} />
<BottomNavigationAction component={Link} to="/match/profile" icon={<ProfileIcon />} />
</BottomNavigation>
);
}
export default MatchBottomNavigation;
@@ -1,61 +0,0 @@
import React, { useEffect, useRef } from 'react';
import { makeStyles } from '@material-ui/core';
import { LikeorDislikeDraggableElement } from '../utils/drag';
const useStyles = makeStyles({
root: {
position: 'relative',
height: '100%',
width: '100%',
},
like: {
position: 'absolute',
zIndex: 20,
padding: '5px 15px',
top: 100,
color: 'green',
border: '4px solid green',
right: 15,
},
nope: {
position: 'absolute',
zIndex: 20,
padding: '5px 15px',
top: 100,
color: 'red',
border: '4px solid red',
left: 15,
},
});
interface IProps {
id: string;
children: JSX.Element | JSX.Element[];
onDrag: (deltaX: number) => void;
onDrop: () => void;
}
const MAX_ROTATION_DEG = 15;
function Draggable({ id, children, onDrag, onDrop }: IProps) {
const classes = useStyles();
const elementRef = useRef(null);
useEffect(() => {
const drag = new LikeorDislikeDraggableElement(elementRef, MAX_ROTATION_DEG, onDrag, onDrop);
return () => drag.cleanup();
}, [elementRef]); // eslint-disable-line
return (
<>
<div ref={elementRef} key={id} id={id} className={classes.root}>
{children}
</div>
</>
);
}
export default Draggable;
-28
View File
@@ -1,28 +0,0 @@
import React from 'react';
import { useTranslation } from 'react-i18next';
import { Box, Typography } from '@material-ui/core';
import { makeStyles, Theme } from '@material-ui/core/styles';
const useStyles = makeStyles((theme: Theme) => ({
root: {
color: theme.palette.primary.main,
fontSize: theme.typography.fontSize,
height: '100%',
width: '100%',
display: 'flex',
justifyContent: 'center',
paddingTop: '140px',
},
}));
function NoProfiles() {
const classes = useStyles();
const { t } = useTranslation();
return (
<Box className={classes.root}>
<Typography variant="h5">{t('APPS_MATCH_NO_PROFILES')}</Typography>
</Box>
);
}
export default NoProfiles;
@@ -1,26 +0,0 @@
import React from 'react';
import { Box, CircularProgress } from '@material-ui/core';
import { makeStyles } from '@material-ui/core/styles';
const useStyles = makeStyles({
root: {
height: '100%',
width: '100%',
display: 'flex',
justifyContent: 'center',
},
progress: {
marginTop: '140px',
},
});
function Loader() {
const classes = useStyles();
return (
<Box className={classes.root}>
<CircularProgress size={60} className={classes.progress} />
</Box>
);
}
export default Loader;
@@ -1,31 +0,0 @@
import React, { useState } from 'react';
import { AppWrapper } from '../../../ui/components';
import { AppTitle } from '../../../ui/components/AppTitle';
import { AppContent } from '../../../ui/components/AppContent';
import { useApp } from '../../../os/apps/hooks/useApps';
import { MatchThemeProvider } from '../providers/MatchThemeProvider';
import MatchBottomNavigation from '../components/BottomNavigation';
import MatchContainer from './MatchContainer';
import { LoadingSpinner } from '../../../ui/components/LoadingSpinner';
export const MatchApp = () => {
const match = useApp('MATCH');
const [activePage, setActivePage] = useState(0);
const handlePageChange = (e, page) => setActivePage(page);
return (
<MatchThemeProvider>
<AppWrapper id="contact-app">
<AppTitle app={match} />
<AppContent>
<React.Suspense fallback={<LoadingSpinner />}>
<MatchContainer />
</React.Suspense>
</AppContent>
<MatchBottomNavigation activePage={activePage} handleChange={handlePageChange} />
</AppWrapper>
</MatchThemeProvider>
);
};
@@ -1,35 +0,0 @@
import React, { useEffect } from 'react';
import { LoadingSpinner } from '../../../ui/components/LoadingSpinner';
import ProfileEditor from './views/ProfileEditor';
import { Route } from 'react-router-dom';
import MatchPage from './views/MatchPage';
import MatchList from './views/MatchList';
import { useProfile } from '../hooks/useProfile';
const MatchContainer: React.FC = () => {
const { profile, noProfileExists, setNoProfileExists } = useProfile();
useEffect(() => {
if (!profile) {
setNoProfileExists(true);
} else {
setNoProfileExists(false);
}
}, [setNoProfileExists, profile]);
return (
<React.Suspense fallback={<LoadingSpinner />}>
{noProfileExists ? (
<ProfileEditor />
) : (
<>
<Route path="/match/" exact component={MatchPage} />
<Route path="/match/matches" exact component={MatchList} />
<Route path="/match/profile" exact component={ProfileEditor} />
</>
)}
</React.Suspense>
);
};
export default MatchContainer;
@@ -1,31 +0,0 @@
import React from 'react';
import { Box, Typography } from '@material-ui/core';
import { makeStyles, Theme } from '@material-ui/core/styles';
const useStyles = makeStyles((theme: Theme) => ({
root: {
color: theme.palette.primary.main,
fontSize: theme.typography.fontSize,
height: '100%',
width: '100%',
display: 'flex',
justifyContent: 'center',
textAlign: 'center',
padding: '140px 15px 15px 15px',
},
}));
interface IProps {
text: string;
}
function PageText({ text }: IProps) {
const classes = useStyles();
return (
<Box className={classes.root}>
<Typography variant="h5">{text}</Typography>
</Box>
);
}
export default PageText;
@@ -1,14 +0,0 @@
import React from 'react';
import { Box } from '@material-ui/core';
function StatusDisplay({ className, visible, text }) {
const style = { opacity: visible ? '0.65' : '0.0' };
return (
<Box className={className} style={style}>
{text}
</Box>
);
}
export default StatusDisplay;
@@ -1,62 +0,0 @@
import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useHistory } from 'react-router-dom';
import ListItemText from '@material-ui/core/ListItemText';
import { Box, Button, ListItem, makeStyles } from '@material-ui/core';
import PersonIcon from '@material-ui/icons/Person';
import ChatIcon from '@material-ui/icons/Chat';
import { FormattedMatch } from '../../../../../../typings/match';
import Profile from '../profile/Profile';
const useStyles = makeStyles({
profile: {
position: 'relative',
height: '90%',
marginTop: '15px',
},
});
interface IProps {
match: FormattedMatch;
}
export const Match = ({ match }: IProps) => {
const history = useHistory();
const classes = useStyles();
const { t } = useTranslation();
const [showProfile, setShowProfile] = useState(false);
const handleMessage = () => {
history.push(`/messages/new/${match.phoneNumber}`);
};
const handleProfile = () => {
setShowProfile((show) => !show);
};
const secondaryText = t('APPS_MATCH_PROFILE_MATCHED_AT', {
matchedAt: match.matchedAtFormatted,
});
return (
<>
<ListItem divider>
<ListItemText primary={match.name} secondary={secondaryText} />
<Button onClick={handleProfile}>
<PersonIcon />
</Button>
<Button onClick={handleMessage}>
<ChatIcon />
</Button>
</ListItem>
{showProfile && (
<Box className={classes.profile}>
<Profile profile={match} />
</Box>
)}
</>
);
};
export default Match;
@@ -1,77 +0,0 @@
import React from 'react';
import { CardContent, CardMedia, Chip, Typography } from '@material-ui/core';
import { makeStyles } from '@material-ui/core/styles';
import { useTranslation } from 'react-i18next';
import { FormattedProfile, FormattedMatch } from '../../../../../../typings/match';
const useStyles = makeStyles({
tags: {
position: 'absolute',
bottom: '40%',
},
tag: {
margin: '3px 3px 0px 0px',
opacity: '0.8',
},
media: {
height: '60%',
},
content: {
height: '40%',
overflowY: 'auto',
},
});
interface IProps {
profile: FormattedProfile | FormattedMatch;
}
const DEFAULT_IMAGE = 'https://upload.wikimedia.org/wikipedia/commons/a/ac/No_image_available.svg';
const Profile = ({ profile }: IProps) => {
const c = useStyles();
const { t } = useTranslation();
function parseSecondaryBio(): string | undefined {
const { location, job } = profile;
if (location && job) {
return `${location} - ${job}`;
} else if (location) {
return location;
} else if (job) {
return job;
}
}
const bioSecondary = parseSecondaryBio();
return (
<>
<CardContent className={c.tags}>
{profile.tagList.map((tag) => (
<Chip className={c.tag} label={tag} color="primary" />
))}
</CardContent>
<CardMedia className={c.media} image={profile.image || DEFAULT_IMAGE} title={profile.name} />
<CardContent className={c.content}>
<Typography gutterBottom variant="h4" component="h2">
{profile.name}
</Typography>
<Typography gutterBottom color="textSecondary" component="p">
{t('APPS_MATCH_PROFILE_LAST_ACTIVE', { lastActive: profile.lastActiveFormatted })}
</Typography>
{bioSecondary && (
<Typography gutterBottom variant="body1" color="textSecondary" component="p">
{bioSecondary}
</Typography>
)}
<Typography variant="body2" color="textSecondary" component="p">
{profile.bio}
</Typography>
</CardContent>
</>
);
};
export default Profile;
@@ -1,148 +0,0 @@
import React, { useState } from 'react';
import { makeStyles } from '@material-ui/core/styles';
import { useTranslation } from 'react-i18next';
import {
Profile as IProfile,
FormattedProfile,
MatchEvents,
} from '../../../../../../typings/match';
import ProfileField from '../../../../ui/components/ProfileField';
import UpdateButton from '../../../../ui/components/UpdateButton';
import { Card } from '@material-ui/core';
import Profile from './Profile';
import { usePhone } from '../../../../os/phone/hooks/usePhone';
import PageText from '../PageText';
import { fetchNui } from '../../../../utils/fetchNui';
import { ServerPromiseResp } from '../../../../../../typings/common';
import { useSnackbar } from '../../../../ui/hooks/useSnackbar';
import { useSetMyProfile } from '../../hooks/state';
const useStyles = makeStyles({
root: {
position: 'relative',
width: '100%',
height: 'calc(100% - 40px)',
padding: '15px',
},
card: {
position: 'absolute',
margin: '15px 15px 25px 15px',
height: 'calc(100% - 80px)',
width: 'calc(100% - 30px)',
overflow: 'hidden',
},
spacer: {
height: '8px',
},
});
interface IProps {
profile: FormattedProfile;
showPreview: boolean;
}
export function ProfileForm({ profile, showPreview }: IProps) {
const classes = useStyles();
const { t } = useTranslation();
const { ResourceConfig } = usePhone();
const { addAlert } = useSnackbar();
const setMyProfile = useSetMyProfile();
// note that this assumes we are defensively checking
// that profile is not null in a parent above this component.
// Annoyingling adding conditionals above this line to not render
// when profile === null results in a react error that different
// amounts of hooks are rendering
const [image, setImage] = useState(profile?.image || '');
const [name, setName] = useState(profile?.name || '');
const [bio, setBio] = useState(profile?.bio || '');
const [job, setJob] = useState(profile?.job || '');
const [location, setLocation] = useState(profile?.location || '');
const [tags, setTags] = useState(profile?.tags || '');
const update: FormattedProfile = {
...profile,
image,
name,
bio,
location,
job,
tagList: tags.split(',').map((tag) => tag.trim()),
};
const handleUpdate = () => {
const updatedProfile: IProfile = {
...update,
name: update.name.trim(),
image: update.image.trim(),
tags: update.tagList.join(','),
};
const event = profile ? MatchEvents.UPDATE_MY_PROFILE : MatchEvents.CREATE_MY_PROFILE;
fetchNui<ServerPromiseResp<FormattedProfile>>(event, updatedProfile).then((resp) => {
if (resp.status !== 'ok') {
return addAlert({
message: 'APPS_MATCH_UPDATE_PROFILE_FAILED',
type: 'error',
});
}
setMyProfile(resp.data);
addAlert({
message: 'APPS_MATCH_UPDATE_PROFILE_SUCCEEDED',
type: 'success',
});
});
};
if (!profile /* && !ResourceConfig.match.allowEditableProfileName*/) {
return <PageText text={t('APPS_MATCH_PROFILE_CONFIGURATION')} />;
}
if (showPreview) {
return (
<Card raised className={classes.card}>
<Profile profile={update} />
</Card>
);
}
return (
<div className={classes.root}>
<ProfileField
label={t('APPS_MATCH_EDIT_PROFILE_IMAGE')}
value={update.image}
handleChange={setImage}
allowChange
/>
<ProfileField
label={t('APPS_MATCH_EDIT_PROFILE_NAME')}
value={name}
handleChange={setName}
allowChange={ResourceConfig.match.allowEditableProfileName}
/>
<ProfileField
label={t('APPS_MATCH_EDIT_PROFILE_BIO')}
value={update.bio}
handleChange={setBio}
multiline
maxLength={250}
/>
<ProfileField
label={t('APPS_MATCH_EDIT_PROFILE_LOCATION')}
value={update.location}
handleChange={setLocation}
/>
<ProfileField
label={t('APPS_MATCH_EDIT_PROFILE_JOB')}
value={update.job}
handleChange={setJob}
maxLength={50}
/>
<ProfileField label={t('APPS_MATCH_EDIT_PROFILE_TAGS')} value={tags} handleChange={setTags} />
<UpdateButton handleClick={handleUpdate} loading={false} />
</div>
);
}
export default ProfileForm;
@@ -1,34 +0,0 @@
import React from 'react';
import { useTranslation } from 'react-i18next';
import { Box, makeStyles } from '@material-ui/core';
import Loader from '../Loader';
import PageText from '../PageText';
import Match from '../matches/Match';
import { useMatches } from '../../hooks/useMatches';
const useStyles = makeStyles({
root: {
height: '100%',
},
});
function MatchList() {
const classes = useStyles();
const { t } = useTranslation();
const { matches, error } = useMatches();
if (error) return <PageText text={t('APPS_MATCH_MATCHES_ERROR')} />;
if (!matches) return <Loader />;
if (matches.length === 0) return <PageText text={t('APPS_MATCH_NO_MATCHES')} />;
return (
<Box className={classes.root}>
{matches.map((match) => (
<Match key={match.id} match={match} />
))}
</Box>
);
}
export default MatchList;
@@ -1,55 +0,0 @@
import React, { useEffect, useState } from 'react';
import { Paper } from '@material-ui/core';
import { makeStyles } from '@material-ui/core/styles';
import { useTranslation } from 'react-i18next';
import { useProfiles } from '../../hooks/useProfiles';
import Loader from '../Loader';
import PageText from '../PageText';
import ActiveProfile from '../ActiveProfile';
import { useMatchActions } from '../../hooks/useMatchActions';
const useStyles = makeStyles({
root: {
height: '100%',
width: '100%',
overflow: 'hidden',
},
});
// set a minimum load time so the user doesn't see a flash
// of the loader and then the matches themselves
const MINIMUM_LOAD_TIME = 1250;
const MatchPage = () => {
const classes = useStyles();
const { t } = useTranslation();
const { profiles, error, activeProfile } = useProfiles();
const { setViewed } = useMatchActions();
const [loaded, setLoaded] = useState(false);
useEffect(() => {
window.setTimeout(() => {
setLoaded(true);
}, MINIMUM_LOAD_TIME);
}, []);
const handleSwipe = (id: number, liked: boolean) => {
// the user didn't choose (didn't swipe far enough)
if (liked === null) return;
setViewed(id, liked);
};
if (error) return <PageText text={t('APPS_MATCH_PROFILES_ERROR')} />;
if (!loaded || !profiles) return <Loader />;
if (!activeProfile) return <PageText text={t('APPS_MATCH_NO_PROFILES')} />;
return (
<Paper className={classes.root} square>
<ActiveProfile profile={activeProfile} onSwipe={handleSwipe} />
</Paper>
);
};
export default MatchPage;
@@ -1,44 +0,0 @@
import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { makeStyles } from '@material-ui/core/styles';
import { Box, FormControlLabel, Switch } from '@material-ui/core';
import Loader from '../Loader';
import ProfileForm from '../profile/ProfileForm';
import { useProfile } from '../../hooks/useProfile';
const useStyles = makeStyles({
root: {
height: '100%',
width: '100%',
},
switch: {
marginLeft: '15px',
},
});
function ProfileEditor() {
const { profile, noProfileExists } = useProfile();
const classes = useStyles();
const { t } = useTranslation();
const [showPreview, setShowPreview] = useState(false);
const toggleSwitch = () => {
setShowPreview((preview) => !preview);
};
if (!profile && !noProfileExists) return <Loader />;
return (
<Box className={classes.root}>
<Box className={classes.switch}>
<FormControlLabel
control={<Switch checked={showPreview} onChange={toggleSwitch} />}
label={t('APPS_MATCH_EDIT_PROFILE_PREVIEW')}
/>
</Box>
<ProfileForm showPreview={showPreview} profile={profile} />
</Box>
);
}
export default ProfileEditor;
-98
View File
@@ -1,98 +0,0 @@
import { atom, selector, useRecoilState, useRecoilValue, useSetRecoilState } from 'recoil';
import { FormattedMatch, FormattedProfile, MatchEvents } from '../../../../../typings/match';
import { fetchNui } from '../../../utils/fetchNui';
import { ServerPromiseResp } from '../../../../../typings/common';
import LogDebugEvent from '../../../os/debug/LogDebugEvents';
import { isEnvBrowser } from '../../../utils/misc';
import { MockMatchesData, MockMyProfileData, MockProfilesData } from '../utils/constants';
export const matchState = {
profiles: atom<FormattedProfile[]>({
key: 'profiles',
default: selector({
key: 'matchDefaultProfiles',
get: async () => {
try {
const resp = await fetchNui<ServerPromiseResp<FormattedProfile[]>>(
MatchEvents.GET_PROFILES,
);
LogDebugEvent({ action: 'fetchProfiles', data: resp.data });
return resp.data;
} catch (e) {
if (isEnvBrowser()) {
return MockProfilesData;
}
console.error(e);
return [];
}
},
}),
}),
errorLoadingProfiles: atom<boolean>({
key: 'errorLoadingProfiles',
default: false,
}),
matches: atom<FormattedMatch[]>({
key: 'matches',
default: selector({
key: 'defaultMatches',
get: async () => {
try {
const resp = await fetchNui<ServerPromiseResp<FormattedMatch[]>>(MatchEvents.GET_MATCHES);
LogDebugEvent({ action: 'fetchMatches', data: resp.data });
return resp.data;
} catch (e) {
if (isEnvBrowser()) {
return MockMatchesData;
}
console.log(e);
return [];
}
},
}),
}),
errorLoadingMatches: atom<boolean>({
key: 'errorLoadingMatches',
default: false,
}),
myProfile: atom<FormattedProfile | null>({
key: 'myProfile',
default: selector({
key: 'myProfileDefault',
get: async () => {
try {
const resp = await fetchNui<ServerPromiseResp<FormattedProfile>>(
MatchEvents.GET_MY_PROFILE,
);
LogDebugEvent({ action: 'fetchMyProfile', data: resp.data });
return resp.data;
} catch (e) {
if (isEnvBrowser()) {
return MockMyProfileData;
}
console.error(e);
return null;
}
},
}),
}),
noProfileExists: atom<boolean>({
key: 'noProfileExists',
default: false,
}),
};
export const useFormattedProfiles = () => useRecoilState(matchState.profiles);
export const useFormattedProfilesValue = () => useRecoilValue(matchState.profiles);
export const useSetFormattedProfiles = () => useSetRecoilState(matchState.profiles);
export const useMyProfile = () => useRecoilState(matchState.myProfile);
export const useMyProfileValue = () => useRecoilValue(matchState.myProfile);
export const useSetMyProfile = () => useSetRecoilState(matchState.myProfile);
export const useProfileExistsValue = () => useRecoilValue(matchState.noProfileExists);
export const useProfileExists = () => useRecoilState(matchState.noProfileExists);
export const useFormattedMatches = () => useRecoilState(matchState.matches);
export const useMatchesValue = () => useRecoilValue(matchState.matches);
export const useSetMatches = () => useSetRecoilState(matchState.matches);
@@ -1,51 +0,0 @@
import { FormattedMatch, MatchEvents } from '../../../../../typings/match';
import { fetchNui } from '../../../utils/fetchNui';
import { ServerPromiseResp } from '../../../../../typings/common';
import { useSetFormattedProfiles, useSetMatches } from './state';
import { useSnackbar } from '../../../ui/hooks/useSnackbar';
import { useCallback } from 'react';
export const useMatchActions = () => {
const setProfiles = useSetFormattedProfiles();
const setMatches = useSetMatches();
const { addAlert } = useSnackbar();
const setViewed = useCallback(
(id: number, liked: boolean) => {
setProfiles((profiles) =>
profiles.map((profile) => {
if (id === profile.id) return { ...profile, viewed: true, liked };
return profile;
}),
);
fetchNui<ServerPromiseResp<boolean>>(MatchEvents.SAVE_LIKES, [{ id, liked }]).then((resp) => {
if (resp.status !== 'ok') {
return addAlert({
message: 'APPS_MATCH_SAVE_LIKES_FAILED',
type: 'error',
});
}
// Instead of just fetching the matches again, we might want to first format the profile to a 'Match',then to a 'FormattedMatch'
// and then just mutate the already existing state of matches?
// I guess that's for another time :P
if (resp.data) {
addAlert({
message: 'APPS_MATCH_NEW_LIKE_FOUND',
type: 'info',
});
fetchNui<ServerPromiseResp<FormattedMatch[]>>(MatchEvents.GET_MATCHES).then((resp) => {
setMatches(resp.data);
});
}
});
},
[setProfiles, addAlert, setMatches],
);
return {
setViewed,
};
};
-16
View File
@@ -1,16 +0,0 @@
import { matchState, useFormattedMatches } from './state';
import { useRecoilValue } from 'recoil';
import { FormattedMatch } from '../../../../../typings/match';
interface UseMatchProps {
matches: FormattedMatch[];
setMatches: (matches: FormattedMatch[]) => void;
error: boolean;
}
export const useMatches = (): UseMatchProps => {
const [matches, setMatches] = useFormattedMatches();
const error = useRecoilValue(matchState.errorLoadingMatches);
return { matches, setMatches, error };
};
-16
View File
@@ -1,16 +0,0 @@
import { useMyProfile, useProfileExists } from './state';
import { FormattedProfile } from '../../../../../typings/match';
interface UseProfileProps {
profile: FormattedProfile;
setProfile: (profile: FormattedProfile) => void;
noProfileExists: boolean;
setNoProfileExists: (exists: boolean) => void;
}
export const useProfile = (): UseProfileProps => {
const [profile, setProfile] = useMyProfile();
const [noProfileExists, setNoProfileExists] = useProfileExists();
return { profile, setProfile, noProfileExists, setNoProfileExists };
};
-20
View File
@@ -1,20 +0,0 @@
import { useRecoilValue } from 'recoil';
import { matchState, useFormattedProfiles } from './state';
import { FormattedProfile } from '../../../../../typings/match';
interface UseProfilesProps {
profiles: FormattedProfile[];
activeProfile: FormattedProfile | null;
error: boolean;
}
export const useProfiles = (): UseProfilesProps => {
const [profiles] = useFormattedProfiles();
const error = useRecoilValue(matchState.errorLoadingProfiles);
const filteredProfiles = profiles ? profiles.filter((profile) => !profile.viewed) : null;
const activeProfile = profiles ? filteredProfiles[0] : null;
return { profiles, activeProfile, error };
};
-27
View File
@@ -1,27 +0,0 @@
import { red, common } from '@material-ui/core/colors';
export const MATCH_APP_PRIMARY_COLOR = '#FE3B73';
export const MATCH_APP_TEXT_COLOR = common.white;
const theme = {
palette: {
primary: {
main: MATCH_APP_PRIMARY_COLOR,
dark: red[700],
light: red[300],
contrastText: MATCH_APP_TEXT_COLOR,
},
secondary: {
main: '#d32f2f',
light: '#eb4242',
dark: '#941212',
contrastText: MATCH_APP_TEXT_COLOR,
},
success: {
main: '#2196f3',
contrastText: MATCH_APP_TEXT_COLOR,
},
},
};
export default theme;
@@ -1,5 +0,0 @@
import { createAppThemeProvider } from '../../../os/apps/utils/createAppThemeProvider';
import matchTheme from '../match.theme';
export const MatchThemeProvider = createAppThemeProvider(matchTheme);
-116
View File
@@ -1,116 +0,0 @@
import { FormattedMatch, FormattedProfile } from '../../../../../typings/match';
export const MockProfilesData: FormattedProfile[] = [
{
id: 1,
identifier: '3r523242',
viewed: false,
image:
'https://cdn.vox-cdn.com/thumbor/9xCALlkm2Mc0HQk8kMr1Ui3YNbc=/0x0:5464x3070/920x613/filters:focal(2295x1098:3169x1972):format(webp)/cdn.vox-cdn.com/uploads/chorus_image/image/67031748/shutterstock_1450403549.0.jpg',
name: 'Evan You',
bio: 'Husband, father of two, independent open source developer. Creator / project lead of @vuejs, @vite_js and connoisseur of sushi.',
createdAt: 1615932985,
updatedAt: 1615932985,
lastActive: 1616004986,
job: 'Gardener',
location: 'Grapeseed',
tags: 'shit framework, vue sucks',
phoneNumber: '987-6543',
tagList: ['shitframework', 'vue sucks'],
lastActiveFormatted: '1616004986',
},
{
id: 2,
identifier: '3r523242',
viewed: false,
image:
'https://media.cntraveler.com/photos/5f8f09c3a078e9112956774d/16:9/w_1600%2Cc_limit/Chicago-GettyImages-1065188752.jpg',
name: 'Person Beta',
bio: 'l impedit quo minus id quod maxime placeat facere possimus',
createdAt: 1615846585,
updatedAt: 1615846585,
lastActive: 1615850185,
job: 'Mechanic',
location: 'Harmony',
tags: 'tinkering,robotics',
phoneNumber: '654-3219',
tagList: ['tinkering', 'robotics'],
lastActiveFormatted: '12332425',
},
{
id: 3,
identifier: '3r523242',
viewed: false,
image: 'https://www.langan.com/wp-content/uploads/2019/02/Boston-996x554.jpg',
name: 'Person Charlie',
bio: 'ut aut reiciendis voluptatibus',
createdAt: 1615850185,
updatedAt: 1615850185,
lastActive: 1613607385,
job: 'Lawyer',
location: 'Los Santos',
tags: 'reading,coolstuff, coffee',
phoneNumber: '123-4567',
tagList: ['reading', 'coolstuff', 'coffee'],
lastActiveFormatted: '12332425',
},
];
export const MockMyProfileData: FormattedProfile = {
id: 4,
identifier: '4785656',
viewed: false,
image:
'https://www.middlebury.edu/institute/sites/www.middlebury.edu.institute/files/styles/1040x585/public/2018-10/Nashville-skyline.jpg?fv=mS11EKrT&itok=HNhHqYUX',
name: 'Kire Says',
bio: "Kire's cool profile that has many cool things. And others.",
createdAt: 1615932985,
updatedAt: 1615932985,
lastActive: 1616004986,
job: 'Engineer',
location: 'Boston',
tags: 'code,javascript',
phoneNumber: '999-9999',
tagList: ['code', 'javascript'],
lastActiveFormatted: '12332425',
};
export const MockMatchesData: FormattedMatch[] = [
{
id: 5,
identifier: '4785656',
viewed: true,
image:
'https://media.cntraveler.com/photos/5f8f09c3a078e9112956774d/16:9/w_1600%2Cc_limit/Chicago-GettyImages-1065188752.jpg',
name: 'Taso',
bio: 'l impedit quo minus id quod maxime placeat facere possimus',
createdAt: 1615846585,
updatedAt: 1615846585,
lastActive: 1615850185,
job: 'Mechanic',
location: 'Harmony',
tags: 'tinkering,robotics',
tagList: ['tinkering', 'robotics'],
lastActiveFormatted: '525343252',
matchedAtFormatted: '3452355',
phoneNumber: '654-3219',
},
{
id: 6,
identifier: '4785656',
viewed: true,
image: 'https://www.langan.com/wp-content/uploads/2019/02/Boston-996x554.jpg',
name: 'Chip',
bio: 'ut aut reiciendis voluptatibus',
createdAt: 1615850185,
updatedAt: 1615850185,
lastActive: 1613607385,
job: 'Lawyer',
location: 'Los Santos',
tags: 'reading,coolstuff, coffee',
tagList: ['reading', 'coolstuff', 'coffee'],
phoneNumber: '123-4567',
lastActiveFormatted: '525343252',
matchedAtFormatted: '3452355',
},
];
-161
View File
@@ -1,161 +0,0 @@
interface IDeltas {
deltaX: number;
deltaY: number;
}
/**
* Given a React ref, which should point to some HTML element,
* add draggable functionality to that element so the user can
* interact with it.
*
* It should be noted that when using this in React that this
* class is directly mutating the DOM, not relying on React state
* to do so. This can cause some problems when relying on React
* state updates based on the values derived from this class. That
* is why we primarily use refs to interact with it.
*
* Order of operations:
* 1. User clicks "down" on element - this initializes event
* handlers and saves initial state
* 2. User moves mouse. Every mouse move event triggers a movement
* of the HTML element and also performs some logic to see how far
* we have moved
* 3. User "releases" mouse - cleanup event handlers and do logic
* to compare our final position to our initial position
*/
export class DraggableElement {
private element: HTMLElement;
private width: number = 0;
private initialX: number = 0;
private initialY: number = 0;
private mouseDownInitialX: number = 0;
private mouseDownInitialY: number = 0;
private useRotation: boolean;
private maxRotationDeg: null | number;
private updatedX: number = 0;
private updatedY: number = 0;
private mouseDownX: number = 0;
private mouseDownY: number = 0;
constructor(ref: React.MutableRefObject<any>, maxRotationDeg: number | null = null) {
this.element = ref.current;
this.width = this.element.clientWidth;
this.maxRotationDeg = maxRotationDeg;
this.useRotation = maxRotationDeg !== null;
this.element.onmousedown = this.onMouseDown;
}
onMouseDown = (e: MouseEvent): void => {
e.preventDefault();
// get the mouse cursor position at startup:
this.mouseDownX = e.clientX;
this.mouseDownY = e.clientY;
// save where we initially started dragging from
// so we can do some math later
this.mouseDownInitialX = this.mouseDownX;
this.mouseDownInitialY = this.mouseDownY;
document.onmouseup = this.onMouseUp;
// call a function whenever the cursor moves:
document.onmousemove = this.onMouseMove;
};
onMouseMove = (e: MouseEvent): void => {
e.preventDefault();
const x = e.clientX;
const y = e.clientY;
this._onMouseMove(x, y);
};
_onMouseMove = (x: number, y: number): void => {
// calculate the new cursor position:
this.updatedX = this.mouseDownX - x;
this.updatedY = this.mouseDownY - y;
this.mouseDownX = x;
this.mouseDownY = y;
// set the element's new position:
this.element.style.top = this.element.offsetTop - this.updatedY + 'px';
this.element.style.left = this.element.offsetLeft - this.updatedX + 'px';
if (this.useRotation) {
const { deltaX } = this.deltas(this.mouseDownX, this.mouseDownY);
const pctWidth = deltaX / this.width;
const rotationDeg = -1 * this.maxRotationDeg * pctWidth;
this.element.style.webkitTransform = `rotate(${rotationDeg}deg)`;
}
};
onMouseUp = (e: MouseEvent): void => {
e.preventDefault();
this._onMouseUp();
};
_onMouseUp = (): void => {
// stop moving when mouse button is released:
this.cleanup();
// revert back to intitial position
this.element.style.left = `${this.initialX}px`;
this.element.style.top = `${this.initialY}px`;
if (this.useRotation) {
this.element.style.webkitTransform = 'rotate(0deg)';
}
};
cleanup = (): void => {
document.onmouseup = null;
document.onmousemove = null;
};
deltas = (x: number, y: number): IDeltas => {
const deltaX = x - this.mouseDownInitialX;
const deltaY = y - this.mouseDownInitialX;
return { deltaX, deltaY };
};
}
type StatusChange = (deltaX: number) => void;
/**
* This class adds hooks to the base DraggableElement class
* so we can update application state based on events
*/
export class LikeorDislikeDraggableElement extends DraggableElement {
private onDrag: StatusChange;
private onDrop: () => void;
constructor(
ref: React.MutableRefObject<any>,
maxRotationDeg: number,
onDrag: StatusChange,
onDrop: () => void,
) {
super(ref, maxRotationDeg);
this.onDrag = onDrag;
this.onDrop = onDrop;
}
onMouseMove = (e: MouseEvent): void => {
e.preventDefault();
const x = e.clientX;
const y = e.clientY;
const { deltaX } = this.deltas(x, y);
this.onDrag(deltaX);
this._onMouseMove(x, y);
};
onMouseUp = (): void => {
this.onDrop();
this._onMouseUp();
};
}
@@ -9,42 +9,37 @@ import { Route, Switch, useHistory } from 'react-router-dom';
import { MessageModal } from './modal/MessageModal';
import InjectDebugData from '../../../os/debug/InjectDebugData';
import NewMessageGroupButton from './form/NewMessageGroupButton';
import { useNuiRequest } from 'fivem-nui-react-lib';
import Nui from '../../../os/nui-events/utils/Nui';
import { MessagesThemeProvider } from '../providers/MessagesThemeProvider';
import { MessageEvents } from '../../../../../typings/messages';
import { LoadingSpinner } from '../../../ui/components/LoadingSpinner';
export const MessagesApp = () => {
const Nui = useNuiRequest();
const messages = useApp('MESSAGES');
const history = useHistory();
useEffect(() => {
Nui.send(MessageEvents.FETCH_MESSAGE_GROUPS);
}, [Nui]);
Nui.send('phone:fetchMessageGroups');
}, []);
return (
<MessagesThemeProvider>
<AppWrapper id="messages-app">
<AppTitle app={messages} />
<AppContent>
<React.Suspense fallback={<LoadingSpinner />}>
<Switch>
<Route path="/messages/conversations/:groupId">
<div>
<MessageModal />
</div>
</Route>
<Route exact path="/messages">
<MessagesList />
</Route>
</Switch>
<Switch>
<Route exact path={['/messages/new/:phoneNumber', '/messages/new']}>
<MessageGroupModal />
</Route>
</Switch>
</React.Suspense>
<Switch>
<Route path="/messages/conversations/:groupId">
<div>
<MessageModal />
</div>
</Route>
<Route exact path="/messages">
<MessagesList />
</Route>
</Switch>
<Switch>
<Route exact path={['/messages/new/:phoneNumber', '/messages/new']}>
<MessageGroupModal />
</Route>
</Switch>
</AppContent>
<Route exact path="/messages">
<NewMessageGroupButton onClick={() => history.push('/messages/new')} />
@@ -57,7 +52,7 @@ export const MessagesApp = () => {
InjectDebugData([
{
app: 'MESSAGES',
method: MessageEvents.FETCH_MESSAGE_GROUPS_SUCCESS,
method: 'phone:fetchMessageGroupsSuccess',
data: [
{
groupId: '2',
@@ -97,7 +92,7 @@ InjectDebugData(
[
{
app: 'MESSAGES',
method: MessageEvents.FETCH_MESSAGES_SUCCESS,
method: 'phone:fetchMessagesSuccess',
data: [
{
id: 1,
Loaded 100 of 421 files, more files were not shown because too many files have changed in this diff. Show more