Browse Source

<project> done

Евгения Акиншина 3 years ago
parent
commit
5ff49a9722

+ 23 - 0
.gitignore

@@ -0,0 +1,23 @@
+# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
+
+# dependencies
+/node_modules
+/.pnp
+.pnp.js
+
+# testing
+/coverage
+
+# production
+/build
+
+# misc
+.DS_Store
+.env.local
+.env.development.local
+.env.test.local
+.env.production.local
+
+npm-debug.log*
+yarn-debug.log*
+yarn-error.log*

File diff suppressed because it is too large
+ 16656 - 0
package-lock.json


+ 48 - 0
package.json

@@ -0,0 +1,48 @@
+{
+  "name": "myproject",
+  "version": "0.1.0",
+  "private": true,
+  "dependencies": {
+    "@testing-library/jest-dom": "^5.14.1",
+    "@testing-library/react": "^11.2.7",
+    "@testing-library/user-event": "^12.8.3",
+    "base-64": "^1.0.0",
+    "base64-arraybuffer": "^1.0.1",
+    "codemirror": "^5.62.3",
+    "react": "^17.0.2",
+    "react-codemirror2": "^7.2.1",
+    "react-dom": "^17.0.2",
+    "react-dropzone": "^11.4.2",
+    "react-redux": "^7.2.5",
+    "react-router-dom": "^5.3.0",
+    "react-scripts": "4.0.3",
+    "redux": "^4.1.1",
+    "redux-thunk": "^2.3.0",
+    "web-vitals": "^1.1.2"
+  },
+  "scripts": {
+    "start": "react-scripts start",
+    "build": "react-scripts build",
+    "test": "react-scripts test",
+    "eject": "react-scripts eject"
+  },
+  "eslintConfig": {
+    "extends": [
+      "react-app",
+      "react-app/jest"
+    ]
+  },
+  "browserslist": {
+    "production": [
+      ">0.2%",
+      "not dead",
+      "not op_mini all"
+    ],
+    "development": [
+      "last 1 chrome version",
+      "last 1 firefox version",
+      "last 1 safari version"
+    ]
+  },
+  "proxy": "http://snippet.asmer.fs.a-level.com.ua/"
+}

BIN
public/favicon.ico


+ 43 - 0
public/index.html

@@ -0,0 +1,43 @@
+<!DOCTYPE html>
+<html lang="en">
+  <head>
+    <meta charset="utf-8" />
+    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
+    <meta name="viewport" content="width=device-width, initial-scale=1" />
+    <meta name="theme-color" content="#000000" />
+    <meta
+      name="description"
+      content="Web site created using create-react-app"
+    />
+    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
+    <!--
+      manifest.json provides metadata used when your web app is installed on a
+      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
+    -->
+    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
+    <!--
+      Notice the use of %PUBLIC_URL% in the tags above.
+      It will be replaced with the URL of the `public` folder during the build.
+      Only files inside the `public` folder can be referenced from the HTML.
+
+      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
+      work correctly both with client-side routing and a non-root public URL.
+      Learn how to configure a non-root public URL by running `npm run build`.
+    -->
+    <title>React App</title>
+  </head>
+  <body>
+    <noscript>You need to enable JavaScript to run this app.</noscript>
+    <div id="root"></div>
+    <!--
+      This HTML file is a template.
+      If you open it directly in the browser, you will see an empty page.
+
+      You can add webfonts, meta tags, or analytics to this file.
+      The build step will place the bundled scripts into the <body> tag.
+
+      To begin the development, run `npm start` or `yarn start`.
+      To create a production bundle, use `npm run build` or `yarn build`.
+    -->
+  </body>
+</html>

BIN
public/logo192.png


BIN
public/logo512.png


+ 25 - 0
public/manifest.json

