Compare commits

...

1 Commits

Author SHA1 Message Date
Julien Fontanet
c03a2f5812 feat(xo-web-6): initial config 2021-11-04 10:35:57 +01:00
11 changed files with 420 additions and 0 deletions

View File

@@ -0,0 +1,4 @@
const config = (module.exports = require('../../@xen-orchestra/babel-config')(require('./package.json')))
// https://webpack.js.org/guides/tree-shaking/
config.presets.find(_ => _[0] === '@babel/preset-env')[1].modules = false

View File

@@ -0,0 +1,56 @@
{
"name": "xo-web-6",
"version": "0.0.0",
"homepage": "https://github.com/vatesfr/xen-orchestra/tree/master/packages/xo-web-6",
"bugs": "https://github.com/vatesfr/xen-orchestra/issues",
"repository": {
"directory": "packages/xo-web-6",
"type": "git",
"url": "https://github.com/vatesfr/xen-orchestra.git"
},
"devDependencies": {
"@babel/core": "^7.3.4",
"@babel/plugin-proposal-nullish-coalescing-operator": "^7.2.0",
"@babel/plugin-proposal-optional-chaining": "^7.2.0",
"@babel/plugin-syntax-dynamic-import": "^7.2.0",
"@babel/preset-env": "^7.3.4",
"@babel/preset-react": "^7.0.0",
"@babel/preset-typescript": "^7.3.3",
"@emotion/core": "^10.0.10",
"@emotion/styled": "^10.0.10",
"@types/react": "^16.8.13",
"@types/react-dom": "^16.8.4",
"@types/react-helmet": "^5.0.8",
"@types/react-router-dom": "^4.3.2",
"@types/webpack-env": "^1.13.9",
"babel-loader": "^8.0.5",
"clean-webpack-plugin": "^2.0.0",
"cross-env": "^5.2.0",
"html-webpack-plugin": "^3.2.0",
"json-rpc-protocol": "^0.13.1",
"reaclette": "^0.9.0-0",
"react": "^16.8.4",
"react-dom": "^16.8.4",
"react-helmet-async": "^1.0.2",
"react-router-dom": "^5.0.0",
"typescript": "^3.4.4",
"webpack": "^4.29.6",
"webpack-cli": "^3.2.3",
"webpack-dev-server": "^3.2.1"
},
"browserslist": "> 0.5%, last 2 versions, Firefox ESR, not dead",
"scripts": {
"build": "cross-env NODE_ENV=production webpack",
"start": "cross-env NODE_ENV=development webpack-dev-server --hot",
"start:open": "npm run start -- --open"
},
"private": true,
"author": {
"name": "Vates SAS",
"url": "https://vates.fr"
},
"license": "AGPL-3.0-or-later",
"engines": {
"node": ">=8.10"
}
}

View File

@@ -0,0 +1,16 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<meta name="theme-color" content="#000000" />
<title>Xen Orchestra</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root">The application is loading…</div>
</body>
</html>

View File

@@ -0,0 +1,11 @@
import React from 'react'
import { Helmet } from 'react-helmet-async'
export default () => (
<>
<Helmet>
<title>Bar</title>
</Helmet>
Welcome in Bar
</>
)

View File

@@ -0,0 +1 @@
export default () => 'Foo'

View File

@@ -0,0 +1,64 @@
import * as React from 'react'
import styled from '@emotion/styled'
import { HashRouter as Router, Route, Link } from 'react-router-dom'
import { Helmet, HelmetProvider } from 'react-helmet-async'
import { withStore } from 'reaclette'
const Bar = React.lazy(() => import('./Bar'))
const Foo = React.lazy(() => import('./Foo'))
const Title = styled.h1`
color: red;
text-align: center;
`
export default withStore(
{
initialState: () => ({
objects: new Map(),
onNotification: undefined,
}),
effects: {
initialize() {
const onNotification = notification => {
if (notification.message === 'objects') {
// TODO: update `objects`
}
}
this.props.connection.on('notification', onNotification)
this.state.onNotification = onNotification
},
finalize() {
this.props.connection.off('notification', this.state.onNotification)
this.state.onNotification = undefined
},
},
},
(store, props) => (
<Router>
<HelmetProvider>
<Helmet>
<title>Xen Orchestra</title>
</Helmet>
<Title>Xen Orchestra</Title>
<nav>
<ul>
<li>
<Link to='/'>Bar</Link>
</li>
<li>
<Link to='/foo/'>Foo</Link>
</li>
</ul>
</nav>
<React.Suspense fallback='loading'>
<Route path='/' exact component={Bar} />
<Route path='/foo' component={Foo} />
</React.Suspense>
</HelmetProvider>
</Router>
)
)

View File

@@ -0,0 +1,11 @@
import React from 'react'
const Button = ({ ...props }) => {
if (props.type === undefined && props.form === undefined) {
props.type = 'button'
}
return <button {...props} />
}
export { Button as default }