@@ -0,0 +1,25 @@
+{
+  "short_name": "React App",
+  "name": "Create React App Sample",
+  "icons": [
+    {
+      "src": "favicon.ico",
+      "sizes": "64x64 32x32 24x24 16x16",
+      "type": "image/x-icon"
+    },
+    {
+      "src": "logo192.png",
+      "type": "image/png",
+      "sizes": "192x192"
+    },
+    {
+      "src": "logo512.png",
+      "type": "image/png",
+      "sizes": "512x512"
+    }
+  ],
+  "start_url": ".",
+  "display": "standalone",
+  "theme_color": "#000000",
+  "background_color": "#ffffff"
+}

+ 3 - 0
public/robots.txt

@@ -0,0 +1,3 @@
+# https://www.robotstxt.org/robotstxt.html
+User-agent: *
+Disallow:

+ 38 - 0
src/App.css

@@ -0,0 +1,38 @@
+.App {
+  text-align: center;
+}
+
+.App-logo {
+  height: 40vmin;
+  pointer-events: none;
+}
+
+@media (prefers-reduced-motion: no-preference) {
+  .App-logo {
+    animation: App-logo-spin infinite 20s linear;
+  }
+}
+
+.App-header {
+  background-color: #282c34;
+  min-height: 100vh;
+  display: flex;
+  flex-direction: column;
+  align-items: center;
+  justify-content: center;
+  font-size: calc(10px + 2vmin);
+  color: white;
+}
+
+.App-link {
+  color: #61dafb;
+}
+
+@keyframes App-logo-spin {
+  from {
+    transform: rotate(0deg);
+  }
+  to {
+    transform: rotate(360deg);
+  }
+}

+ 34 - 0
src/App.js

@@ -0,0 +1,34 @@
+import './App.css';
+import { BrowserRouter as Router, Route, Link, Switch } from 'react-router-dom';
+import createHistory from "history/createBrowserHistory";
+import {Provider, connect} from 'react-redux';
+import { actionFullLogin, actionFullRegister, actionUploadFile } from './actions';
+import { LoginForm } from './components/LoginForm';
+import { FormReg } from './components/FormReg';
+import { FormDate } from './components/FormDate';
+import { Main } from './pages/Main';
+import store from './reducers';
+
+const ConnectLoginForm = connect(null, {onLogin:actionFullLogin}) (LoginForm) 
+
+const ConnectFormReg = connect(null, {FormReg:actionFullRegister}) (FormReg)
+
+const ConnectFormUpload = connect(null, {onUpload:actionUploadFile}) (FormDate)
+
+
+function App() {
+    return (
+        <Provider store = {store}>
+            <Router history = {createHistory()}>
+                <div className="App">
+                    <Route path = "/login" component={ConnectLoginForm} exact />
+                    <Route path = "/reg" component={ConnectFormReg} exact />
+                    <Route path = "/upload" component={ConnectFormUpload} exact />
+                    <Route path = "/" component={Main} exact />
+                </div>
+            </Router>
+        </Provider>
+    )
+  }
+
+  export default App;

+ 8 - 0
src/App.test.js

@@ -0,0 +1,8 @@
+import { render, screen } from '@testing-library/react';
+import App from './App';
+
+test('renders learn react link', () => {
+  render(<App />);
+  const linkElement = screen.getByText(/learn react/i);
+  expect(linkElement).toBeInTheDocument();
+});

+ 114 - 0
src/actions/index.js

@@ -0,0 +1,114 @@
+const getGQL = url => 
+    (query, variables) =>
+        fetch(url , {
+            method: 'POST',
+            headers: {
+                "content-type": "application/json",
+                ...(localStorage.authToken ? { Authorization: "Bearer " + localStorage.authToken } : {})
+            },
+            body: JSON.stringify({query, variables})
+        }).then(res => res.json())
+
+let gql = getGQL("/graphql")
+
+let log = async(login, password) => {
+    let query = `query login($login:String!, $password:String!) {
+        login(login: $login, password: $password)
+    }`
+
+    let variables = {"login":login, "password":password}
+
+    let token = await gql(query, variables)
+    localStorage.authToken = token.data.login
+    console.log(token)
+    return token.data.login
+}
+
+
+let reg = async(login, password) => {
+    let query = `mutation reg($login:String!, $password:String!) {
+    createUser(
+        login: $login,
+        password: $password
+
+    ){
+       _id
+    }}`
+    
+    let variables = {"login":login, "password":password}
+
+    let res = await gql(query, variables)
+    return res
+}
+
+let changePass = async(login, password, newPassword) => {
+    let query = `mutation changePass($login:String!, $password:String!, $newPassword:String!) {
+    changePassword(
+        login: $login,
+        password: $password,
+        newPassword: $newPassword
+
+    ){
+       _id
+    }`
+
+    let variables = {"login":login, "password":password, newPassword:"newPassword"}
+
+    let res = await gql(query, variables)
+    return res 
+}
+
+// actions
+
+const actionPending = name => ({type: 'PROMISE', status: 'PENDING', name})
+const actionResolved = (name, payload) => ({type: 'PROMISE', status: 'RESOLVED', name, payload})
+const actionRejected = (name, error) => ({type: 'PROMISE', status: 'REJECTED', name, error})
+
+const actionPromise = (name, promise) => 
+    async dispatch => {
+        dispatch(actionPending(name))
+        try{
+            let payload = await promise
+            dispatch(actionResolved(name, payload)) 
+            return payload
+        }
+        catch(error){
+             dispatch(actionRejected(name, error))
+        }
+    }
+
+// export const actionchangePass = (login, password, newPassword) => actionPromise("changePass", changePass(login, password, newPassword))
+const actionAuthLogin = token => ({type: 'LOGIN', token})
+// const actionAuthLogout = () => ({type: 'LOGOUT'})
+const actionLogin = (login, password) => actionPromise("login", log(login, password))
+const actionReg = (login, password) => actionPromise("reg", reg(login, password))
+
+export const actionFullLogin = (login, password) => async(dispatch) => {
+let result = await dispatch(actionLogin(login, password))
+    if (result !== null){
+        dispatch(actionAuthLogin(result))
+    } else {
+        alert ('Такой пользователь не существует')
+    }
+}
+
+export const actionFullRegister = (login, password) => async(dispatch) => {
+    let result = await dispatch(actionReg(login, password))
+    if(result?.data?.createUser !== null) {
+        dispatch(actionFullLogin(login, password))
+    } else {
+        alert('Такой пользователь уже существует!')
+    }
+}
+
+let up = async(file) => {
+    let formData = new FormData();
+    formData.append('photo', file)
+    fetch('/upload', {
+        method: "POST",
+        headers: localStorage.authToken ? {Authorization: 'Bearer ' + localStorage.authToken} : {},
+        body: formData
+    })
+}
+
+export const actionUploadFile = (file) => actionPromise("upload", up(file))

+ 42 - 0
src/components/Editor.js

@@ -0,0 +1,42 @@
+import { useState } from 'react';
+import { Controlled as ControlledEditor } from 'react-codemirror2';
+
+export function Editor(props) {
+    const {
+      language,
+      displayName,
+      value,
+      onChange
+    } = props
+    const [open, setOpen] = useState(true)
+  
+    function handleChange(editor, data, value) {
+      onChange(value)
+    }
+  
+    return (
+      <div className={`editor-container ${open ? '' : 'collapsed'}`}>
+        <div className="editor-title">
+          {displayName}
+          <button
+            type="button"
+            className="expand-collapse-btn"
+            onClick={() => setOpen(prevOpen => !prevOpen)}
+          >
+          </button>
+        </div>
+        <ControlledEditor
+          onBeforeChange={handleChange}
+          value={value}
+          className="code-mirror-wrapper"
+          options={{
+            lineWrapping: true,
+            lint: true,
+            mode: language,
+            theme: 'material',
+            lineNumbers: true
+          }}
+        />
+      </div>
+    )
+  }