View File

@@ -0,0 +1,16 @@
import React, { StrictMode } from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import Connection from './libs/Connection'
ReactDOM.render(
<StrictMode>
<App connection={new Connection()} />
</StrictMode>,
document.getElementById('root')
)
if (module.hot) {
module.hot.accept()
}

View File

@@ -0,0 +1,132 @@
import * as JsonRpc from 'json-rpc-protocol'
import assert from 'assert'
const CONNECTED = 'connected'
const CONNECTING = 'connecting'
const DISCONNECTED = 'disconnected'
function onMessage({ data }) {
const message = JsonRpc.parse(data)
const { type } = message
if (type === 'notification') {
this.emit('notification', message)
} else if (type === 'request') {
this.send(JsonRpc.format.error(message.id, new JsonRpc.MethodNotFound(message.method)))
} else {
const { id } = message
const deferred = this._deferreds[id]
delete this._deferreds[id]
if (type === 'response') {
deferred(message.result)
} else {
assert.strictEqual(type, 'error')
deferred(Promise.reject(message.error))
}
}
}
export default class Connection {
constructor() {
this._deferreds = { __proto__: null }
this._onMessage = onMessage.bind(this)
const url = new URL('./api/')
url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'
this._url = url.href
this._connected = new Promise(resolve => {
this._resolveConnected = resolve
})
this._disconnected = Promise.resolve()
this._status = DISCONNECTED
}
get connected() {
return this._connected
}
get disconnected() {
return this._disconnected
}
get status() {
return this._status
}
async connect() {
const status = this._status
if (status === CONNECTED) {
return
}
assert.strictEqual(status, DISCONNECTED)
this._status = CONNECTING
try {
ws = this._ws = new WebSocket(this._url)
ws.addEventListener('message', this._onMessage)
await fromEvent(ws, 'open')
await this._call('session.signIn', { token: cookies.get('token') })
this._status = CONNECTED
this._resolveConnected()
this._resolveConnected = undefined
} catch (error) {
ignoreErrors.call(this.disconnect())
throw error
}
}
async disconnect() {
const status = this._status
if (status === DISCONNECTED) {
return
}
if (status === CONNECTED) {
this._connected = new Promise(resolve => {
this._resolveConnected = resolve
})
} else {
assert(status === CONNECTING)
}
const ws = this._ws
this._ws = undefined
ws.close()
this._status = DISCONNECTED
this._resolveDisconnected()
this._resolveDisconnected = undefined
const deferreds = this._deferreds
const ids = Object.keys(deferreds)
if (ids.length !== undefined) {
this._deferreds = { __proto__: null }
const error = Promise.reject(new Error('disconnected'))
ids.forEach(id => {
deferreds[id](error)
})
}
}
call(method, args) {
return method.startsWith('session.')
? Promise.reject(new Error('session.*() methods are disabled from this interface'))
: this._call(method, args)
}
_call(method, args) {
const id = Math.random().toString(36).slice(2)
return new Promise(resolve => {
this._ws.send(JsonRpc.format.request(id, method, args))
this._deferreds[id] = resolve
})
}
}

View File

@@ -0,0 +1,62 @@
{
"compilerOptions": {
/* Basic Options */
"target": "esnext", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
"jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
"declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "./dist", /* Redirect output structure to the directory. */
"rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "incremental": true, /* Enable incremental compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
"noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
"noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
"strictNullChecks": true, /* Enable strict null checks. */
"strictFunctionTypes": true, /* Enable strict checking of function types. */
"strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
"strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
"noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
"alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
"noUnusedLocals": true, /* Report errors on unused locals. */
"noUnusedParameters": true, /* Report errors on unused parameters. */
"noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
"noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
"allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
}
}

View File

@@ -0,0 +1,47 @@
const path = require('path')
const resolveApp = relative => path.resolve(__dirname, relative)
const { NODE_ENV = 'production' } = process.env
const __PROD__ = NODE_ENV === 'production'
// https://webpack.js.org/configuration/
module.exports = {
mode: NODE_ENV,
entry: resolveApp('src/index.tsx'),
output: {
filename: __PROD__ ? '[name].[contenthash:8].js' : '[name].js',
path: resolveApp('dist'),
},
optimization: {
runtimeChunk: true,
splitChunks: {
chunks: 'all',
},
},
module: {
rules: [
{
test: /\.tsx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
cacheDirectory: true,
},
},
},
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
devtool: __PROD__ ? 'source-map' : 'cheap-module-eval-source-map',
plugins: [
new (require('clean-webpack-plugin'))(),
new (require('html-webpack-plugin'))({
template: resolveApp('public/index.html'),
}),
__PROD__ && new (require('webpack').HashedModuleIdsPlugin)(),
].filter(Boolean),
}