+ 20 - 0
src/components/FormDate.js

@@ -0,0 +1,20 @@
+import { useCallback } from 'react';
+import { useDropzone } from 'react-dropzone';
+
+export const FormDate = ({onUpload}) => {
+    const onDrop = useCallback(acceptedFiles => {
+      acceptedFiles.map((file) => onUpload(file))
+    }, [onUpload])
+    const {getRootProps, getInputProps, isDragActive} = useDropzone({onDrop})
+  
+    return (
+      <div {...getRootProps()}>
+        <input {...getInputProps()} />
+        {
+          isDragActive ?
+            <p>Drop the files here ...</p> :
+            <p>Drag 'n' drop some files here, or click to select files</p>
+        }
+      </div>
+    )
+}

+ 15 - 0
src/components/FormReg.js

@@ -0,0 +1,15 @@
+import React, {useState} from 'react';
+
+export const FormReg = ({FormReg}) => {
+    const [login, setLogin] = useState('')
+    const [password, setPassword] = useState('')
+    const [passwordValid, setPasswordValid] = useState('')
+    return (
+        <>
+        <input value = {login} onChange = {e => setLogin(e.target.value)} />
+        <input type = "password" value = {password} onChange = {e => setPassword(e.target.value)} />
+        <input type = "password" value = {passwordValid} onChange = {e => setPasswordValid(e.target.value)} />
+        <button disabled = {!login || !password || (password !== passwordValid)} onClick = {() => FormReg(login, password)}>Registration </button>
+        </>
+    )
+}

+ 13 - 0
src/components/LoginForm.js

@@ -0,0 +1,13 @@
+import { useState } from 'react';
+
+export const LoginForm = ({onLogin}) => {
+    const [login, setLogin] = useState('')
+    const [password, setPassword] = useState('')
+    return (
+        <>
+        <input value = {login} onChange = {e => setLogin(e.target.value)} />
+        <input type = "password" value = {password} onChange = {e => setPassword(e.target.value)} />
+        <button disabled = {!login || !password} onClick = {() => onLogin(login, password)}>Login </button>
+        </>
+    )
+}

+ 69 - 0
src/index.css

@@ -0,0 +1,69 @@
+body {
+  margin: 0;
+  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
+    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
+    sans-serif;
+  -webkit-font-smoothing: antialiased;
+  -moz-osx-font-smoothing: grayscale;
+}
+
+code {
+  font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
+    monospace;
+}
+
+.top-pane {
+    background-color: hsl(225, 6%, 25%);
+}
+  
+.pane {
+    height: 50vh;
+    display: flex;
+}
+
+.editor-container {
+    flex-grow: 1;
+    flex-basis: 0;
+    display: flex;
+    flex-direction: column;
+    padding: .5rem;
+    background-color: hsl(225, 6%, 25%);
+}
+  
+.editor-container.collapsed {
+    flex-grow: 0;
+}
+
+.editor-container.collapsed .CodeMirror-scroll {
+    position: absolute;
+    overflow: hidden !important;
+}
+  
+.expand-collapse-btn {
+    margin-left: .5rem;
+    background: none;
+    border: none;
+    color: white;
+    cursor: pointer;
+}
+  
+.editor-title {
+    display: flex;
+    justify-content: space-between;
+    background-color: hsl(225, 6%, 13%);
+    color: white;
+    padding: .5rem .5rem .5rem 1rem;
+    border-top-right-radius: .5rem;
+    border-top-left-radius: .5rem;
+}
+  
+.CodeMirror {
+    height: 100% !important;
+}
+  
+.code-mirror-wrapper {
+    flex-grow: 1;
+    border-bottom-right-radius: .5rem;
+    border-bottom-left-radius: .5rem;
+    overflow: hidden;
+}

+ 17 - 0
src/index.js

@@ -0,0 +1,17 @@
+import React from 'react';
+import ReactDOM from 'react-dom';
+import './index.css';
+import App from './App';
+import reportWebVitals from './reportWebVitals';
+
+ReactDOM.render(
+  <React.StrictMode>
+    <App />
+  </React.StrictMode>,
+  document.getElementById('root')
+);
+
+// If you want to start measuring performance in your app, pass a function
+// to log results (for example: reportWebVitals(console.log))
+// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
+reportWebVitals();

File diff suppressed because it is too large
+ 1 - 0
src/logo.svg


+ 27 - 0
src/pages/Main.js

@@ -0,0 +1,27 @@
+import { useState } from 'react';
+import { Editor } from '../components/Editor';
+
+export const Main = () => {
+    const [html, setHtml] = useState('html', '')
+    const [css, setCss] = useState('css', '')
+    const [js, setJs] = useState('js', '')
+    return (
+        <>
+        <Editor   
+            language="xml"
+            displayName="HTML"
+            value={html}
+            onChange={setHtml} /> 
+        <Editor   
+            language="css"
+            displayName="CSS"
+            value={css}
+            onChange={setCss} />
+        <Editor   
+            language="javascript"
+            displayName="JS"
+            value={js}
+            onChange={setJs} />
+        </>
+    )     
+}

+ 33 - 0
src/reducers/auth.js

@@ -0,0 +1,33 @@
+import { decode as atob } from 'base-64'
+
+// функция authReducer
+
+let signatureToken = (token) => JSON.parse(atob(token.split(".")[1]))
+
+function authReducer(state, { type, token }) {
+
+    if (state === undefined) {
+        if (localStorage.authToken) {
+            type = "LOGIN"
+            token = localStorage.authToken
+        } else {
+            return {}
+        }
+    }
+
+    if (type === "LOGIN") {
+        console.log('LOGIN')
+        localStorage.authToken = token
+        return {token, payload: signatureToken(token)}
+    }
+
+    if (type === "LOGOUT") {
+        console.log('LOGOUT')
+        localStorage.removeItem("authToken")
+        return {}
+    }
+
+    return state
+}
+
+export default authReducer;

+ 13 - 0
src/reducers/index.js

@@ -0,0 +1,13 @@
+import { createStore, combineReducers, applyMiddleware } from 'redux';
+import thunk from 'redux-thunk';
+import authReducer from './auth';
+import promiseReducer from './promise';
+
+let reducers = combineReducers({
+    p: promiseReducer,
+    a: authReducer
+})
+
+const store = createStore(reducers, applyMiddleware(thunk))
+
+export default store;

+ 14 - 0
src/reducers/promise.js

@@ -0,0 +1,14 @@
+// функция promiseReducer
+function promiseReducer(state = {}, { type, status, payload, error, name }) {
+    
+    if (type === 'PROMISE') {
+        return {
+            ...state,
+            [name]: { status, payload, error }
+        }
+    }
+
+    return state;
+}
+
+export default promiseReducer;

+ 13 - 0
src/reportWebVitals.js

@@ -0,0 +1,13 @@
+const reportWebVitals = onPerfEntry => {
+  if (onPerfEntry && onPerfEntry instanceof Function) {
+    import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
+      getCLS(onPerfEntry);
+      getFID(onPerfEntry);
+      getFCP(onPerfEntry);
+      getLCP(onPerfEntry);
+      getTTFB(onPerfEntry);
+    });
+  }
+};
+
+export default reportWebVitals;

+ 5 - 0
src/setupTests.js

@@ -0,0 +1,5 @@
+// jest-dom adds custom jest matchers for asserting on DOM nodes.
+// allows you to do things like:
+// expect(element).toHaveTextContent(/react/i)
+// learn more: https://github.com/testing-library/jest-dom
+import '@testing-library/jest-dom';