Compare commits

...

11 Commits

  1. 38
      .gitignore
  2. 8
      .idea/.gitignore
  3. 21
      .idea/hexmap.iml
  4. 8
      .idea/modules.xml
  5. 17
      .idea/protoeditor.xml
  6. 7
      .idea/runConfigurations/All_Tests.xml
  7. 11
      .idea/runConfigurations/Client_Tests.xml
  8. 13
      .idea/runConfigurations/Server_Tests.xml
  9. 17
      .idea/runConfigurations/mage_protobuf_build.xml
  10. 6
      .idea/vcs.xml
  11. 14
      .idea/webResources.xml
  12. 23
      client/.gitignore
  13. 46
      client/README.md
  14. 106
      client/config/env.js
  15. 66
      client/config/getHttpsConfig.js
  16. 29
      client/config/jest/babelTransform.js
  17. 14
      client/config/jest/cssTransform.js
  18. 40
      client/config/jest/fileTransform.js
  19. 134
      client/config/modules.js
  20. 75
      client/config/paths.js
  21. 35
      client/config/pnpTs.js
  22. 757
      client/config/webpack.config.js
  23. 130
      client/config/webpackDevServer.config.js
  24. 4334
      client/package-lock.json
  25. 134
      client/package.json
  26. 212
      client/scripts/build.js
  27. 166
      client/scripts/start.js
  28. 53
      client/scripts/test.js
  29. 65
      client/src/App.tsx
  30. 178
      client/src/actions/NetworkAction.ts
  31. 18
      client/src/index.tsx
  32. 72
      client/src/react-app-env.d.ts
  33. 15
      client/src/reducers/AppStateReducer.ts
  34. 15
      client/src/reducers/ClientReducer.ts
  35. 8
      client/src/reducers/NetworkReducer.ts
  36. 55
      client/src/reducers/ServerReducer.ts
  37. 6
      client/src/reducers/TileReducer.ts
  38. 2
      client/src/state/AppState.ts
  39. 20
      client/src/state/NetworkState.ts
  40. 16
      client/src/ui/App.css
  41. 2
      client/src/ui/App.test.tsx
  42. 65
      client/src/ui/App.tsx
  43. 124
      client/src/ui/DOMWebsocketTranslator.ts
  44. 0
      client/src/ui/EntryPoint.css
  45. 18
      client/src/ui/EntryPoint.tsx
  46. 23
      client/src/ui/HexColorPicker.tsx
  47. 4
      client/src/ui/HexMapRenderer.tsx
  48. 6
      client/src/ui/HexTileRenderer.tsx
  49. 72
      client/src/ui/WebsocketReactAdapter.tsx
  50. 2
      client/src/ui/context/DispatchContext.ts
  51. 176
      client/src/ui/debug/ConsoleConnection.tsx
  52. 0
      client/src/ui/reportWebVitals.ts
  53. 32
      client/tsconfig.json
  54. 25
      common/proto/action.proto
  55. 26
      common/proto/client.proto
  56. 6
      common/proto/coords.proto
  57. 35
      common/proto/map.proto
  58. 36
      common/proto/server.proto
  59. 9
      common/proto/state.proto
  60. 5
      common/proto/user.proto
  61. 0
      common/src/actions/AppAction.ts
  62. 0
      common/src/actions/BaseAction.ts
  63. 0
      common/src/actions/CellAction.ts
  64. 75
      common/src/actions/ClientAction.ts
  65. 0
      common/src/actions/MapAction.ts
  66. 15
      common/src/actions/NetworkAction.ts
  67. 121
      common/src/actions/ServerAction.ts
  68. 0
      common/src/actions/TileAction.ts
  69. 0
      common/src/actions/UserAction.ts
  70. 38
      common/src/pbconv/ClientToPb.ts
  71. 91
      common/src/pbconv/MapFromPb.ts
  72. 9
      common/src/pbconv/MapToPb.ts
  73. 50
      common/src/pbconv/ServerFromPb.ts
  74. 35
      common/src/pbconv/SyncableActionFromPb.ts
  75. 26
      common/src/pbconv/SyncableActionToPb.ts
  76. 8
      common/src/reducers/HexMapReducer.ts
  77. 2
      common/src/reducers/SyncedStateReducer.ts
  78. 0
      common/src/reducers/UserReducer.ts
  79. 34
      common/src/state/Coordinates.ts
  80. 20
      common/src/state/HexMap.ts
  81. 0
      common/src/state/SyncedState.ts
  82. 0
      common/src/state/UserState.ts
  83. 4
      common/src/util/ArrayUtils.ts
  84. 27
      common/src/util/ColorUtils.ts
  85. 0
      common/src/util/TypeUtils.ts
  86. 31
      common/tsconfig.json
  87. 45
      server/action/map.go
  88. 43
      server/action/syncable.go
  89. 37
      server/action/user.go
  90. 9
      server/go.mod
  91. 49
      server/go.sum
  92. 1
      server/persistence/persistence.go
  93. 273
      server/room/actor.go
  94. 165
      server/room/client.go
  95. 124
      server/room/clientmessage.go
  96. 147
      server/room/message.go
  97. 54
      server/room/room.go
  98. 17
      server/state/coordinates.go
  99. 104
      server/state/hexcolor.go
  100. 131
      server/state/hexmap.go
  101. Some files were not shown because too many files have changed in this diff Show More

38
.gitignore vendored

@ -0,0 +1,38 @@
# dependencies
/node_modules
/client/node_modules
/common/node_modules
/server/node_modules
/.pnp
/client/.pnp
/common/.pnp
/server/.pnp
.pnp.js
# testing
/coverage
/client/coverage
/common/coverage
/server/coverage
# production
/build
/client/build
/common/build
/server/build
# Generated protocol buffers files
/common/src/proto
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

8
.idea/.gitignore vendored

@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
# Editor-based HTTP Client requests
/httpRequests/

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="Go" enabled="true">
<buildTags>
<option name="customFlags">
<array>
<option value="mage" />
</array>
</option>
</buildTags>
</component>
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/mage" />
<excludeFolder url="file://$MODULE_DIR$/buildtools" />
<excludeFolder url="file://$MODULE_DIR$/client/coverage" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/hexmap.iml" filepath="$PROJECT_DIR$/.idea/hexmap.iml" />
</modules>
</component>
</project>

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProtobufLanguageSettings">
<option name="autoConfigEnabled" value="false" />
<option name="importPathEntries">
<list>
<ImportPathEntry>
<option name="location" value="jar://$APPLICATION_PLUGINS_DIR$/protoeditor/lib/protoeditor.jar!/protobuf" />
</ImportPathEntry>
<ImportPathEntry>
<option name="location" value="file://$PROJECT_DIR$/common/proto" />
</ImportPathEntry>
</list>
</option>
<option name="descriptorPath" value="google/protobuf/descriptor.proto" />
</component>
</project>

@ -0,0 +1,7 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="All Tests" type="CompoundRunConfigurationType">
<toRun name="Client Tests" type="JavaScriptTestRunnerJest" />
<toRun name="Server Tests" type="GoTestRunConfiguration" />
<method v="2" />
</configuration>
</component>

@ -0,0 +1,11 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Client Tests" type="JavaScriptTestRunnerJest">
<node-interpreter value="project" />
<node-options value="" />
<jest-package value="$PROJECT_DIR$/client/node_modules/react-scripts" />
<working-dir value="$PROJECT_DIR$/client" />
<envs />
<scope-kind value="ALL" />
<method v="2" />
</configuration>
</component>

@ -0,0 +1,13 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Server Tests" type="GoTestRunConfiguration" factoryName="Go Test">
<module name="hexmap" />
<working_directory value="$PROJECT_DIR$/server" />
<go_parameters value="-i" />
<kind value="DIRECTORY" />
<package value="git.reya.zone/reya/hexmap" />
<directory value="$PROJECT_DIR$/server" />
<filePath value="$PROJECT_DIR$" />
<framework value="gotest" />
<method v="2" />
</configuration>
</component>

@ -0,0 +1,17 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="mage protobuf:build" type="ShConfigurationType">
<option name="SCRIPT_TEXT" value="" />
<option name="INDEPENDENT_SCRIPT_PATH" value="true" />
<option name="SCRIPT_PATH" value="$PROJECT_DIR$/mage.sh" />
<option name="SCRIPT_OPTIONS" value="-v protobuf:build" />
<option name="INDEPENDENT_SCRIPT_WORKING_DIRECTORY" value="true" />
<option name="SCRIPT_WORKING_DIRECTORY" value="$PROJECT_DIR$" />
<option name="INDEPENDENT_INTERPRETER_PATH" value="true" />
<option name="INTERPRETER_PATH" value="/bin/bash" />
<option name="INTERPRETER_OPTIONS" value="" />
<option name="EXECUTE_IN_TERMINAL" value="false" />
<option name="EXECUTE_SCRIPT_FILE" value="true" />
<envs />
<method v="2" />
</configuration>
</component>

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="WebResourcesPaths">
<contentEntries>
<entry url="file://$PROJECT_DIR$">
<entryData>
<resourceRoots>
<path value="file://$PROJECT_DIR$/client/public" />
</resourceRoots>
</entryData>
</entry>
</contentEntries>
</component>
</project>

23
client/.gitignore vendored

@ -1,23 +0,0 @@
# 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*

@ -1,46 +0,0 @@
# Getting Started with Create React App
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.\
You will also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you can’t go back!**
If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).

@ -0,0 +1,106 @@
'use strict';
const fs = require('fs');
const path = require('path');
const paths = require('./paths');
// Make sure that including paths.js after env.js will read .env variables.
delete require.cache[require.resolve('./paths')];
const NODE_ENV = process.env.NODE_ENV;
if (!NODE_ENV) {
throw new Error(
'The NODE_ENV environment variable is required but was not specified.'
);
}
// https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use
const dotenvFiles = [
`${paths.dotenv}.${NODE_ENV}.local`,
// Don't include `.env.local` for `test` environment
// since normally you expect tests to produce the same
// results for everyone
NODE_ENV !== 'test' && `${paths.dotenv}.local`,
`${paths.dotenv}.${NODE_ENV}`,
paths.dotenv,
].filter(Boolean);
// Load environment variables from .env* files. Suppress warnings using silent
// if this file is missing. dotenv will never modify any environment variables
// that have already been set. Variable expansion is supported in .env files.
// https://github.com/motdotla/dotenv
// https://github.com/motdotla/dotenv-expand
dotenvFiles.forEach(dotenvFile => {
if (fs.existsSync(dotenvFile)) {
require('dotenv-expand')(
require('dotenv').config({
path: dotenvFile,
})
);
}
});
// We support resolving modules according to `NODE_PATH`.
// This lets you use absolute paths in imports inside large monorepos:
// https://github.com/facebook/create-react-app/issues/253.
// It works similar to `NODE_PATH` in Node itself:
// https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders
// Note that unlike in Node, only *relative* paths from `NODE_PATH` are honored.
// Otherwise, we risk importing Node.js core modules into an app instead of webpack shims.
// https://github.com/facebook/create-react-app/issues/1023#issuecomment-265344421
// We also resolve them to make sure all tools using them work consistently.
const appDirectory = fs.realpathSync(process.cwd());
process.env.NODE_PATH = (process.env.NODE_PATH || '')
.split(path.delimiter)
.filter(folder => folder && !path.isAbsolute(folder))
.map(folder => path.resolve(appDirectory, folder))
.join(path.delimiter);
// Grab NODE_ENV and REACT_APP_* environment variables and prepare them to be
// injected into the application via DefinePlugin in webpack configuration.
const REACT_APP = /^REACT_APP_/i;
function getClientEnvironment(publicUrl) {
const raw = Object.keys(process.env)
.filter(key => REACT_APP.test(key))
.reduce(
(env, key) => {
env[key] = process.env[key];
return env;
},
{
// Useful for determining whether we’re running in production mode.
// Most importantly, it switches React into the correct mode.
NODE_ENV: process.env.NODE_ENV || 'development',
// Useful for resolving the correct path to static assets in `public`.
// For example, <img src={process.env.PUBLIC_URL + '/img/logo.png'} />.
// This should only be used as an escape hatch. Normally you would put
// images into the `src` and `import` them in code to get their paths.
PUBLIC_URL: publicUrl,
// We support configuring the sockjs pathname during development.
// These settings let a developer run multiple simultaneous projects.
// They are used as the connection `hostname`, `pathname` and `port`
// in webpackHotDevClient. They are used as the `sockHost`, `sockPath`
// and `sockPort` options in webpack-dev-server.
WDS_SOCKET_HOST: process.env.WDS_SOCKET_HOST,
WDS_SOCKET_PATH: process.env.WDS_SOCKET_PATH,
WDS_SOCKET_PORT: process.env.WDS_SOCKET_PORT,
// Whether or not react-refresh is enabled.
// react-refresh is not 100% stable at this time,
// which is why it's disabled by default.
// It is defined here so it is available in the webpackHotDevClient.
FAST_REFRESH: process.env.FAST_REFRESH !== 'false',
}
);
// Stringify all values so we can feed into webpack DefinePlugin
const stringified = {
'process.env': Object.keys(raw).reduce((env, key) => {
env[key] = JSON.stringify(raw[key]);
return env;
}, {}),
};
return { raw, stringified };
}
module.exports = getClientEnvironment;

@ -0,0 +1,66 @@
'use strict';
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const chalk = require('react-dev-utils/chalk');
const paths = require('./paths');
// Ensure the certificate and key provided are valid and if not
// throw an easy to debug error
function validateKeyAndCerts({ cert, key, keyFile, crtFile }) {
let encrypted;
try {
// publicEncrypt will throw an error with an invalid cert
encrypted = crypto.publicEncrypt(cert, Buffer.from('test'));
} catch (err) {
throw new Error(
`The certificate "${chalk.yellow(crtFile)}" is invalid.\n${err.message}`
);
}
try {
// privateDecrypt will throw an error with an invalid key
crypto.privateDecrypt(key, encrypted);
} catch (err) {
throw new Error(
`The certificate key "${chalk.yellow(keyFile)}" is invalid.\n${
err.message
}`
);
}
}
// Read file and throw an error if it doesn't exist
function readEnvFile(file, type) {
if (!fs.existsSync(file)) {
throw new Error(
`You specified ${chalk.cyan(
type
)} in your env, but the file "${chalk.yellow(file)}" can't be found.`
);
}
return fs.readFileSync(file);
}
// Get the https config
// Return cert files if provided in env, otherwise just true or false
function getHttpsConfig() {
const { SSL_CRT_FILE, SSL_KEY_FILE, HTTPS } = process.env;
const isHttps = HTTPS === 'true';
if (isHttps && SSL_CRT_FILE && SSL_KEY_FILE) {
const crtFile = path.resolve(paths.appPath, SSL_CRT_FILE);
const keyFile = path.resolve(paths.appPath, SSL_KEY_FILE);
const config = {
cert: readEnvFile(crtFile, 'SSL_CRT_FILE'),
key: readEnvFile(keyFile, 'SSL_KEY_FILE'),
};
validateKeyAndCerts({ ...config, keyFile, crtFile });
return config;
}
return isHttps;
}
module.exports = getHttpsConfig;

@ -0,0 +1,29 @@
'use strict';
const babelJest = require('babel-jest');
const hasJsxRuntime = (() => {
if (process.env.DISABLE_NEW_JSX_TRANSFORM === 'true') {
return false;
}
try {
require.resolve('react/jsx-runtime');
return true;
} catch (e) {
return false;
}
})();
module.exports = babelJest.createTransformer({
presets: [
[
require.resolve('babel-preset-react-app'),
{
runtime: hasJsxRuntime ? 'automatic' : 'classic',
},
],
],
babelrc: false,
configFile: false,
});

@ -0,0 +1,14 @@
'use strict';
// This is a custom Jest transformer turning style imports into empty objects.
// http://facebook.github.io/jest/docs/en/webpack.html
module.exports = {
process() {
return 'module.exports = {};';
},
getCacheKey() {
// The output is always the same.
return 'cssTransform';
},
};

@ -0,0 +1,40 @@
'use strict';
const path = require('path');
const camelcase = require('camelcase');
// This is a custom Jest transformer turning file imports into filenames.
// http://facebook.github.io/jest/docs/en/webpack.html
module.exports = {
process(src, filename) {
const assetFilename = JSON.stringify(path.basename(filename));
if (filename.match(/\.svg$/)) {
// Based on how SVGR generates a component name:
// https://github.com/smooth-code/svgr/blob/01b194cf967347d43d4cbe6b434404731b87cf27/packages/core/src/state.js#L6
const pascalCaseFilename = camelcase(path.parse(filename).name, {
pascalCase: true,
});
const componentName = `Svg${pascalCaseFilename}`;
return `const React = require('react');
module.exports = {
__esModule: true,
default: ${assetFilename},
ReactComponent: React.forwardRef(function ${componentName}(props, ref) {
return {
$$typeof: Symbol.for('react.element'),
type: 'svg',
ref: ref,
key: null,
props: Object.assign({}, props, {
children: ${assetFilename}
})
};
}),
};`;
}
return `module.exports = ${assetFilename};`;
},
};

@ -0,0 +1,134 @@
'use strict';
const fs = require('fs');
const path = require('path');
const paths = require('./paths');
const chalk = require('react-dev-utils/chalk');
const resolve = require('resolve');
/**
* Get additional module paths based on the baseUrl of a compilerOptions object.
*
* @param {Object} options
*/
function getAdditionalModulePaths(options = {}) {
const baseUrl = options.baseUrl;
if (!baseUrl) {
return '';
}
const baseUrlResolved = path.resolve(paths.appPath, baseUrl);
// We don't need to do anything if `baseUrl` is set to `node_modules`. This is
// the default behavior.
if (path.relative(paths.appNodeModules, baseUrlResolved) === '') {
return null;
}
// Allow the user set the `baseUrl` to `appSrc`.
if (path.relative(paths.appSrc, baseUrlResolved) === '') {
return [paths.appSrc];
}
// If the path is equal to the root directory we ignore it here.
// We don't want to allow importing from the root directly as source files are
// not transpiled outside of `src`. We do allow importing them with the
// absolute path (e.g. `src/Components/Button.js`) but we set that up with
// an alias.
if (path.relative(paths.appPath, baseUrlResolved) === '') {
return null;
}
// Otherwise, throw an error.
throw new Error(
chalk.red.bold(
"Your project's `baseUrl` can only be set to `src` or `node_modules`." +
' Create React App does not support other values at this time.'
)
);
}
/**
* Get webpack aliases based on the baseUrl of a compilerOptions object.
*
* @param {*} options
*/
function getWebpackAliases(options = {}) {
const baseUrl = options.baseUrl;
if (!baseUrl) {
return {};
}
const baseUrlResolved = path.resolve(paths.appPath, baseUrl);
if (path.relative(paths.appPath, baseUrlResolved) === '') {
return {
src: paths.appSrc,
};
}
}
/**
* Get jest aliases based on the baseUrl of a compilerOptions object.
*
* @param {*} options
*/
function getJestAliases(options = {}) {
const baseUrl = options.baseUrl;
if (!baseUrl) {
return {};
}
const baseUrlResolved = path.resolve(paths.appPath, baseUrl);
if (path.relative(paths.appPath, baseUrlResolved) === '') {
return {
'^src/(.*)$': '<rootDir>/src/$1',
};
}
}
function getModules() {
// Check if TypeScript is setup
const hasTsConfig = fs.existsSync(paths.appTsConfig);
const hasJsConfig = fs.existsSync(paths.appJsConfig);
if (hasTsConfig && hasJsConfig) {
throw new Error(
'You have both a tsconfig.json and a jsconfig.json. If you are using TypeScript please remove your jsconfig.json file.'
);
}
let config;
// If there's a tsconfig.json we assume it's a
// TypeScript project and set up the config
// based on tsconfig.json
if (hasTsConfig) {
const ts = require(resolve.sync('typescript', {
basedir: paths.appNodeModules,
}));
config = ts.readConfigFile(paths.appTsConfig, ts.sys.readFile).config;
// Otherwise we'll check if there is jsconfig.json
// for non TS projects.
} else if (hasJsConfig) {
config = require(paths.appJsConfig);
}
config = config || {};
const options = config.compilerOptions || {};
const additionalModulePaths = getAdditionalModulePaths(options);
return {
additionalModulePaths: additionalModulePaths,
webpackAliases: getWebpackAliases(options),
jestAliases: getJestAliases(options),
hasTsConfig,
};
}
module.exports = getModules();

@ -0,0 +1,75 @@
'use strict';
const path = require('path');
const fs = require('fs');
const getPublicUrlOrPath = require('react-dev-utils/getPublicUrlOrPath');
// Make sure any symlinks in the project folder are resolved:
// https://github.com/facebook/create-react-app/issues/637
const appDirectory = fs.realpathSync(process.cwd());
const resolveApp = relativePath => path.resolve(appDirectory, relativePath);
// We use `PUBLIC_URL` environment variable or "homepage" field to infer
// "public path" at which the app is served.
// webpack needs to know it to put the right <script> hrefs into HTML even in
// single-page apps that may serve index.html for nested URLs like /todos/42.
// We can't use a relative path in HTML because we don't want to load something
// like /todos/42/static/js/bundle.7289d.js. We have to know the root.
const publicUrlOrPath = getPublicUrlOrPath(
process.env.NODE_ENV === 'development',
require(resolveApp('package.json')).homepage,
process.env.PUBLIC_URL
);
const buildPath = process.env.BUILD_PATH || 'build';
const moduleFileExtensions = [
'web.mjs',
'mjs',
'web.js',
'js',
'web.ts',
'ts',
'web.tsx',
'tsx',
'json',
'web.jsx',
'jsx',
];
// Resolve file paths in the same order as webpack
const resolveModule = (resolveFn, filePath) => {
const extension = moduleFileExtensions.find(extension =>
fs.existsSync(resolveFn(`${filePath}.${extension}`))
);
if (extension) {
return resolveFn(`${filePath}.${extension}`);
}
return resolveFn(`${filePath}.js`);
};
// config after eject: we're in ./config/
module.exports = {
dotenv: resolveApp('.env'),
appPath: resolveApp('.'),
appBuild: resolveApp(buildPath),
appPublic: resolveApp('public'),
appHtml: resolveApp('public/index.html'),
appIndexJs: resolveModule(resolveApp, 'src/index'),
appPackageJson: resolveApp('package.json'),
appSrc: resolveApp('src'),
appTsConfig: resolveApp('tsconfig.json'),
appJsConfig: resolveApp('jsconfig.json'),
yarnLockFile: resolveApp('yarn.lock'),
testsSetup: resolveModule(resolveApp, 'src/setupTests'),
proxySetup: resolveApp('src/setupProxy.js'),
appNodeModules: resolveApp('node_modules'),
swSrc: resolveModule(resolveApp, 'src/service-worker'),
publicUrlOrPath,
};
module.exports.moduleFileExtensions = moduleFileExtensions;

@ -0,0 +1,35 @@
'use strict';
const { resolveModuleName } = require('ts-pnp');
exports.resolveModuleName = (
typescript,
moduleName,
containingFile,
compilerOptions,
resolutionHost
) => {
return resolveModuleName(
moduleName,
containingFile,
compilerOptions,
resolutionHost,
typescript.resolveModuleName
);
};
exports.resolveTypeReferenceDirective = (
typescript,
moduleName,
containingFile,
compilerOptions,
resolutionHost
) => {
return resolveModuleName(
moduleName,
containingFile,
compilerOptions,
resolutionHost,
typescript.resolveTypeReferenceDirective
);
};

@ -0,0 +1,757 @@
'use strict';
const fs = require('fs');
const path = require('path');
const webpack = require('webpack');
const resolve = require('resolve');
const PnpWebpackPlugin = require('pnp-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
const InlineChunkHtmlPlugin = require('react-dev-utils/InlineChunkHtmlPlugin');
const TerserPlugin = require('terser-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const safePostCssParser = require('postcss-safe-parser');
const ManifestPlugin = require('webpack-manifest-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const WorkboxWebpackPlugin = require('workbox-webpack-plugin');
const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
const getCSSModuleLocalIdent = require('react-dev-utils/getCSSModuleLocalIdent');
const ESLintPlugin = require('eslint-webpack-plugin');
const paths = require('./paths');
const modules = require('./modules');
const getClientEnvironment = require('./env');
const ModuleNotFoundPlugin = require('react-dev-utils/ModuleNotFoundPlugin');
const ForkTsCheckerWebpackPlugin = require('react-dev-utils/ForkTsCheckerWebpackPlugin');
const typescriptFormatter = require('react-dev-utils/typescriptFormatter');
const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
const postcssNormalize = require('postcss-normalize');
const appPackageJson = require(paths.appPackageJson);
// Source maps are resource heavy and can cause out of memory issue for large source files.
const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';
const webpackDevClientEntry = require.resolve(
'react-dev-utils/webpackHotDevClient'
);
const reactRefreshOverlayEntry = require.resolve(
'react-dev-utils/refreshOverlayInterop'
);
// Some apps do not need the benefits of saving a web request, so not inlining the chunk
// makes for a smoother build process.
const shouldInlineRuntimeChunk = process.env.INLINE_RUNTIME_CHUNK !== 'false';
const emitErrorsAsWarnings = process.env.ESLINT_NO_DEV_ERRORS === 'true';
const disableESLintPlugin = process.env.DISABLE_ESLINT_PLUGIN === 'true';
const imageInlineSizeLimit = parseInt(
process.env.IMAGE_INLINE_SIZE_LIMIT || '10000'
);
// Check if TypeScript is setup
const useTypeScript = fs.existsSync(paths.appTsConfig);
// Get the path to the uncompiled service worker (if it exists).
const swSrc = paths.swSrc;
// style files regexes
const cssRegex = /\.css$/;
const cssModuleRegex = /\.module\.css$/;
const sassRegex = /\.(scss|sass)$/;
const sassModuleRegex = /\.module\.(scss|sass)$/;
const hasJsxRuntime = (() => {
if (process.env.DISABLE_NEW_JSX_TRANSFORM === 'true') {
return false;
}
try {
require.resolve('react/jsx-runtime');
return true;
} catch (e) {
return false;
}
})();
// This is the production and development configuration.
// It is focused on developer experience, fast rebuilds, and a minimal bundle.
module.exports = function (webpackEnv) {
const isEnvDevelopment = webpackEnv === 'development';
const isEnvProduction = webpackEnv === 'production';
// Variable used for enabling profiling in Production
// passed into alias object. Uses a flag if passed into the build command
const isEnvProductionProfile =
isEnvProduction && process.argv.includes('--profile');
// We will provide `paths.publicUrlOrPath` to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
// Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
// Get environment variables to inject into our app.
const env = getClientEnvironment(paths.publicUrlOrPath.slice(0, -1));
const shouldUseReactRefresh = env.raw.FAST_REFRESH;
// common function to get style loaders
const getStyleLoaders = (cssOptions, preProcessor) => {
const loaders = [
isEnvDevelopment && require.resolve('style-loader'),
isEnvProduction && {
loader: MiniCssExtractPlugin.loader,
// css is located in `static/css`, use '../../' to locate index.html folder
// in production `paths.publicUrlOrPath` can be a relative path
options: paths.publicUrlOrPath.startsWith('.')
? { publicPath: '../../' }
: {},
},
{
loader: require.resolve('css-loader'),
options: cssOptions,
},
{
// Options for PostCSS as we reference these options twice
// Adds vendor prefixing based on your specified browser support in
// package.json
loader: require.resolve('postcss-loader'),
options: {
// Necessary for external CSS imports to work
// https://github.com/facebook/create-react-app/issues/2677
ident: 'postcss',
plugins: () => [
require('postcss-flexbugs-fixes'),
require('postcss-preset-env')({
autoprefixer: {
flexbox: 'no-2009',
},
stage: 3,
}),
// Adds PostCSS Normalize as the reset css with default options,
// so that it honors browserslist config in package.json
// which in turn let's users customize the target behavior as per their needs.
postcssNormalize(),
],
sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment,
},
},
].filter(Boolean);
if (preProcessor) {
loaders.push(
{
loader: require.resolve('resolve-url-loader'),
options: {
sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment,
root: paths.appSrc,
},
},
{
loader: require.resolve(preProcessor),
options: {
sourceMap: true,
},
}
);
}
return loaders;
};
return {
mode: isEnvProduction ? 'production' : isEnvDevelopment && 'development',
// Stop compilation early in production
bail: isEnvProduction,
devtool: isEnvProduction
? shouldUseSourceMap
? 'source-map'
: false
: isEnvDevelopment && 'cheap-module-source-map',
// These are the "entry points" to our application.
// This means they will be the "root" imports that are included in JS bundle.
entry:
isEnvDevelopment && !shouldUseReactRefresh
? [
// Include an alternative client for WebpackDevServer. A client's job is to
// connect to WebpackDevServer by a socket and get notified about changes.
// When you save a file, the client will either apply hot updates (in case
// of CSS changes), or refresh the page (in case of JS changes). When you
// make a syntax error, this client will display a syntax error overlay.
// Note: instead of the default WebpackDevServer client, we use a custom one
// to bring better experience for Create React App users. You can replace
// the line below with these two lines if you prefer the stock client:
//
// require.resolve('webpack-dev-server/client') + '?/',
// require.resolve('webpack/hot/dev-server'),
//
// When using the experimental react-refresh integration,
// the webpack plugin takes care of injecting the dev client for us.
webpackDevClientEntry,
// Finally, this is your app's code:
paths.appIndexJs,
// We include the app code last so that if there is a runtime error during
// initialization, it doesn't blow up the WebpackDevServer client, and
// changing JS code would still trigger a refresh.
]
: paths.appIndexJs,
output: {
// The build folder.
path: isEnvProduction ? paths.appBuild : undefined,
// Add /* filename */ comments to generated require()s in the output.
pathinfo: isEnvDevelopment,
// There will be one main bundle, and one file per asynchronous chunk.
// In development, it does not produce real files.
filename: isEnvProduction
? 'static/js/[name].[contenthash:8].js'
: isEnvDevelopment && 'static/js/bundle.js',
// TODO: remove this when upgrading to webpack 5
futureEmitAssets: true,
// There are also additional JS chunk files if you use code splitting.
chunkFilename: isEnvProduction
? 'static/js/[name].[contenthash:8].chunk.js'
: isEnvDevelopment && 'static/js/[name].chunk.js',
// webpack uses `publicPath` to determine where the app is being served from.
// It requires a trailing slash, or the file assets will get an incorrect path.
// We inferred the "public path" (such as / or /my-project) from homepage.
publicPath: paths.publicUrlOrPath,
// Point sourcemap entries to original disk location (format as URL on Windows)
devtoolModuleFilenameTemplate: isEnvProduction
? info =>
path
.relative(paths.appSrc, info.absoluteResourcePath)
.replace(/\\/g, '/')
: isEnvDevelopment &&
(info => path.resolve(info.absoluteResourcePath).replace(/\\/g, '/')),
// Prevents conflicts when multiple webpack runtimes (from different apps)
// are used on the same page.
jsonpFunction: `webpackJsonp${appPackageJson.name}`,
// this defaults to 'window', but by setting it to 'this' then
// module chunks which are built will work in web workers as well.
globalObject: 'this',
},
optimization: {
minimize: isEnvProduction,
minimizer: [
// This is only used in production mode
new TerserPlugin({
terserOptions: {
parse: {
// We want terser to parse ecma 8 code. However, we don't want it
// to apply any minification steps that turns valid ecma 5 code
// into invalid ecma 5 code. This is why the 'compress' and 'output'
// sections only apply transformations that are ecma 5 safe
// https://github.com/facebook/create-react-app/pull/4234
ecma: 8,
},
compress: {
ecma: 5,
warnings: false,
// Disabled because of an issue with Uglify breaking seemingly valid code:
// https://github.com/facebook/create-react-app/issues/2376
// Pending further investigation:
// https://github.com/mishoo/UglifyJS2/issues/2011
comparisons: false,
// Disabled because of an issue with Terser breaking valid code:
// https://github.com/facebook/create-react-app/issues/5250
// Pending further investigation:
// https://github.com/terser-js/terser/issues/120
inline: 2,
},
mangle: {
safari10: true,
},
// Added for profiling in devtools
keep_classnames: isEnvProductionProfile,
keep_fnames: isEnvProductionProfile,
output: {
ecma: 5,
comments: false,
// Turned on because emoji and regex is not minified properly using default
// https://github.com/facebook/create-react-app/issues/2488
ascii_only: true,
},
},
sourceMap: shouldUseSourceMap,
}),
// This is only used in production mode
new OptimizeCSSAssetsPlugin({
cssProcessorOptions: {
parser: safePostCssParser,
map: shouldUseSourceMap
? {
// `inline: false` forces the sourcemap to be output into a
// separate file
inline: false,
// `annotation: true` appends the sourceMappingURL to the end of
// the css file, helping the browser find the sourcemap
annotation: true,
}
: false,
},
cssProcessorPluginOptions: {
preset: ['default', { minifyFontValues: { removeQuotes: false } }],
},
}),
],
// Automatically split vendor and commons
// https://twitter.com/wSokra/status/969633336732905474
// https://medium.com/webpack/webpack-4-code-splitting-chunk-graph-and-the-splitchunks-optimization-be739a861366
splitChunks: {
chunks: 'all',
name: isEnvDevelopment,
},
// Keep the runtime chunk separated to enable long term caching
// https://twitter.com/wSokra/status/969679223278505985
// https://github.com/facebook/create-react-app/issues/5358
runtimeChunk: {
name: entrypoint => `runtime-${entrypoint.name}`,
},
},
resolve: {
// This allows you to set a fallback for where webpack should look for modules.
// We placed these paths second because we want `node_modules` to "win"
// if there are any conflicts. This matches Node resolution mechanism.
// https://github.com/facebook/create-react-app/issues/253
modules: ['node_modules', paths.appNodeModules].concat(
modules.additionalModulePaths || []
),
// These are the reasonable defaults supported by the Node ecosystem.
// We also include JSX as a common component filename extension to support
// some tools, although we do not recommend using it, see:
// https://github.com/facebook/create-react-app/issues/290
// `web` extension prefixes have been added for better support
// for React Native Web.
extensions: paths.moduleFileExtensions
.map(ext => `.${ext}`)
.filter(ext => useTypeScript || !ext.includes('ts')),
alias: {
// Support React Native Web
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
'react-native': 'react-native-web',
// Allows for better profiling with ReactDevTools
...(isEnvProductionProfile && {
'react-dom$': 'react-dom/profiling',
'scheduler/tracing': 'scheduler/tracing-profiling',
}),
...(modules.webpackAliases || {}),
},
plugins: [
// Adds support for installing with Plug'n'Play, leading to faster installs and adding
// guards against forgotten dependencies and such.
PnpWebpackPlugin,
// Prevents users from importing files from outside of src/ (or node_modules/).
// This often causes confusion because we only process files within src/ with babel.
// To fix this, we prevent you from importing files out of src/ -- if you'd like to,
// please link the files into your node_modules/ and let module-resolution kick in.
// Make sure your source files are compiled, as they will not be processed in any way.
new ModuleScopePlugin(paths.appSrc, [
paths.appPackageJson,
reactRefreshOverlayEntry,
]),
],
},
resolveLoader: {
plugins: [
// Also related to Plug'n'Play, but this time it tells webpack to load its loaders
// from the current package.
PnpWebpackPlugin.moduleLoader(module),
],
},
module: {
strictExportPresence: true,
rules: [
// Disable require.ensure as it's not a standard language feature.
{ parser: { requireEnsure: false } },
{
// "oneOf" will traverse all following loaders until one will
// match the requirements. When no loader matches it will fall
// back to the "file" loader at the end of the loader list.
oneOf: [
// TODO: Merge this config once `image/avif` is in the mime-db
// https://github.com/jshttp/mime-db
{
test: [/\.avif$/],
loader: require.resolve('url-loader'),
options: {
limit: imageInlineSizeLimit,
mimetype: 'image/avif',
name: 'static/media/[name].[hash:8].[ext]',
},
},
// "url" loader works like "file" loader except that it embeds assets
// smaller than specified limit in bytes as data URLs to avoid requests.
// A missing `test` is equivalent to a match.
{
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
loader: require.resolve('url-loader'),
options: {
limit: imageInlineSizeLimit,
name: 'static/media/[name].[hash:8].[ext]',
},
},
// Process application JS with Babel.
// The preset includes JSX, Flow, TypeScript, and some ESnext features.
{
test: /\.(js|mjs|jsx|ts|tsx)$/,
include: paths.appSrc,
loader: require.resolve('babel-loader'),
options: {
customize: require.resolve(
'babel-preset-react-app/webpack-overrides'
),
presets: [
[
require.resolve('babel-preset-react-app'),
{
runtime: hasJsxRuntime ? 'automatic' : 'classic',
},
],
],
plugins: [
[
require.resolve('babel-plugin-named-asset-import'),
{
loaderMap: {
svg: {
ReactComponent:
'@svgr/webpack?-svgo,+titleProp,+ref![path]',
},
},
},
],
isEnvDevelopment &&
shouldUseReactRefresh &&
require.resolve('react-refresh/babel'),
].filter(Boolean),
// This is a feature of `babel-loader` for webpack (not Babel itself).
// It enables caching results in ./node_modules/.cache/babel-loader/
// directory for faster rebuilds.
cacheDirectory: true,
// See #6846 for context on why cacheCompression is disabled
cacheCompression: false,
compact: isEnvProduction,
},
},
// Process any JS outside of the app with Babel.
// Unlike the application JS, we only compile the standard ES features.
{
test: /\.(js|mjs)$/,
exclude: /@babel(?:\/|\\{1,2})runtime/,
loader: require.resolve('babel-loader'),
options: {
babelrc: false,
configFile: false,
compact: false,
presets: [
[
require.resolve('babel-preset-react-app/dependencies'),
{ helpers: true },
],
],
cacheDirectory: true,
// See #6846 for context on why cacheCompression is disabled
cacheCompression: false,
// Babel sourcemaps are needed for debugging into node_modules
// code. Without the options below, debuggers like VSCode
// show incorrect code and set breakpoints on the wrong lines.
sourceMaps: shouldUseSourceMap,
inputSourceMap: shouldUseSourceMap,
},
},
// "postcss" loader applies autoprefixer to our CSS.
// "css" loader resolves paths in CSS and adds assets as dependencies.
// "style" loader turns CSS into JS modules that inject <style> tags.
// In production, we use MiniCSSExtractPlugin to extract that CSS
// to a file, but in development "style" loader enables hot editing
// of CSS.
// By default we support CSS Modules with the extension .module.css
{
test: cssRegex,
exclude: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
sourceMap: isEnvProduction
? shouldUseSourceMap
: isEnvDevelopment,
}),
// Don't consider CSS imports dead code even if the
// containing package claims to have no side effects.
// Remove this when webpack adds a warning or an error for this.
// See https://github.com/webpack/webpack/issues/6571
sideEffects: true,
},
// Adds support for CSS Modules (https://github.com/css-modules/css-modules)
// using the extension .module.css
{
test: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
sourceMap: isEnvProduction
? shouldUseSourceMap
: isEnvDevelopment,
modules: {
getLocalIdent: getCSSModuleLocalIdent,
},
}),
},
// Opt-in support for SASS (using .scss or .sass extensions).
// By default we support SASS Modules with the
// extensions .module.scss or .module.sass
{
test: sassRegex,
exclude: sassModuleRegex,
use: getStyleLoaders(
{
importLoaders: 3,
sourceMap: isEnvProduction
? shouldUseSourceMap
: isEnvDevelopment,
},
'sass-loader'
),
// Don't consider CSS imports dead code even if the
// containing package claims to have no side effects.
// Remove this when webpack adds a warning or an error for this.
// See https://github.com/webpack/webpack/issues/6571
sideEffects: true,
},
// Adds support for CSS Modules, but using SASS
// using the extension .module.scss or .module.sass
{
test: sassModuleRegex,
use: getStyleLoaders(
{
importLoaders: 3,
sourceMap: isEnvProduction
? shouldUseSourceMap
: isEnvDevelopment,
modules: {
getLocalIdent: getCSSModuleLocalIdent,
},
},
'sass-loader'
),
},
// "file" loader makes sure those assets get served by WebpackDevServer.
// When you `import` an asset, you get its (virtual) filename.
// In production, they would get copied to the `build` folder.
// This loader doesn't use a "test" so it will catch all modules
// that fall through the other loaders.
{
loader: require.resolve('file-loader'),
// Exclude `js` files to keep "css" loader working as it injects
// its runtime that would otherwise be processed through "file" loader.
// Also exclude `html` and `json` extensions so they get processed
// by webpacks internal loaders.
exclude: [/\.(js|mjs|jsx|ts|tsx)$/, /\.html$/, /\.json$/],
options: {
name: 'static/media/[name].[hash:8].[ext]',
},
},
// ** STOP ** Are you adding a new loader?
// Make sure to add the new loader(s) before the "file" loader.
],
},
],
},
plugins: [
// Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin(
Object.assign(
{},
{
inject: true,
template: paths.appHtml,
},
isEnvProduction
? {
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true,
},
}
: undefined
)
),
// Inlines the webpack runtime script. This script is too small to warrant
// a network request.
// https://github.com/facebook/create-react-app/issues/5358
isEnvProduction &&
shouldInlineRuntimeChunk &&
new InlineChunkHtmlPlugin(HtmlWebpackPlugin, [/runtime-.+[.]js/]),
// Makes some environment variables available in index.html.
// The public URL is available as %PUBLIC_URL% in index.html, e.g.:
// <link rel="icon" href="%PUBLIC_URL%/favicon.ico">
// It will be an empty string unless you specify "homepage"
// in `package.json`, in which case it will be the pathname of that URL.
new InterpolateHtmlPlugin(HtmlWebpackPlugin, env.raw),
// This gives some necessary context to module not found errors, such as
// the requesting resource.
new ModuleNotFoundPlugin(paths.appPath),
// Makes some environment variables available to the JS code, for example:
// if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
// It is absolutely essential that NODE_ENV is set to production
// during a production build.
// Otherwise React will be compiled in the very slow development mode.
new webpack.DefinePlugin(env.stringified),
// This is necessary to emit hot updates (CSS and Fast Refresh):
isEnvDevelopment && new webpack.HotModuleReplacementPlugin(),
// Experimental hot reloading for React .
// https://github.com/facebook/react/tree/master/packages/react-refresh
isEnvDevelopment &&
shouldUseReactRefresh &&
new ReactRefreshWebpackPlugin({
overlay: {
entry: webpackDevClientEntry,
// The expected exports are slightly different from what the overlay exports,
// so an interop is included here to enable feedback on module-level errors.
module: reactRefreshOverlayEntry,
// Since we ship a custom dev client and overlay integration,
// the bundled socket handling logic can be eliminated.
sockIntegration: false,
},
}),
// Watcher doesn't work well if you mistype casing in a path so we use
// a plugin that prints an error when you attempt to do this.
// See https://github.com/facebook/create-react-app/issues/240
isEnvDevelopment && new CaseSensitivePathsPlugin(),
// If you require a missing module and then `npm install` it, you still have
// to restart the development server for webpack to discover it. This plugin
// makes the discovery automatic so you don't have to restart.
// See https://github.com/facebook/create-react-app/issues/186
isEnvDevelopment &&
new WatchMissingNodeModulesPlugin(paths.appNodeModules),
isEnvProduction &&
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: 'static/css/[name].[contenthash:8].css',
chunkFilename: 'static/css/[name].[contenthash:8].chunk.css',
}),
// Generate an asset manifest file with the following content:
// - "files" key: Mapping of all asset filenames to their corresponding
// output file so that tools can pick it up without having to parse
// `index.html`
// - "entrypoints" key: Array of files which are included in `index.html`,
// can be used to reconstruct the HTML if necessary
new ManifestPlugin({
fileName: 'asset-manifest.json',
publicPath: paths.publicUrlOrPath,
generate: (seed, files, entrypoints) => {
const manifestFiles = files.reduce((manifest, file) => {
manifest[file.name] = file.path;
return manifest;
}, seed);
const entrypointFiles = entrypoints.main.filter(
fileName => !fileName.endsWith('.map')
);
return {
files: manifestFiles,
entrypoints: entrypointFiles,
};
},
}),
// Moment.js is an extremely popular library that bundles large locale files
// by default due to how webpack interprets its code. This is a practical
// solution that requires the user to opt into importing specific locales.
// https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
// You can remove this if you don't use Moment.js:
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
// Generate a service worker script that will precache, and keep up to date,
// the HTML & assets that are part of the webpack build.
isEnvProduction &&
fs.existsSync(swSrc) &&
new WorkboxWebpackPlugin.InjectManifest({
swSrc,
dontCacheBustURLsMatching: /\.[0-9a-f]{8}\./,
exclude: [/\.map$/, /asset-manifest\.json$/, /LICENSE/],
// Bump up the default maximum size (2mb) that's precached,
// to make lazy-loading failure scenarios less likely.
// See https://github.com/cra-template/pwa/issues/13#issuecomment-722667270
maximumFileSizeToCacheInBytes: 5 * 1024 * 1024,
}),
// TypeScript type checking
useTypeScript &&
new ForkTsCheckerWebpackPlugin({
typescript: resolve.sync('typescript', {
basedir: paths.appNodeModules,
}),
async: isEnvDevelopment,
checkSyntacticErrors: true,
resolveModuleNameModule: process.versions.pnp
? `${__dirname}/pnpTs.js`
: undefined,
resolveTypeReferenceDirectiveModule: process.versions.pnp
? `${__dirname}/pnpTs.js`
: undefined,
tsconfig: paths.appTsConfig,
reportFiles: [
// This one is specifically to match during CI tests,
// as micromatch doesn't match
// '../cra-template-typescript/template/src/App.tsx'
// otherwise.
'../**/src/**/*.{ts,tsx}',
'**/src/**/*.{ts,tsx}',
'!**/src/**/__tests__/**',
'!**/src/**/?(*.)(spec|test).*',
'!**/src/setupProxy.*',
'!**/src/setupTests.*',
],
silent: true,
// The formatter is invoked directly in WebpackDevServerUtils during development
formatter: isEnvProduction ? typescriptFormatter : undefined,
}),
!disableESLintPlugin &&
new ESLintPlugin({
// Plugin options
extensions: ['js', 'mjs', 'jsx', 'ts', 'tsx'],
formatter: require.resolve('react-dev-utils/eslintFormatter'),
eslintPath: require.resolve('eslint'),
failOnError: !(isEnvDevelopment && emitErrorsAsWarnings),
context: paths.appSrc,
cache: true,
cacheLocation: path.resolve(
paths.appNodeModules,
'.cache/.eslintcache'
),
// ESLint class options
cwd: paths.appPath,
resolvePluginsRelativeTo: __dirname,
baseConfig: {
extends: [require.resolve('eslint-config-react-app/base')],
rules: {
...(!hasJsxRuntime && {
'react/react-in-jsx-scope': 'error',
}),
},
},
}),
].filter(Boolean),
// Some libraries import Node modules but don't use them in the browser.
// Tell webpack to provide empty mocks for them so importing them works.
node: {
module: 'empty',
dgram: 'empty',
dns: 'mock',
fs: 'empty',
http2: 'empty',
net: 'empty',
tls: 'empty',
child_process: 'empty',
},
// Turn off performance processing because we utilize
// our own hints via the FileSizeReporter
performance: false,
};
};

@ -0,0 +1,130 @@
'use strict';
const fs = require('fs');
const errorOverlayMiddleware = require('react-dev-utils/errorOverlayMiddleware');
const evalSourceMapMiddleware = require('react-dev-utils/evalSourceMapMiddleware');
const noopServiceWorkerMiddleware = require('react-dev-utils/noopServiceWorkerMiddleware');
const ignoredFiles = require('react-dev-utils/ignoredFiles');
const redirectServedPath = require('react-dev-utils/redirectServedPathMiddleware');
const paths = require('./paths');
const getHttpsConfig = require('./getHttpsConfig');
const host = process.env.HOST || '0.0.0.0';
const sockHost = process.env.WDS_SOCKET_HOST;
const sockPath = process.env.WDS_SOCKET_PATH; // default: '/sockjs-node'
const sockPort = process.env.WDS_SOCKET_PORT;
module.exports = function (proxy, allowedHost) {
return {
// WebpackDevServer 2.4.3 introduced a security fix that prevents remote
// websites from potentially accessing local content through DNS rebinding:
// https://github.com/webpack/webpack-dev-server/issues/887
// https://medium.com/webpack/webpack-dev-server-middleware-security-issues-1489d950874a
// However, it made several existing use cases such as development in cloud
// environment or subdomains in development significantly more complicated:
// https://github.com/facebook/create-react-app/issues/2271
// https://github.com/facebook/create-react-app/issues/2233
// While we're investigating better solutions, for now we will take a
// compromise. Since our WDS configuration only serves files in the `public`
// folder we won't consider accessing them a vulnerability. However, if you
// use the `proxy` feature, it gets more dangerous because it can expose
// remote code execution vulnerabilities in backends like Django and Rails.
// So we will disable the host check normally, but enable it if you have
// specified the `proxy` setting. Finally, we let you override it if you
// really know what you're doing with a special environment variable.
disableHostCheck:
!proxy || process.env.DANGEROUSLY_DISABLE_HOST_CHECK === 'true',
// Enable gzip compression of generated files.
compress: true,
// Silence WebpackDevServer's own logs since they're generally not useful.
// It will still show compile warnings and errors with this setting.
clientLogLevel: 'none',
// By default WebpackDevServer serves physical files from current directory
// in addition to all the virtual build products that it serves from memory.
// This is confusing because those files won’t automatically be available in
// production build folder unless we copy them. However, copying the whole
// project directory is dangerous because we may expose sensitive files.
// Instead, we establish a convention that only files in `public` directory
// get served. Our build script will copy `public` into the `build` folder.
// In `index.html`, you can get URL of `public` folder with %PUBLIC_URL%:
// <link rel="icon" href="%PUBLIC_URL%/favicon.ico">
// In JavaScript code, you can access it with `process.env.PUBLIC_URL`.
// Note that we only recommend to use `public` folder as an escape hatch
// for files like `favicon.ico`, `manifest.json`, and libraries that are
// for some reason broken when imported through webpack. If you just want to
// use an image, put it in `src` and `import` it from JavaScript instead.
contentBase: paths.appPublic,
contentBasePublicPath: paths.publicUrlOrPath,
// By default files from `contentBase` will not trigger a page reload.
watchContentBase: true,
// Enable hot reloading server. It will provide WDS_SOCKET_PATH endpoint
// for the WebpackDevServer client so it can learn when the files were
// updated. The WebpackDevServer client is included as an entry point
// in the webpack development configuration. Note that only changes
// to CSS are currently hot reloaded. JS changes will refresh the browser.
hot: true,
// Use 'ws' instead of 'sockjs-node' on server since we're using native
// websockets in `webpackHotDevClient`.
transportMode: 'ws',
// Prevent a WS client from getting injected as we're already including
// `webpackHotDevClient`.
injectClient: false,
// Enable custom sockjs pathname for websocket connection to hot reloading server.
// Enable custom sockjs hostname, pathname and port for websocket connection
// to hot reloading server.
sockHost,
sockPath,
sockPort,
// It is important to tell WebpackDevServer to use the same "publicPath" path as
// we specified in the webpack config. When homepage is '.', default to serving
// from the root.
// remove last slash so user can land on `/test` instead of `/test/`
publicPath: paths.publicUrlOrPath.slice(0, -1),
// WebpackDevServer is noisy by default so we emit custom message instead
// by listening to the compiler events with `compiler.hooks[...].tap` calls above.
quiet: true,
// Reportedly, this avoids CPU overload on some systems.
// https://github.com/facebook/create-react-app/issues/293
// src/node_modules is not ignored to support absolute imports
// https://github.com/facebook/create-react-app/issues/1065
watchOptions: {
ignored: ignoredFiles(paths.appSrc),
},
https: getHttpsConfig(),
host,
overlay: false,
historyApiFallback: {
// Paths with dots should still use the history fallback.
// See https://github.com/facebook/create-react-app/issues/387.
disableDotRule: true,
index: paths.publicUrlOrPath,
},
public: allowedHost,
// `proxy` is run between `before` and `after` `webpack-dev-server` hooks
proxy,
before(app, server) {
// Keep `evalSourceMapMiddleware` and `errorOverlayMiddleware`
// middlewares before `redirectServedPath` otherwise will not have any effect
// This lets us fetch source contents from webpack for the error overlay
app.use(evalSourceMapMiddleware(server));
// This lets us open files from the runtime error overlay.
app.use(errorOverlayMiddleware());
if (fs.existsSync(paths.proxySetup)) {
// This registers user provided middleware for proxy reasons
require(paths.proxySetup)(app);
}
},
after(app) {
// Redirect to `PUBLIC_URL` or `homepage` from `package.json` if url not match
app.use(redirectServedPath(paths.publicUrlOrPath));
// This service worker file is effectively a 'no-op' that will reset any
// previous service worker registered for the same host:port combination.
// We do this in development to avoid hitting the production cache if
// it used the same host and port.
// https://github.com/facebook/create-react-app/issues/2272#issuecomment-302832432
app.use(noopServiceWorkerMiddleware(paths.publicUrlOrPath));
},
};
};

File diff suppressed because it is too large Load Diff

@ -1,8 +1,11 @@
{
"name": "hexmap",
"name": "hexmap-client",
"version": "0.1.0",
"private": true,
"dependencies": {
"@babel/core": "^7.13.0",
"@pmmmwh/react-refresh-webpack-plugin": "0.4.3",
"@svgr/webpack": "5.5.0",
"@testing-library/jest-dom": "^5.14.1",
"@testing-library/react": "^11.2.7",
"@testing-library/user-event": "^12.8.3",
@ -11,18 +14,76 @@
"@types/react": "^17.0.13",
"@types/react-color": "^3.0.5",
"@types/react-dom": "^17.0.8",
"@typescript-eslint/eslint-plugin": "^4.5.0",
"@typescript-eslint/parser": "^4.5.0",
"babel-eslint": "^10.1.0",
"babel-jest": "^26.6.0",
"babel-loader": "8.1.0",
"babel-plugin-named-asset-import": "^0.3.7",
"babel-preset-react-app": "^10.0.0",
"base64-arraybuffer": "^0.2.0",
"bfj": "^7.0.2",
"camelcase": "^6.1.0",
"case-sensitive-paths-webpack-plugin": "2.3.0",
"css-loader": "4.3.0",
"dotenv": "8.2.0",
"dotenv-expand": "5.1.0",
"eslint": "^7.11.0",
"eslint-config-react-app": "^6.0.0",
"eslint-plugin-flowtype": "^5.2.0",
"eslint-plugin-import": "^2.22.1",
"eslint-plugin-jest": "^24.1.0",
"eslint-plugin-jsx-a11y": "^6.3.1",
"eslint-plugin-react": "^7.21.5",
"eslint-plugin-react-hooks": "^4.2.0",
"eslint-plugin-testing-library": "^3.9.2",
"eslint-webpack-plugin": "^2.5.2",
"file-loader": "6.1.1",
"fs-extra": "^9.0.1",
"html-webpack-plugin": "4.5.0",
"identity-obj-proxy": "3.0.0",
"jest": "26.6.0",
"jest-circus": "26.6.0",
"jest-resolve": "26.6.0",
"jest-watch-typeahead": "0.6.1",
"mini-css-extract-plugin": "0.11.3",
"optimize-css-assets-webpack-plugin": "5.0.4",
"pnp-webpack-plugin": "1.6.4",
"postcss-flexbugs-fixes": "4.2.1",
"postcss-loader": "3.0.0",
"postcss-normalize": "8.0.1",
"postcss-preset-env": "6.7.0",
"postcss-safe-parser": "5.0.2",
"prompts": "2.4.0",
"protobufjs": "^6.11.2",
"protoc-tools": "^3.11.3",
"react": "^17.0.2",
"react-app-polyfill": "^2.0.0",
"react-color": "^2.19.3",
"react-dev-utils": "^11.0.3",
"react-dom": "^17.0.2",
"react-scripts": "4.0.3",
"react-refresh": "^0.8.3",
"resolve": "1.18.1",
"resolve-url-loader": "^3.1.2",
"sass-loader": "^10.0.5",
"semver": "7.3.2",
"style-loader": "1.3.0",
"terser-webpack-plugin": "4.2.3",
"ts-pnp": "1.2.0",
"ts-proto": "^1.82.2",
"typescript": "^4.3.5",
"web-vitals": "^1.1.2"
"url-loader": "4.1.1",
"web-vitals": "^1.1.2",
"webpack": "4.44.2",
"webpack-dev-server": "3.11.1",
"webpack-manifest-plugin": "2.2.0",
"workbox-webpack-plugin": "5.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
"protoc": "mkdir -p ../common/src/proto && protoc -I=proto --plugin=node_modules/.bin/protoc-gen-ts_proto --ts_proto_out=src/proto --ts_proto_opt=env=both --ts_proto_opt=esModuleInterop=true proto/*.proto",
"start": "node scripts/start.js",
"build": "npm run protoc && node scripts/build.js",
"test": "node scripts/test.js"
},
"eslintConfig": {
"extends": [
@ -41,5 +102,64 @@
"last 1 firefox version",
"last 1 safari version"
]
},
"jest": {
"roots": [
"<rootDir>/src"
],
"collectCoverageFrom": [
"src/**/*.{js,jsx,ts,tsx}",
"!src/**/*.d.ts"
],
"setupFiles": [
"react-app-polyfill/jsdom"
],
"setupFilesAfterEnv": [
"<rootDir>/src/setupTests.ts"
],
"testMatch": [
"<rootDir>/src/**/__tests__/**/*.{js,jsx,ts,tsx}",
"<rootDir>/src/**/*.{spec,test}.{js,jsx,ts,tsx}"
],
"testEnvironment": "jsdom",
"testRunner": "/home/reya/go/src/hexmap/node_modules/jest-circus/runner.js",
"transform": {
"^.+\\.(js|jsx|mjs|cjs|ts|tsx)$": "<rootDir>/config/jest/babelTransform.js",
"^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
"^(?!.*\\.(js|jsx|mjs|cjs|ts|tsx|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
},
"transformIgnorePatterns": [
"[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs|cjs|ts|tsx)$",
"^.+\\.module\\.(css|sass|scss)$"
],
"modulePaths": [
"/home/reya/go/src/hexmap/src"
],
"moduleNameMapper": {
"^react-native$": "react-native-web",
"^.+\\.module\\.(css|sass|scss)$": "identity-obj-proxy"
},
"moduleFileExtensions": [
"web.js",
"js",
"web.ts",
"ts",
"web.tsx",
"tsx",
"json",
"web.jsx",
"jsx",
"node"
],
"watchPlugins": [
"jest-watch-typeahead/filename",
"jest-watch-typeahead/testname"
],
"resetMocks": true
},
"babel": {
"presets": [
"react-app"
]
}
}

@ -0,0 +1,212 @@
'use strict';
// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'production';
process.env.NODE_ENV = 'production';
// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
throw err;
});
// Ensure environment variables are read.
require('../config/env');
const path = require('path');
const chalk = require('react-dev-utils/chalk');
const fs = require('fs-extra');
const bfj = require('bfj');
const webpack = require('webpack');
const configFactory = require('../config/webpack.config');
const paths = require('../config/paths');
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
const formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
const printHostingInstructions = require('react-dev-utils/printHostingInstructions');
const FileSizeReporter = require('react-dev-utils/FileSizeReporter');
const printBuildError = require('react-dev-utils/printBuildError');
const measureFileSizesBeforeBuild =
FileSizeReporter.measureFileSizesBeforeBuild;
const printFileSizesAfterBuild = FileSizeReporter.printFileSizesAfterBuild;
const useYarn = fs.existsSync(paths.yarnLockFile);
// These sizes are pretty large. We'll warn for bundles exceeding them.
const WARN_AFTER_BUNDLE_GZIP_SIZE = 512 * 1024;
const WARN_AFTER_CHUNK_GZIP_SIZE = 1024 * 1024;
const isInteractive = process.stdout.isTTY;
// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
process.exit(1);
}
const argv = process.argv.slice(2);
const writeStatsJson = argv.indexOf('--stats') !== -1;
// Generate configuration
const config = configFactory('production');
// We require that you explicitly set browsers and do not fall back to
// browserslist defaults.
const { checkBrowsers } = require('react-dev-utils/browsersHelper');
checkBrowsers(paths.appPath, isInteractive)
.then(() => {
// First, read the current file sizes in build directory.
// This lets us display how much they changed later.
return measureFileSizesBeforeBuild(paths.appBuild);
})
.then(previousFileSizes => {
// Remove all content but keep the directory so that
// if you're in it, you don't end up in Trash
fs.emptyDirSync(paths.appBuild);
// Merge with the public folder
copyPublicFolder();
// Start the webpack build
return build(previousFileSizes);
})
.then(
({ stats, previousFileSizes, warnings }) => {
if (warnings.length) {
console.log(chalk.yellow('Compiled with warnings.\n'));
console.log(warnings.join('\n\n'));
console.log(
'\nSearch for the ' +
chalk.underline(chalk.yellow('keywords')) +
' to learn more about each warning.'
);
console.log(
'To ignore, add ' +
chalk.cyan('// eslint-disable-next-line') +
' to the line before.\n'
);
} else {
console.log(chalk.green('Compiled successfully.\n'));
}
console.log('File sizes after gzip:\n');
printFileSizesAfterBuild(
stats,
previousFileSizes,
paths.appBuild,
WARN_AFTER_BUNDLE_GZIP_SIZE,
WARN_AFTER_CHUNK_GZIP_SIZE
);
console.log();
const appPackage = require(paths.appPackageJson);
const publicUrl = paths.publicUrlOrPath;
const publicPath = config.output.publicPath;
const buildFolder = path.relative(process.cwd(), paths.appBuild);
printHostingInstructions(
appPackage,
publicUrl,
publicPath,
buildFolder,
useYarn
);
},
err => {
const tscCompileOnError = process.env.TSC_COMPILE_ON_ERROR === 'true';
if (tscCompileOnError) {
console.log(
chalk.yellow(
'Compiled with the following type errors (you may want to check these before deploying your app):\n'
)
);
printBuildError(err);
} else {
console.log(chalk.red('Failed to compile.\n'));
printBuildError(err);
process.exit(1);
}
}
)
.catch(err => {
if (err && err.message) {
console.log(err.message);
}
process.exit(1);
});
// Create the production build and print the deployment instructions.
function build(previousFileSizes) {
console.log('Creating an optimized production build...');
const compiler = webpack(config);
return new Promise((resolve, reject) => {
compiler.run((err, stats) => {
let messages;
if (err) {
if (!err.message) {
return reject(err);
}
let errMessage = err.message;
// Add additional information for postcss errors
if (Object.prototype.hasOwnProperty.call(err, 'postcssNode')) {
errMessage +=
'\nCompileError: Begins at CSS selector ' +
err['postcssNode'].selector;
}
messages = formatWebpackMessages({
errors: [errMessage],
warnings: [],
});
} else {
messages = formatWebpackMessages(
stats.toJson({ all: false, warnings: true, errors: true })
);
}
if (messages.errors.length) {
// Only keep the first error. Others are often indicative
// of the same problem, but confuse the reader with noise.
if (messages.errors.length > 1) {
messages.errors.length = 1;
}
return reject(new Error(messages.errors.join('\n\n')));
}
if (
process.env.CI &&
(typeof process.env.CI !== 'string' ||
process.env.CI.toLowerCase() !== 'false') &&
messages.warnings.length
) {
console.log(
chalk.yellow(
'\nTreating warnings as errors because process.env.CI = true.\n' +
'Most CI servers set it automatically.\n'
)
);
return reject(new Error(messages.warnings.join('\n\n')));
}
const resolveArgs = {
stats,
previousFileSizes,
warnings: messages.warnings,
};
if (writeStatsJson) {
return bfj
.write(paths.appBuild + '/bundle-stats.json', stats.toJson())
.then(() => resolve(resolveArgs))
.catch(error => reject(new Error(error)));
}
return resolve(resolveArgs);
});
});
}
function copyPublicFolder() {
fs.copySync(paths.appPublic, paths.appBuild, {
dereference: true,
filter: file => file !== paths.appHtml,
});
}

@ -0,0 +1,166 @@
'use strict';
// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'development';
process.env.NODE_ENV = 'development';
// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
throw err;
});
// Ensure environment variables are read.
require('../config/env');
const fs = require('fs');
const chalk = require('react-dev-utils/chalk');
const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const clearConsole = require('react-dev-utils/clearConsole');
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
const {
choosePort,
createCompiler,
prepareProxy,
prepareUrls,
} = require('react-dev-utils/WebpackDevServerUtils');
const openBrowser = require('react-dev-utils/openBrowser');
const semver = require('semver');
const paths = require('../config/paths');
const configFactory = require('../config/webpack.config');
const createDevServerConfig = require('../config/webpackDevServer.config');
const getClientEnvironment = require('../config/env');
const react = require(require.resolve('react', { paths: [paths.appPath] }));
const env = getClientEnvironment(paths.publicUrlOrPath.slice(0, -1));
const useYarn = fs.existsSync(paths.yarnLockFile);
const isInteractive = process.stdout.isTTY;
// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
process.exit(1);
}
// Tools like Cloud9 rely on this.
const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000;
const HOST = process.env.HOST || '0.0.0.0';
if (process.env.HOST) {
console.log(
chalk.cyan(
`Attempting to bind to HOST environment variable: ${chalk.yellow(
chalk.bold(process.env.HOST)
)}`
)
);
console.log(
`If this was unintentional, check that you haven't mistakenly set it in your shell.`
);
console.log(
`Learn more here: ${chalk.yellow('https://cra.link/advanced-config')}`
);
console.log();
}
// We require that you explicitly set browsers and do not fall back to
// browserslist defaults.
const { checkBrowsers } = require('react-dev-utils/browsersHelper');
checkBrowsers(paths.appPath, isInteractive)
.then(() => {
// We attempt to use the default port but if it is busy, we offer the user to
// run on a different port. `choosePort()` Promise resolves to the next free port.
return choosePort(HOST, DEFAULT_PORT);
})
.then(port => {
if (port == null) {
// We have not found a port.
return;
}
const config = configFactory('development');
const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
const appName = require(paths.appPackageJson).name;
const useTypeScript = fs.existsSync(paths.appTsConfig);
const tscCompileOnError = process.env.TSC_COMPILE_ON_ERROR === 'true';
const urls = prepareUrls(
protocol,
HOST,
port,
paths.publicUrlOrPath.slice(0, -1)
);
const devSocket = {
warnings: warnings =>
devServer.sockWrite(devServer.sockets, 'warnings', warnings),
errors: errors =>
devServer.sockWrite(devServer.sockets, 'errors', errors),
};
// Create a webpack compiler that is configured with custom messages.
const compiler = createCompiler({
appName,
config,
devSocket,
urls,
useYarn,
useTypeScript,
tscCompileOnError,
webpack,
});
// Load proxy config
const proxySetting = require(paths.appPackageJson).proxy;
const proxyConfig = prepareProxy(
proxySetting,
paths.appPublic,
paths.publicUrlOrPath
);
// Serve webpack assets generated by the compiler over a web server.
const serverConfig = createDevServerConfig(
proxyConfig,
urls.lanUrlForConfig
);
const devServer = new WebpackDevServer(compiler, serverConfig);
// Launch WebpackDevServer.
devServer.listen(port, HOST, err => {
if (err) {
return console.log(err);
}
if (isInteractive) {
clearConsole();
}
if (env.raw.FAST_REFRESH && semver.lt(react.version, '16.10.0')) {
console.log(
chalk.yellow(
`Fast Refresh requires React 16.10 or higher. You are using React ${react.version}.`
)
);
}
console.log(chalk.cyan('Starting the development server...\n'));
openBrowser(urls.localUrlForBrowser);
});
['SIGINT', 'SIGTERM'].forEach(function (sig) {
process.on(sig, function () {
devServer.close();
process.exit();
});
});
if (process.env.CI !== 'true') {
// Gracefully exit when stdin ends
process.stdin.on('end', function () {
devServer.close();
process.exit();
});
}
})
.catch(err => {
if (err && err.message) {
console.log(err.message);
}
process.exit(1);
});

@ -0,0 +1,53 @@
'use strict';
// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'test';
process.env.NODE_ENV = 'test';
process.env.PUBLIC_URL = '';
// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
throw err;
});
// Ensure environment variables are read.
require('../config/env');
const jest = require('jest');
const execSync = require('child_process').execSync;
let argv = process.argv.slice(2);
function isInGitRepository() {
try {
execSync('git rev-parse --is-inside-work-tree', { stdio: 'ignore' });
return true;
} catch (e) {
return false;
}
}
function isInMercurialRepository() {
try {
execSync('hg --cwd . root', { stdio: 'ignore' });
return true;
} catch (e) {
return false;
}
}
// Watch unless on CI or explicitly running all tests
if (
!process.env.CI &&
argv.indexOf('--watchAll') === -1 &&
argv.indexOf('--watchAll=false') === -1
) {
// https://github.com/facebook/create-react-app/issues/5210
const hasSourceControl = isInGitRepository() || isInMercurialRepository();
argv.push(hasSourceControl ? '--watch' : '--watchAll');
}
jest.run(argv);

@ -1,65 +0,0 @@
import React, {useMemo, useReducer} from 'react';
import './App.css';
import {DispatchContext} from './ui/context/DispatchContext';
import {appStateReducer, AppStateReducer} from "./reducers/AppStateReducer";
import {USER_ACTIVE_COLOR} from "./actions/UserAction";
import {ServerConnectionState} from "./state/NetworkState";
import HexMapRenderer from "./ui/HexMapRenderer";
import HexColorPicker from "./ui/HexColorPicker";
import {sizeFromLinesAndCells} from "./state/Coordinates";
import {ConsoleConnector} from "./ui/debug/ConsoleConnection";
function App() {
const [state, dispatch] = useReducer<AppStateReducer, null>(
appStateReducer,
null,
() => ({
localState: null,
network: {
serverState: null,
connectionState: ServerConnectionState.OFFLINE,
specialMessage: null,
nextID: 0,
sentActions: [],
pendingActions: [],
goodbyeCode: 1000,
goodbyeReason: "",
autoReconnectAt: null,
reconnectAttempts: null
}
}));
const {user, map} = state.localState || {user: null, map: null}
const offsets = useMemo(() => (!!map ? {
top: 10,
left: 10,
size: 50,
displayMode: map.displayMode
} : null), [map])
const mapElement = !!offsets && !!map ? <HexMapRenderer map={map} offsets={offsets} /> : null;
const {width, height} = useMemo(() => !!offsets && !!map ? sizeFromLinesAndCells({
bottomMargin: 10, cells: map.cellsPerLine, lines: map.lines, offsets: offsets, rightMargin: 10
}) : {width: 1, height: 1}, [map, offsets]);
const colorPickerElement = !!user ? <HexColorPicker color={user?.activeColor} onChangeComplete={(colorResult) => dispatch({
type: USER_ACTIVE_COLOR,
color: colorResult.hex
})} /> : null
return (
<div className="App">
<DispatchContext.Provider value={dispatch}>
<div className={"scrollbox"}>
<div className={"centerbox"}>
<svg className={"map"} width={width} height={height} viewBox={`0 0 ${width} ${height}`} onContextMenu={(e) => e.preventDefault()}>
{mapElement}
</svg>
</div>
</div>
{colorPickerElement}
<ConsoleConnector specialMessage={state.network.specialMessage} pendingMessages={state.network.pendingActions} nextID={state.network.nextID} />
</DispatchContext.Provider>
</div>
);
}
export default App;

@ -1,178 +0,0 @@
import {BaseAction} from "./BaseAction";
import {AppAction} from "./AppAction";
import {CellColorAction, isCellColorAction} from "./CellAction";
import {SyncedState} from "../state/SyncedState";
import {isUserActiveColorAction, UserActiveColorAction} from "./UserAction";
// TODO: Split into ServerAction and ClientAction files
export const SERVER_HELLO = "SERVER_HELLO"
/** Sent in response to the client's ClientHelloAction when the client has been accepted. */
export interface ServerHelloAction extends BaseAction {
readonly type: typeof SERVER_HELLO
/** The protocol version the server is running on. */
readonly version: number
/** The current state of the server as of when the client connected. */
readonly state: SyncedState
}
export function isServerHelloAction(action: AppAction): action is ServerHelloAction {
return action.type === SERVER_HELLO
}
export const SERVER_GOODBYE = "SERVER_GOODBYE"
/** Synthesized when the server closes the connection. */
export interface ServerGoodbyeAction extends BaseAction {
readonly type: typeof SERVER_GOODBYE
/** The error code sent with the close message by the server, or -1 if our side crashed.*/
readonly code: number
/** The text of the server's goodbye message, or the exception message if our side crashed. */
readonly reason: string
/** The current time when this close message was received. */
readonly currentTime: Date
}
export function isServerGoodbyeAction(action: AppAction): action is ServerGoodbyeAction {
return action.type === SERVER_GOODBYE
}
export const SERVER_REFRESH = "SERVER_REFRESH"
/** Sent in response to the client's ClientRefreshAction. */
export interface ServerRefreshAction extends BaseAction {
readonly type: typeof SERVER_REFRESH
/** The current state of the server as of when the client's refresh request was processed. */
readonly state: SyncedState
}
export function isServerRefreshAction(action: AppAction): action is ServerRefreshAction {
return action.type === SERVER_REFRESH
}
export const SERVER_OK = "SERVER_OK"
/** Sent in response to the client's ClientNestedAction, if it succeeds and is applied to the server map. */
export interface ServerOKAction extends BaseAction {
readonly type: typeof SERVER_OK
/**
* The IDs of the successful actions.
* These will always be sent in sequential order - the order in which the server received and applied them.
* This allows the client to apply that set of actions to its server-state copy and then refresh its local copy.
*/
readonly ids: readonly number[]
}
export function isServerOKAction(action: AppAction): action is ServerOKAction {
return action.type === SERVER_OK
}
export interface ActionFailure {
readonly id: number
readonly error: string
}
export const SERVER_FAILED = "SERVER_FAILED"
/** Sent in response to the client's ClientNestedAction, if it fails and has not been applied to the server map. */
export interface ServerFailedAction extends BaseAction {
readonly type: typeof SERVER_FAILED
/** The IDs of the failed actions, all of which failed with the same error. */
readonly ids: readonly number[]
/** The error the above actions failed with. */
readonly error: string
}
export function isServerFailedAction(action: AppAction): action is ServerFailedAction {
return action.type === SERVER_FAILED
}
export enum SocketState {
CONNECTING = "CONNECTING",
OPEN = "OPEN",
}
export const SERVER_SOCKET_STARTUP = "SERVER_SOCKET_STARTUP"
/** Synthesized when the websocket begins connecting, i.e., enters the Connecting or Open states.. */
export interface ServerSocketStartupAction extends BaseAction {
readonly type: typeof SERVER_SOCKET_STARTUP
readonly state: SocketState
}
export function isServerSocketStartupAction(action: AppAction): action is ServerSocketStartupAction {
return action.type === SERVER_SOCKET_STARTUP
}
export const SERVER_ACT = "SERVER_ACT"
/** Sent by the server when another client has performed an action. Never sent for the client's own actions. */
export interface ServerActAction extends BaseAction {
readonly type: typeof SERVER_ACT
readonly actions: readonly SyncableAction[]
}
export function isServerActAction(action: AppAction): action is ServerActAction {
return action.type === SERVER_ACT
}
export type SyncableAction = SendableAction
export function isSyncableAction(action: AppAction): action is SyncableAction {
return isSendableAction(action)
}
export type ServerAction =
ServerHelloAction | ServerGoodbyeAction | ServerRefreshAction |
ServerOKAction | ServerFailedAction |
ServerSocketStartupAction | ServerActAction
export function isServerAction(action: AppAction) {
return isServerHelloAction(action) || isServerGoodbyeAction(action) || isServerRefreshAction(action)
|| isServerOKAction(action) || isServerFailedAction(action)
|| isServerSocketStartupAction(action) || isServerActAction(action)
}
export const CLIENT_HELLO = "CLIENT_HELLO"
/** Sent when the client connects. */
export interface ClientHelloAction extends BaseAction {
readonly type: typeof CLIENT_HELLO
/** The protocol version the client is running on */
readonly version: number
}
export function isClientHelloAction(action: AppAction): action is ClientHelloAction {
return action.type === CLIENT_HELLO
}
export const CLIENT_REFRESH = "CLIENT_REFRESH"
/** Sent when the user requests a refresh, or if a malformed action comes through. */
export interface ClientRefreshAction extends BaseAction {
readonly type: typeof CLIENT_REFRESH
}
export function isClientRefreshAction(action: AppAction): action is ClientRefreshAction {
return action.type === CLIENT_REFRESH
}
export const CLIENT_PENDING = "CLIENT_PENDING"
/** Synthesized when a user action is ready to be sent to the server. */
export interface ClientPendingAction extends BaseAction {
readonly type: typeof CLIENT_PENDING
readonly pending: SendableAction
}
export function isClientPendingAction(action: AppAction): action is ClientPendingAction {
return action.type === CLIENT_PENDING
}
export interface SentAction {
readonly id: number
readonly action: SendableAction
}
export const CLIENT_ACT = "CLIENT_ACT"
/** Sent to the server when the user performs an action. */
export interface ClientActAction extends BaseAction {
readonly type: typeof CLIENT_ACT
readonly actions: readonly SentAction[]
}
export function isClientActAction(action: AppAction): action is ClientActAction {
return action.type === CLIENT_ACT
}
export type SendableAction = CellColorAction | UserActiveColorAction
export function isSendableAction(action: AppAction): action is SendableAction {
return isCellColorAction(action) || isUserActiveColorAction(action)
}
export type ClientAction = ClientHelloAction | ClientRefreshAction | ClientPendingAction | ClientActAction
export function isClientAction(action: AppAction): action is ClientAction {
return isClientHelloAction(action) || isClientRefreshAction(action) || isClientPendingAction(action) || isClientActAction(action)
}
export type NetworkAction = ServerAction | ClientAction;
export function isNetworkAction(action: AppAction): action is NetworkAction {
return isServerAction(action) || isClientAction(action)
}

@ -1,17 +1,3 @@
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import {EntryPoint} from "./ui/EntryPoint";
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();
EntryPoint();

@ -1 +1,71 @@
/// <reference types="react-scripts" />
/// <reference types="node" />
/// <reference types="react" />
/// <reference types="react-dom" />
declare namespace NodeJS {
interface ProcessEnv {
readonly NODE_ENV: 'development' | 'production' | 'test';
readonly PUBLIC_URL: string;
}
}
declare module '*.avif' {
const src: string;
export default src;
}
declare module '*.bmp' {
const src: string;
export default src;
}
declare module '*.gif' {
const src: string;
export default src;
}
declare module '*.jpg' {
const src: string;
export default src;
}
declare module '*.jpeg' {
const src: string;
export default src;
}
declare module '*.png' {
const src: string;
export default src;
}
declare module '*.webp' {
const src: string;
export default src;
}
declare module '*.svg' {
import * as React from 'react';
export const ReactComponent: React.FunctionComponent<React.SVGProps<
SVGSVGElement
> & { title?: string }>;
const src: string;
export default src;
}
declare module '*.module.css' {
const classes: { readonly [key: string]: string };
export default classes;
}
declare module '*.module.scss' {
const classes: { readonly [key: string]: string };
export default classes;
}
declare module '*.module.sass' {
const classes: { readonly [key: string]: string };
export default classes;
}

@ -1,14 +1,15 @@
import {AppAction} from "../actions/AppAction";
import {AppAction} from "../../../common/src/actions/AppAction";
import {AppState} from "../state/AppState";
import {isTileAction} from "../actions/TileAction";
import {isTileAction} from "../../../common/src/actions/TileAction";
import {tileReducer} from "./TileReducer";
import {networkReducer} from "./NetworkReducer";
import {CLIENT_PENDING, isNetworkAction, isSendableAction} from "../actions/NetworkAction";
import {syncedStateReducer} from "./SyncedStateReducer";
import {exhaustivenessCheck} from "../util/TypeUtils";
import {isMapAction, MapAction} from "../actions/MapAction";
import {isUserAction, UserAction} from "../actions/UserAction";
import {CLIENT_PENDING, isSendableAction} from "../../../common/src/actions/ClientAction";
import {syncedStateReducer} from "../../../common/src/reducers/SyncedStateReducer";
import {exhaustivenessCheck} from "../../../common/src/util/TypeUtils";
import {isMapAction, MapAction} from "../../../common/src/actions/MapAction";
import {isUserAction, UserAction} from "../../../common/src/actions/UserAction";
import {clientReducer} from "./ClientReducer";
import {isNetworkAction} from "../../../common/src/actions/NetworkAction";
function appSyncedStateReducer(oldState: AppState, action: MapAction|UserAction): AppState {
if (oldState.localState === null) {

@ -1,4 +1,11 @@
import {CLIENT_HELLO, CLIENT_PENDING, CLIENT_REFRESH, CLIENT_ACT, ClientAction} from "../actions/NetworkAction";
import {
CLIENT_ACT,
CLIENT_GOODBYE,
CLIENT_HELLO,
CLIENT_PENDING,
CLIENT_REFRESH,
ClientAction
} from "../../../common/src/actions/ClientAction";
import {NetworkState, ServerConnectionState} from "../state/NetworkState";
// TODO: Verify that only one special message exists at a time.
@ -34,5 +41,11 @@ export function clientReducer(oldState: NetworkState, action: ClientAction): Net
sentActions: [...oldState.sentActions, ...action.actions],
pendingActions: oldState.pendingActions.slice(action.actions.length),
}
case CLIENT_GOODBYE:
return {
...oldState,
specialMessage: action,
connectionState: ServerConnectionState.AWAITING_GOODBYE,
}
}
}

@ -1,7 +1,10 @@
import {AppState} from "../state/AppState";
import {isClientAction, NetworkAction} from "../actions/NetworkAction";
import {isClientAction} from "../../../common/src/actions/ClientAction";
import {clientReducer} from "./ClientReducer";
import {serverReducer} from "./ServerReducer";
import {NetworkAction} from "../../../common/src/actions/NetworkAction";
import {isServerAction} from "../../../common/src/actions/ServerAction";
import {exhaustivenessCheck} from "../../../common/src/util/TypeUtils";
export function networkReducer(oldState: AppState, action: NetworkAction): AppState {
if (isClientAction(action)) {
@ -14,7 +17,8 @@ export function networkReducer(oldState: AppState, action: NetworkAction): AppSt
...oldState,
network: newState
}
} else /* if (isServerAction(action)) */ {
} else if (isServerAction(action)) {
return serverReducer(oldState, action)
}
exhaustivenessCheck(action)
}

@ -1,29 +1,30 @@
import {AppState} from "../state/AppState";
import {NetworkState, ServerConnectionState} from "../state/NetworkState";
import {SyncedState} from "../../../common/src/state/SyncedState";
import {applySyncableActions} from "../../../common/src/reducers/SyncedStateReducer";
import {clientReducer} from "./ClientReducer";
import {
CLIENT_HELLO,
SendableAction,
SERVER_ACT,
SERVER_FAILED,
SERVER_GOODBYE,
SERVER_HELLO,
SERVER_MALFORMED,
SERVER_OK,
SERVER_REFRESH,
SERVER_ACT,
SERVER_SOCKET_STARTUP,
ServerActCommand,
ServerAction,
ServerFailedAction,
ServerFailedCommand,
ServerGoodbyeAction,
ServerHelloAction,
ServerOKAction,
ServerRefreshAction,
ServerActAction,
ServerHelloCommand,
ServerMalformedAction,
ServerOKCommand,
ServerRefreshCommand,
ServerSocketStartupAction,
SocketState,
SyncableAction,
} from "../actions/NetworkAction";
import {NetworkState, ServerConnectionState} from "../state/NetworkState";
import {SyncedState} from "../state/SyncedState";
import {applySyncableActions} from "./SyncedStateReducer";
import {clientReducer} from "./ClientReducer";
SyncableAction
} from "../../../common/src/actions/ServerAction";
import {CLIENT_GOODBYE, CLIENT_HELLO, SendableAction} from "../../../common/src/actions/ClientAction";
interface StateRecalculationInputs {
/** The original server state before the actions changed. The base on which the actions are all applied. */
@ -59,7 +60,7 @@ function recalculateStates(input: StateRecalculationInputs): StateRecalculationO
return { newServerState, newLocalState, appliedUnsentActions }
}
function serverHelloReducer(oldState: AppState, action: ServerHelloAction): AppState {
function serverHelloReducer(oldState: AppState, action: ServerHelloCommand): AppState {
const {
newServerState,
newLocalState,
@ -86,7 +87,7 @@ function serverHelloReducer(oldState: AppState, action: ServerHelloAction): AppS
}
}
function serverRefreshReducer(oldState: AppState, action: ServerRefreshAction): AppState {
function serverRefreshReducer(oldState: AppState, action: ServerRefreshCommand): AppState {
const {
newServerState,
newLocalState,
@ -123,7 +124,7 @@ function serverGoodbyeReducer(oldState: NetworkState, action: ServerGoodbyeActio
}
}
function serverOkReducer(oldState: AppState, action: ServerOKAction): AppState {
function serverOkReducer(oldState: AppState, action: ServerOKCommand): AppState {
if (oldState.network.serverState === null) {
return oldState
}
@ -153,7 +154,7 @@ function serverOkReducer(oldState: AppState, action: ServerOKAction): AppState {
}
}
function serverFailedReducer(oldState: AppState, action: ServerFailedAction): AppState {
function serverFailedReducer(oldState: AppState, action: ServerFailedCommand): AppState {
if (oldState.network.serverState === null) {
return oldState
}
@ -211,7 +212,7 @@ function serverSocketStartupReducer(oldState: NetworkState, action: ServerSocket
}
}
function serverSentReducer(oldState: AppState, action: ServerActAction): AppState {
function serverActReducer(oldState: AppState, action: ServerActCommand): AppState {
if (oldState.network.serverState === null) {
return oldState
}
@ -237,6 +238,15 @@ function serverSentReducer(oldState: AppState, action: ServerActAction): AppStat
};
}
function serverMalformedReducer(oldState: NetworkState, action: ServerMalformedAction): NetworkState {
console.log("Got serverMalformed", action.error)
return clientReducer(oldState, {
type: CLIENT_GOODBYE,
code: 1002, // protocol error
reason: action.error?.message || "Unknown error"
});
}
export function serverReducer(oldState: AppState, action: ServerAction): AppState {
// TODO: Verify that these messages are only received at the proper times and in the proper states.
// e.g., BeginConnecting should only happen when the state is somewhere in the disconnected region.
@ -262,6 +272,11 @@ export function serverReducer(oldState: AppState, action: ServerAction): AppStat
network: serverSocketStartupReducer(oldState.network, action)
}
case SERVER_ACT:
return serverSentReducer(oldState, action)
return serverActReducer(oldState, action)
case SERVER_MALFORMED:
return {
...oldState,
network: serverMalformedReducer(oldState.network, action)
}
}
}

@ -1,7 +1,7 @@
import {AppState} from "../state/AppState";
import {TILE_PAINT, TILE_REMOVE, TileAction} from "../actions/TileAction";
import {getCell} from "../state/HexMap";
import {CELL_COLOR, CELL_REMOVE} from "../actions/CellAction";
import {TILE_PAINT, TILE_REMOVE, TileAction} from "../../../common/src/actions/TileAction";
import {getCell} from "../../../common/src/state/HexMap";
import {CELL_COLOR, CELL_REMOVE} from "../../../common/src/actions/CellAction";
import {appStateReducer} from "./AppStateReducer";
export function tileReducer(oldState: AppState, action: TileAction): AppState {

@ -1,5 +1,5 @@
import {NetworkState} from "./NetworkState";
import {SyncedState} from "./SyncedState";
import {SyncedState} from "../../../common/src/state/SyncedState";
export interface AppState {
/** The current state of the app with pending actions applied; the local version. */

@ -1,5 +1,11 @@
import {ClientHelloAction, ClientRefreshAction, SendableAction, SentAction} from "../actions/NetworkAction";
import {SyncedState} from "./SyncedState";
import {
ClientGoodbyeAction,
ClientHelloCommand,
ClientRefreshCommand,
SendableAction,
SentAction
} from "../../../common/src/actions/ClientAction";
import {SyncedState} from "../../../common/src/state/SyncedState";
export enum ServerConnectionState {
/** Used when the client is going through the WebSockets connection process and sending a Hello. */
@ -10,12 +16,17 @@ export enum ServerConnectionState {
AWAITING_REFRESH = "AWAITING_REFRESH",
/** Used when the client is connected and everything is normal. */
CONNECTED = "CONNECTED",
/**
* Used when the client has requested that the connection be closed,
* and is waiting for it to actually be closed.
*/
AWAITING_GOODBYE = "AWAITING_GOODBYE",
/**
* Used when the client is disconnected and not currently connecting,
* such as when waiting for the automatic reconnect, or if the browser is currently in offline mode,
* or if the client was disconnected due to a protocol error.
*/
OFFLINE = "OFFLINE",
OFFLINE = "OFFLINE"
}
export interface NetworkState {
@ -35,7 +46,7 @@ export interface NetworkState {
/**
* A special action that should take precedence over sending more actions.
*/
readonly specialMessage: ClientHelloAction|ClientRefreshAction|null
readonly specialMessage: ClientHelloCommand|ClientRefreshCommand|ClientGoodbyeAction|null
/**
* The ID of the next ClientSentAction to be created.
*/
@ -50,7 +61,6 @@ export interface NetworkState {
/**
* The error code of the close message.
* Non-null if and only if the current state is OFFLINE or REJECTED.
* -1 means no onClose was called, and the reason is a stringized error from onError instead.
*/
readonly goodbyeCode: number | null
/**

@ -3,7 +3,7 @@ body {
background-color: #282c34;
}
.App, .scrollbox {
.App, .scrollBox {
position: absolute;
top: 0;
bottom: 0;
@ -11,11 +11,11 @@ body {
right: 0;
}
.scrollbox {
.scrollBox {
overflow-x: scroll;
overflow-y: scroll;
}
.centerbox {
.centerBox {
display: flex;
align-items: center;
justify-content: center;
@ -61,9 +61,9 @@ body {
.colorPickerBackground {
fill: lightslategray;
}
.consoleConnector {
.connectionState {
position: absolute;
text-shadow: white 0 0 5px;
text-shadow: white 0 0 5px, white 0 1px 5px, white 0 -1px 5px, white 1px 0 5px, white -1px 0 5px;
color: black;
top: 0;
right: 0;
@ -72,7 +72,7 @@ body {
.hexColorPicker {
width: 30vw;
}
.centerbox {
.centerBox {
padding-bottom: calc(2vh + (30vw * 126 / 855));
}
}
@ -80,7 +80,7 @@ body {
.hexColorPicker {
width: 300px;
}
.centerbox {
.centerBox {
padding-bottom: calc(2vh + (300px * 126 / 855));
}
}
@ -88,7 +88,7 @@ body {
.hexColorPicker {
width: 98vw;
}
.centerbox {
.centerBox {
padding-bottom: calc(2vh + (98vw * 126 / 855));
}
}

@ -2,8 +2,10 @@ import React from 'react';
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();
});
*/

@ -0,0 +1,65 @@
import {Dispatch, useMemo, useReducer} from "react";
import {appStateReducer} from "../reducers/AppStateReducer";
import {AppState} from "../state/AppState";
import {ServerConnectionState} from "../state/NetworkState";
import {sizeFromLinesAndCells} from "../../../common/src/state/Coordinates";
import {AppAction} from "../../../common/src/actions/AppAction";
import {USER_ACTIVE_COLOR} from "../../../common/src/actions/UserAction";
import HexColorPicker from "./HexColorPicker";
import HexMapRenderer from "./HexMapRenderer";
import {DispatchContext} from "./context/DispatchContext";
import "./App.css";
import {WebsocketReactAdapter} from "./WebsocketReactAdapter";
function App() {
const defaultState: AppState = {
localState: null,
network: {
serverState: null,
connectionState: ServerConnectionState.OFFLINE,
specialMessage: null,
nextID: 0,
sentActions: [],
pendingActions: [],
goodbyeCode: 1000,
goodbyeReason: "",
autoReconnectAt: null,
reconnectAttempts: null
},
};
const [state, dispatch]: [AppState, Dispatch<AppAction>] = useReducer(appStateReducer, defaultState, undefined);
const {user, map} = state.localState || {user: null, map: null}
const offsets = useMemo(() => (!!map ? {
top: 10,
left: 10,
size: 50,
layout: map.layout
} : null), [map])
const mapElement = !!offsets && !!map ? <HexMapRenderer map={map} offsets={offsets} /> : null;
const {width, height} = useMemo(() => !!offsets && !!map ? sizeFromLinesAndCells({
bottomMargin: 10, cells: map.cellsPerLine, lines: map.lines, offsets: offsets, rightMargin: 10,
}) : {width: 1, height: 1}, [map, offsets]);
const colorPickerElement = !!user ? <HexColorPicker color={user?.activeColor} onChangeComplete={(colorResult) => dispatch({
type: USER_ACTIVE_COLOR,
color: colorResult.hex
})} /> : null
return (
<div className="App">
<DispatchContext.Provider value={dispatch}>
<WebsocketReactAdapter url={"wss://hexmap.deliciousreya.net/map"} state={state.network.connectionState} specialMessage={state.network.specialMessage} pendingMessages={state.network.pendingActions} nextID={state.network.nextID} />
<div className={"scrollBox"}>
<div className={"centerBox"}>
<svg className={"map"} width={width} height={height} viewBox={`0 0 ${width} ${height}`} onContextMenu={(e) => e.preventDefault()}>
{mapElement}
</svg>
</div>
</div>
{colorPickerElement}
</DispatchContext.Provider>
</div>
);
}
export default App;

@ -0,0 +1,124 @@
/** Translates between ws messages and Commands. */
import {ClientCommand} from "../../../common/src/actions/ClientAction";
import {
SERVER_GOODBYE,
SERVER_MALFORMED,
SERVER_SOCKET_STARTUP,
ServerCommand,
ServerGoodbyeAction,
ServerMalformedAction,
ServerSocketStartupAction,
SocketState
} from "../../../common/src/actions/ServerAction";
import {clientToPb} from "../../../common/src/pbconv/ClientToPb";
import {ClientCommandPB} from "../../../common/src/proto/client";
import {Reader} from "protobufjs";
import {ServerCommandPB} from "../../../common/src/proto/server";
import {serverFromPb} from "../../../common/src/pbconv/ServerFromPb";
export class DOMWebsocketTranslator {
readonly url: string
readonly protocols: readonly string[]
readonly onStartup: (startup: ServerSocketStartupAction) => void
readonly onMessage: (command: ServerCommand) => void
readonly onError: (error: ServerMalformedAction) => void
readonly onGoodbye: (goodbye: ServerGoodbyeAction) => void
private socket: WebSocket|null
constructor({
url,
protocols,
onStartup,
onMessage,
onError,
onGoodbye,
}: {
url: string,
protocols: readonly string[],
onStartup: (startup: ServerSocketStartupAction) => void,
onMessage: (command: ServerCommand) => void,
onError: (error: ServerMalformedAction) => void,
onGoodbye: (goodbye: ServerGoodbyeAction) => void,
}) {
this.url = url
this.protocols = protocols.slice()
this.onStartup = onStartup
this.onMessage = onMessage
this.onError = onError
this.onGoodbye = onGoodbye
this.socket = null
}
connect() {
console.log("entering connect()", this)
if (this.socket !== null) {
throw Error("Already running")
}
this.socket = new WebSocket(this.url, this.protocols.slice())
this.socket.binaryType = "arraybuffer"
this.socket.addEventListener("open", () => this.handleOpen())
this.socket.addEventListener("message", (m) => this.handleMessage(m))
this.socket.addEventListener("close", (c) => this.handleClose(c))
this.socket.addEventListener("error", () => this.handleError())
this.onStartup({
type: SERVER_SOCKET_STARTUP,
state: SocketState.CONNECTING,
})
}
send(message: ClientCommand) {
this.socket?.send(ClientCommandPB.encode(clientToPb(message)).finish())
}
close(code: number, reason: string) {
if (this.socket === null || this.socket.readyState !== WebSocket.OPEN) {
return
}
this.socket?.close(code, reason)
}
private handleOpen() {
this.onStartup({
type: SERVER_SOCKET_STARTUP,
state: SocketState.OPEN,
})
}
private handleMessage(e: MessageEvent) {
const data: ArrayBuffer = e.data
const reader: Reader = Reader.create(new Uint8Array(data))
const proto = ServerCommandPB.decode(reader)
let decoded;
try {
decoded = serverFromPb((proto))
} catch (e) {
this.onError({
type: SERVER_MALFORMED,
error: e,
})
return
}
this.onMessage(decoded)
}
private handleError() {
this.onError({
type: SERVER_MALFORMED,
error: null
})
}
private handleClose(e: CloseEvent) {
this.onGoodbye({
type: SERVER_GOODBYE,
code: e.code,
reason: e.reason,
currentTime: new Date(),
})
this.clearSocket()
}
private clearSocket() {
this.socket = null
}
}

@ -0,0 +1,18 @@
import React from 'react';
import ReactDOM from 'react-dom';
import './ui/EntryPoint.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
export function EntryPoint() {
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();
}

@ -4,8 +4,9 @@ import {
renderCoordinatesToPolygonPoints,
RenderOffsets,
storageCoordinatesToRenderCoordinates
} from "../state/Coordinates";
import {HexagonOrientation, LineParity} from "../state/HexMap";
} from "../../../common/src/state/Coordinates";
import {HexagonOrientation, LineParity} from "../../../common/src/state/HexMap";
import {normalizeColor} from "../../../common/src/util/ColorUtils";
function HexSwatch({color, index, offsets, classNames, onClick}: {color: string, index: number, offsets: RenderOffsets, classNames?: readonly string[], onClick: () => void}): ReactElement {
const renderCoordinates = useMemo(() => storageCoordinatesToRenderCoordinates({line: index, cell: 0}, offsets), [index, offsets]);
@ -19,7 +20,7 @@ function HexSwatch({color, index, offsets, classNames, onClick}: {color: string,
}
const ACTIVE_OFFSETS: RenderOffsets = {
displayMode: {
layout: {
orientation: HexagonOrientation.POINTY_TOP,
indentedLines: LineParity.ODD
},
@ -29,7 +30,7 @@ const ACTIVE_OFFSETS: RenderOffsets = {
}
const SWATCH_OFFSETS: RenderOffsets = {
displayMode: {
layout: {
orientation: HexagonOrientation.FLAT_TOP,
indentedLines: LineParity.EVEN
},
@ -49,20 +50,6 @@ const COLORS: readonly string[] = [
"#AAAAAAFF", "#FFFFFFFF",
]
function normalizeColor(hex: string): string {
hex = hex.toUpperCase()
if (hex.length === 4) {
return `#${hex[1]}${hex[1]}${hex[2]}${hex[2]}${hex[3]}${hex[3]}FF`
}
if (hex.length === 5) {
return `#${hex[1]}${hex[1]}${hex[2]}${hex[2]}${hex[3]}${hex[3]}${hex[4]}${hex[4]}`
}
if (hex.length === 7) {
return `${hex}FF`
}
return hex
}
function HexColorPicker({ hex, onChange }: InjectedColorProps): ReactElement {
const selected = COLORS.indexOf(normalizeColor(hex || "#INVALID"))
const swatches = COLORS.map((color, index) =>

@ -1,7 +1,7 @@
import React, {ReactElement} from "react";
import {getCell, HexMap} from "../state/HexMap";
import {getCell, HexMap} from "../../../common/src/state/HexMap";
import {HexTileRenderer} from "./HexTileRenderer";
import {RenderOffsets, storageCoordinatesToKey} from "../state/Coordinates";
import {RenderOffsets, storageCoordinatesToKey} from "../../../common/src/state/Coordinates";
function HexMapRenderer({map, offsets}: {map: HexMap, offsets: RenderOffsets}) {
const tiles: ReactElement[] = [];

@ -1,12 +1,12 @@
import {MouseEvent as ReactMouseEvent, ReactElement, useContext, useMemo} from "react";
import {HexCell} from "../state/HexMap";
import {HexCell} from "../../../common/src/state/HexMap";
import {
renderCoordinatesToPolygonPoints, RenderOffsets,
StorageCoordinates,
storageCoordinatesToRenderCoordinates
} from "../state/Coordinates";
} from "../../../common/src/state/Coordinates";
import {DispatchContext} from "./context/DispatchContext";
import {TILE_PAINT, TILE_REMOVE} from "../actions/TileAction";
import {TILE_PAINT, TILE_REMOVE} from "../../../common/src/actions/TileAction";
export function HexTileRenderer({classNames, coords, cell, offsets}: {classNames?: readonly string[], coords: StorageCoordinates, cell: HexCell, offsets: RenderOffsets}): ReactElement {
const dispatch = useContext(DispatchContext);

@ -0,0 +1,72 @@
import {ReactElement, useContext, useEffect, useRef, useState} from "react";
import {
CLIENT_ACT,
CLIENT_REFRESH,
ClientActCommand,
ClientGoodbyeAction,
ClientHelloCommand,
ClientRefreshCommand, isClientGoodbyeCommand,
isClientHelloCommand,
isClientRefreshCommand,
SendableAction,
SentAction
} from "../../../common/src/actions/ClientAction";
import {DispatchContext} from "./context/DispatchContext";
import {DOMWebsocketTranslator} from "./DOMWebsocketTranslator";
import {ServerConnectionState} from "../state/NetworkState";
import {SERVER_SOCKET_STARTUP, SocketState} from "../../../common/src/actions/ServerAction";
export function WebsocketReactAdapter({url, protocols = ["v1.hexmap.deliciousreya.net"], state, specialMessage, pendingMessages, nextID}: {
url: string,
protocols?: readonly string[],
state: ServerConnectionState,
specialMessage: ClientHelloCommand | ClientRefreshCommand | ClientGoodbyeAction | null,
pendingMessages: readonly SendableAction[],
nextID: number
}): ReactElement {
const dispatch = useContext(DispatchContext)
if (dispatch === null) {
throw Error("What the heck?! No dispatch?! I quit!")
}
const connector = useRef(new DOMWebsocketTranslator({
url,
protocols,
onStartup: dispatch,
onMessage: dispatch,
onError: dispatch,
onGoodbye: dispatch,
}))
useEffect(() => {
connector.current.connect();
dispatch({
type: SERVER_SOCKET_STARTUP,
state: SocketState.CONNECTING,
});
}, [dispatch])
const [lastSpecialMessage, setLastSpecialMessage] = useState<ClientHelloCommand | ClientRefreshCommand | ClientGoodbyeAction | null>(null)
useEffect(() => {
if (state === ServerConnectionState.CONNECTED && pendingMessages.length > 0) {
const sentMessages: SentAction[] = pendingMessages.map((action, index) => {
return {id: index + nextID, action}
});
const sentMessage: ClientActCommand = {
type: CLIENT_ACT,
actions: sentMessages,
};
connector.current.send(sentMessage)
dispatch(sentMessage)
}
}, [nextID, dispatch, pendingMessages, state])
useEffect(() => {
if (specialMessage !== null && specialMessage !== lastSpecialMessage) {
if ((state === ServerConnectionState.AWAITING_HELLO && isClientHelloCommand(specialMessage))
|| (state === ServerConnectionState.AWAITING_REFRESH && isClientRefreshCommand(specialMessage))) {
connector.current.send(specialMessage);
} else if (state === ServerConnectionState.AWAITING_GOODBYE && isClientGoodbyeCommand(specialMessage)) {
connector.current.close(specialMessage.code, specialMessage.reason)
}
setLastSpecialMessage(specialMessage);
}
}, [specialMessage, lastSpecialMessage, setLastSpecialMessage, state])
return <div className="connectionState" onClick={() => dispatch ? dispatch({type: CLIENT_REFRESH}) : null}>{state}</div>
}

@ -1,4 +1,4 @@
import { createContext } from "react";
import {AppAction} from "../../actions/AppAction";
import {AppAction} from "../../../../common/src/actions/AppAction";
export const DispatchContext = createContext<null|((action: AppAction) => void)>(null);

@ -1,176 +0,0 @@
import {
CLIENT_ACT,
ClientAction,
ClientActAction,
isClientActAction,
SendableAction,
SentAction,
SERVER_FAILED,
SERVER_GOODBYE,
SERVER_HELLO,
SERVER_OK,
SERVER_ACT,
SERVER_SOCKET_STARTUP,
ServerAction,
SocketState
} from "../../actions/NetworkAction";
import {HexagonOrientation, HexMapRepresentation, initializeMap, LineParity} from "../../state/HexMap";
import {ReactElement, useContext, useEffect, useRef, useState} from "react";
import {DispatchContext} from "../context/DispatchContext";
import {USER_ACTIVE_COLOR} from "../../actions/UserAction";
import {CELL_COLOR} from "../../actions/CellAction";
export enum OrientationConstants {
ROWS = "ROWS",
COLUMNS = "COLUMNS",
EVEN_ROWS = "EVEN_ROWS",
EVEN_COLUMNS = "EVEN_COLUMNS"
}
export function orientationFromString(string: string): HexMapRepresentation {
const normalized = string.toUpperCase().trim()
switch (normalized) {
case OrientationConstants.ROWS:
return { orientation: HexagonOrientation.POINTY_TOP, indentedLines: LineParity.ODD }
case OrientationConstants.COLUMNS:
return { orientation: HexagonOrientation.FLAT_TOP, indentedLines: LineParity.ODD }
case OrientationConstants.EVEN_ROWS:
return { orientation: HexagonOrientation.POINTY_TOP, indentedLines: LineParity.EVEN }
case OrientationConstants.EVEN_COLUMNS:
return { orientation: HexagonOrientation.FLAT_TOP, indentedLines: LineParity.EVEN }
default:
return { orientation: HexagonOrientation.POINTY_TOP, indentedLines: LineParity.ODD }
}
}
/** Fake "connection" to a "server" that actually just goes back and forth with the console. */
export class ConsoleConnection {
public receivedMessages: ClientAction[] = []
private readonly dispatch: (action: ServerAction) => void
constructor(dispatch: (action: ServerAction) => void) {
this.dispatch = dispatch
}
receive(action: ClientAction): void {
this.receivedMessages.push(action)
if (isClientActAction(action)) {
console.log(`Received Sent action containing: ${action.actions.map((value) => `${value.id}/${value.action.type}`).join(", ")}`)
} else {
console.log(`Received: ${action.type}`)
}
}
public sendSocketConnecting(): void {
this.dispatch({
type: SERVER_SOCKET_STARTUP,
state: SocketState.CONNECTING
})
}
public sendSocketConnected(): void {
this.dispatch({
type: SERVER_SOCKET_STARTUP,
state: SocketState.OPEN
})
}
public sendHello({color = "#0000FF", displayMode = "ROWS", xid = "TotallyCoolXID", lines = 10, cells = 10}: {
color?: string,
displayMode?: string,
xid?: string,
lines?: number,
cells?: number
} = {}): void {
this.dispatch({
type: SERVER_HELLO,
version: 1,
state: {
map: initializeMap({
lines,
cellsPerLine: cells,
displayMode: orientationFromString(displayMode),
xid
}),
user: {activeColor: color}
}
})
}
public sendOK(ids: readonly number[]): void {
this.dispatch({
type: SERVER_OK,
ids
})
}
public sendFailed(ids: readonly number[], error: string = "No thanks."): void {
this.dispatch({
type: SERVER_FAILED,
ids,
error
})
}
public sendGoodbye({code = 1000, reason = "Okay, bye then!"}: { code?: number, reason?: string } = {}): void {
this.dispatch({
type: SERVER_GOODBYE,
code,
reason,
currentTime: new Date()
})
}
public sendColorChange(color: string = "#FF0000FF"): void {
this.dispatch({
type: SERVER_ACT,
actions: [{
type: USER_ACTIVE_COLOR,
color
}]
})
}
public sendColorAtTile(color: string = "#FFFF00FF", line: number = 0, cell: number = 0): void {
this.dispatch({
type: SERVER_ACT,
actions: [{
type: CELL_COLOR,
at: { line, cell },
color
}]
})
}
}
export function ConsoleConnector({specialMessage, pendingMessages, nextID}: {specialMessage: ClientAction|null, pendingMessages: readonly SendableAction[], nextID: number}): ReactElement {
const dispatch = useContext(DispatchContext)
const connector = useRef(new ConsoleConnection(dispatch || (() => null)))
const [lastSpecialMessage, setLastSpecialMessage] = useState<ClientAction|null>(null)
useEffect(() => {
// @ts-ignore
window.fakedServerConnection = connector.current
}, []);
useEffect(() => {
if (dispatch !== null) {
if (pendingMessages.length > 0) {
const sentMessages: SentAction[] = pendingMessages.map((action, index) => {
return { id: index + nextID, action }
});
const sentMessage: ClientActAction = {
type: CLIENT_ACT,
actions: sentMessages
};
connector.current.receive(sentMessage)
dispatch(sentMessage)
}
}
}, [nextID, dispatch, pendingMessages])
useEffect(() => {
if (specialMessage !== null && specialMessage !== lastSpecialMessage) {
connector.current.receive(specialMessage);
setLastSpecialMessage(specialMessage);
}
}, [specialMessage, lastSpecialMessage, setLastSpecialMessage])
return <div className="consoleConnector">Console connection active</div>
}

@ -1,26 +1,14 @@
{
"extends": "../common/tsconfig.json",
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"baseUrl": "src",
"lib": ["dom", "dom.iterable"],
"paths": {
"~client/*": ["./*"],
"~common/*": ["../../common/src/*"]
},
"jsx": "react-jsx"
},
"include": [
"src"
]
}
"include": ["src"],
"exclude": ["*.test.ts", "*.test.tsx"],
}

@ -0,0 +1,25 @@
syntax = "proto3";
import "coords.proto";
message CellSetColorPB {
fixed32 color = 1;
StorageCoordinatesPB at = 2;
}
message UserSetActiveColorPB {
fixed32 color = 1;
}
message ClientActionPB {
oneof action {
CellSetColorPB cell_set_color = 1;
UserSetActiveColorPB user_set_active_color = 2;
}
}
message ServerActionPB {
oneof action {
ClientActionPB client = 1;
}
}

@ -0,0 +1,26 @@
syntax = "proto3";
import "action.proto";
message ClientHelloPB {
uint32 version = 1;
}
message ClientRefreshPB {
}
message ClientActPB {
message IDed {
uint32 id = 1;
ClientActionPB action = 2;
}
repeated IDed actions = 1;
}
message ClientCommandPB {
oneof command {
ClientHelloPB hello = 1;
ClientRefreshPB refresh = 2;
ClientActPB act = 3;
}
}

@ -0,0 +1,6 @@
syntax = "proto3";
message StorageCoordinatesPB {
uint32 line = 1;
uint32 cell = 2;
}

@ -0,0 +1,35 @@
syntax = "proto3";
message HexCellPB {
fixed32 color = 1;
}
message HexLinePB {
repeated HexCellPB cells = 1;
}
message HexLayerPB {
repeated HexLinePB lines = 1;
}
message HexMapPB {
message Layout {
enum Orientation {
UNKNOWN_ORIENTATION = 0;
POINTY_TOP = 1;
FLAT_TOP = 2;
}
enum LineParity {
UNKNOWN_LINE = 0;
ODD = 1;
EVEN = 2;
}
Orientation orientation = 1;
LineParity indented_lines = 2;
}
bytes xid = 1;
uint32 lines = 2;
uint32 cells_per_line = 3;
Layout layout = 4;
HexLayerPB layer = 5;
}

@ -0,0 +1,36 @@
syntax = "proto3";
import "action.proto";
import "state.proto";
message ServerHelloPB {
uint32 version = 1;
SyncableStatePB state = 2;
}
message ServerRefreshPB {
SyncableStatePB state = 1;
}
message ServerOKPB {
repeated uint32 ids = 1;
}
message ServerFailedPB {
repeated uint32 ids = 1;
string error = 2;
}
message ServerActPB {
repeated ServerActionPB actions = 1;
}
message ServerCommandPB {
oneof command {
ServerHelloPB hello = 1;
ServerRefreshPB refresh = 2;
ServerOKPB ok = 3;
ServerFailedPB failed = 4;
ServerActPB act = 5;
}
}

@ -0,0 +1,9 @@
syntax = "proto3";
import "map.proto";
import "user.proto";
message SyncableStatePB {
HexMapPB map = 1;
UserStatePB user = 2;
}

@ -0,0 +1,5 @@
syntax = "proto3";
message UserStatePB {
fixed32 color = 1;
}

@ -0,0 +1,75 @@
import {BaseAction} from "./BaseAction";
import {AppAction} from "./AppAction";
import {CellColorAction, isCellColorAction} from "./CellAction";
import {isUserActiveColorAction, UserActiveColorAction} from "./UserAction";
export const CLIENT_HELLO = "CLIENT_HELLO"
/** Sent when the client connects. */
export interface ClientHelloCommand extends BaseAction {
readonly type: typeof CLIENT_HELLO
/** The protocol version the client is running on */
readonly version: number
}
export function isClientHelloCommand(action: AppAction): action is ClientHelloCommand {
return action.type === CLIENT_HELLO
}
export const CLIENT_REFRESH = "CLIENT_REFRESH"
/** Sent when the user requests a refresh. */
export interface ClientRefreshCommand extends BaseAction {
readonly type: typeof CLIENT_REFRESH
}
export function isClientRefreshCommand(action: AppAction): action is ClientRefreshCommand {
return action.type === CLIENT_REFRESH
}
export const CLIENT_PENDING = "CLIENT_PENDING"
/** Synthesized when a user action is ready to be sent to the server. */
export interface ClientPendingAction extends BaseAction {
readonly type: typeof CLIENT_PENDING
readonly pending: SendableAction
}
export function isClientPendingAction(action: AppAction): action is ClientPendingAction {
return action.type === CLIENT_PENDING
}
export interface SentAction {
readonly id: number
readonly action: SendableAction
}
export const CLIENT_ACT = "CLIENT_ACT"
/** Sent to the server when the user performs an action. */
export interface ClientActCommand extends BaseAction {
readonly type: typeof CLIENT_ACT
readonly actions: readonly SentAction[]
}
export function isClientActCommand(action: AppAction): action is ClientActCommand {
return action.type === CLIENT_ACT
}
export const CLIENT_GOODBYE = "CLIENT_GOODBYE"
/** Synthesized when the client wants to close the connection. */
export interface ClientGoodbyeAction extends BaseAction {
readonly type: typeof CLIENT_GOODBYE
readonly code: number,
readonly reason: string,
}
export function isClientGoodbyeCommand(action: AppAction): action is ClientGoodbyeAction {
return action.type === CLIENT_GOODBYE
}
export type SendableAction = CellColorAction | UserActiveColorAction
export function isSendableAction(action: AppAction): action is SendableAction {
return isCellColorAction(action) || isUserActiveColorAction(action)
}
export type ClientCommand = ClientHelloCommand | ClientRefreshCommand | ClientActCommand
export function isClientCommand(action: AppAction): action is ClientCommand {
return isClientHelloCommand(action) || isClientRefreshCommand(action) || isClientActCommand(action)
}
export type ClientAction = ClientCommand | ClientPendingAction | ClientGoodbyeAction
export function isClientAction(action: AppAction): action is ClientAction {
return isClientCommand(action) || isClientPendingAction(action) || isClientGoodbyeCommand(action)
}

@ -0,0 +1,15 @@
import {isServerAction, ServerAction} from "./ServerAction";
import {AppAction} from "./AppAction";
import {ClientAction, isClientAction} from "./ClientAction";
// Terminology: Messages are the data packets sent and received over the WebSocket connection.
// Commands are the protocol laid on top of messages.
// Actions are data objects that the client uses to communicate between parts of itself.
// All commands are both messages and actions.
// An action is a message if and only if it is a command.
// A message is an action if and only if it is a command.
export type NetworkAction = ServerAction | ClientAction;
export function isNetworkAction(action: AppAction): action is NetworkAction {
return isServerAction(action) || isClientAction(action)
}

@ -0,0 +1,121 @@
import {BaseAction} from "./BaseAction";
import {SyncedState} from "../state/SyncedState";
import {AppAction} from "./AppAction";
import {SendableAction} from "./ClientAction";
export const SERVER_HELLO = "SERVER_HELLO"
/** Sent in response to the client's ClientHelloAction when the client has been accepted. */
export interface ServerHelloCommand extends BaseAction {
readonly type: typeof SERVER_HELLO
/** The protocol version the server is running on. */
readonly version: number
/** The current state of the server as of when the client connected. */
readonly state: SyncedState
}
export function isServerHelloCommand(action: AppAction): action is ServerHelloCommand {
return action.type === SERVER_HELLO
}
export const SERVER_GOODBYE = "SERVER_GOODBYE"
/** Synthesized out of the close message when the server closes the connection. */
export interface ServerGoodbyeAction extends BaseAction {
readonly type: typeof SERVER_GOODBYE
/** The exit code sent with the close message by the server. */
readonly code: number
/** The text of the server's goodbye message. */
readonly reason: string
/** The current time when this close message was received. */
readonly currentTime: Date
}
export function isServerGoodbyeAction(action: AppAction): action is ServerGoodbyeAction {
return action.type === SERVER_GOODBYE
}
export const SERVER_REFRESH = "SERVER_REFRESH"
/** Sent in response to the client's ClientRefreshCommand. */
export interface ServerRefreshCommand extends BaseAction {
readonly type: typeof SERVER_REFRESH
/** The current state of the server as of when the client's refresh request was processed. */
readonly state: SyncedState
}
export function isServerRefreshCommand(action: AppAction): action is ServerRefreshCommand {
return action.type === SERVER_REFRESH
}
export const SERVER_OK = "SERVER_OK"
/** Sent in response to the client's ClientActCommand, if it succeeds and is applied to the server map. */
export interface ServerOKCommand extends BaseAction {
readonly type: typeof SERVER_OK
/**
* The IDs of the successful actions.
* These will always be sent in sequential order - the order in which the server received and applied them.
* This allows the client to apply that set of actions to its server-state copy and then refresh its local copy.
*/
readonly ids: readonly number[]
}
export function isServerOKCommand(action: AppAction): action is ServerOKCommand {
return action.type === SERVER_OK
}
export const SERVER_FAILED = "SERVER_FAILED"
/** Sent in response to the client's ClientActCommand, if it fails and has not been applied to the server map. */
export interface ServerFailedCommand extends BaseAction {
readonly type: typeof SERVER_FAILED
/** The IDs of the failed actions, all of which failed with the same error. */
readonly ids: readonly number[]
/** The error the above actions failed with. */
readonly error: string
}
export function isServerFailedCommand(action: AppAction): action is ServerFailedCommand {
return action.type === SERVER_FAILED
}
export enum SocketState {
CONNECTING = "CONNECTING",
OPEN = "OPEN",
}
export const SERVER_SOCKET_STARTUP = "SERVER_SOCKET_STARTUP"
/** Synthesized when the ws begins connecting, i.e., enters the Connecting or Open states.. */
export interface ServerSocketStartupAction extends BaseAction {
readonly type: typeof SERVER_SOCKET_STARTUP
readonly state: SocketState
}
export function isServerSocketStartupAction(action: AppAction): action is ServerSocketStartupAction {
return action.type === SERVER_SOCKET_STARTUP
}
export const SERVER_ACT = "SERVER_ACT"
/** Sent by the server when another client has performed an action. Never sent for the client's own actions. */
export interface ServerActCommand extends BaseAction {
readonly type: typeof SERVER_ACT
readonly actions: readonly SyncableAction[]
}
export function isServerActCommand(action: AppAction): action is ServerActCommand {
return action.type === SERVER_ACT
}
export const SERVER_MALFORMED = "SERVER_MALFORMED"
/** Synthesized when the client can't understand a command the server sent, or when an error event appears on the ws. */
export interface ServerMalformedAction extends BaseAction {
readonly type: typeof SERVER_MALFORMED,
readonly error: Error | null,
}
export function isServerMalformedAction(action: AppAction): action is ServerMalformedAction {
return action.type === SERVER_MALFORMED
}
export type SyncableAction = SendableAction
export type ServerCommand =
ServerHelloCommand | ServerRefreshCommand |
ServerOKCommand | ServerFailedCommand | ServerActCommand
export function isServerCommand(action: AppAction): action is ServerCommand {
return isServerHelloCommand(action) || isServerRefreshCommand(action)
|| isServerOKCommand(action) || isServerFailedCommand(action) || isServerActCommand(action)
}
export type ServerAction = ServerCommand | ServerSocketStartupAction | ServerMalformedAction | ServerGoodbyeAction
export function isServerAction(action: AppAction): action is ServerAction {
return isServerCommand(action) || isServerSocketStartupAction(action) || isServerMalformedAction(action) || isServerGoodbyeAction(action)
}

@ -0,0 +1,38 @@
import {CLIENT_ACT, CLIENT_HELLO, CLIENT_REFRESH, ClientCommand, SentAction} from "../actions/ClientAction";
import {ClientActPB_IDed, ClientCommandPB} from "../proto/client";
import {sendableActionToPB} from "./SyncableActionToPb";
export function sentActionToPb(message: SentAction): ClientActPB_IDed {
return {
id: message.id,
action: sendableActionToPB(message.action),
}
}
export function clientToPb(message: ClientCommand): ClientCommandPB {
switch (message.type) {
case CLIENT_HELLO:
return {
hello: {
version: message.version,
},
refresh: undefined,
act: undefined,
}
case CLIENT_REFRESH:
return {
refresh: {
},
hello: undefined,
act: undefined,
}
case CLIENT_ACT:
return {
act: {
actions: message.actions.map(sentActionToPb)
},
hello: undefined,
refresh: undefined,
}
}
}

@ -0,0 +1,91 @@
import {SyncableStatePB} from "../proto/state";
import {SyncedState} from "../state/SyncedState";
import {HexagonOrientation, HexCell, HexLayout, HexMap, LineParity} from "../state/HexMap";
import {UserStatePB} from "../proto/user";
import {
HexCellPB,
HexMapPB,
HexMapPB_Layout,
HexMapPB_Layout_LineParity,
HexMapPB_Layout_Orientation
} from "../proto/map";
import {UserState} from "../state/UserState";
import {unpackHexColor} from "../util/ColorUtils";
import {encode} from "base64-arraybuffer";
import {StorageCoordinatesPB} from "../proto/coords";
import {StorageCoordinates} from "../state/Coordinates";
export function storageCoordsFromPb(coords: StorageCoordinatesPB): StorageCoordinates {
return {
line: coords.line,
cell: coords.cell,
};
}
function orientationFromPb(orientation: HexMapPB_Layout_Orientation): HexagonOrientation {
switch (orientation) {
case HexMapPB_Layout_Orientation.FLAT_TOP:
return HexagonOrientation.FLAT_TOP
case HexMapPB_Layout_Orientation.POINTY_TOP:
return HexagonOrientation.POINTY_TOP
case HexMapPB_Layout_Orientation.UNKNOWN_ORIENTATION:
case HexMapPB_Layout_Orientation.UNRECOGNIZED:
throw Error("unknown orientation")
}
}
function lineParityFromPb(parity: HexMapPB_Layout_LineParity): LineParity {
switch (parity) {
case HexMapPB_Layout_LineParity.EVEN:
return LineParity.EVEN
case HexMapPB_Layout_LineParity.ODD:
return LineParity.ODD
case HexMapPB_Layout_LineParity.UNKNOWN_LINE:
case HexMapPB_Layout_LineParity.UNRECOGNIZED:
throw Error("unknown line parity")
}
}
function layoutFromPb(layout: HexMapPB_Layout): HexLayout {
return {
orientation: orientationFromPb(layout.orientation),
indentedLines: lineParityFromPb(layout.indentedLines),
}
}
function cellFromPb(cell: HexCellPB): HexCell {
return {
color: unpackHexColor(cell.color)
}
}
function mapFromPb(map: HexMapPB): HexMap {
if (!map.layout || !map.layer) {
throw Error("HexMapPB did not have layout and layer");
}
return {
xid: encode(map.xid),
lines: map.lines,
cellsPerLine: map.cellsPerLine,
layout: layoutFromPb(map.layout),
layer: map.layer.lines.map((line): HexCell[] => {
return line.cells.map(cellFromPb)
}),
};
}
function userFromPb(user: UserStatePB): UserState {
return {
activeColor: unpackHexColor(user.color)
}
}
export function stateFromPb(state: SyncableStatePB): SyncedState {
if (!state.map || !state.user) {
throw Error("SyncableStatePB did not have map and user")
}
return {
map: mapFromPb(state.map),
user: userFromPb(state.user),
}
}

@ -0,0 +1,9 @@
import {StorageCoordinates} from "../state/Coordinates";
import {StorageCoordinatesPB} from "../proto/coords";
export function storageCoordsToPb(storageCoords: StorageCoordinates): StorageCoordinatesPB {
return {
line: storageCoords.line,
cell: storageCoords.cell,
}
}

@ -0,0 +1,50 @@
import {ServerCommandPB} from "../proto/server";
import {
SERVER_ACT,
SERVER_FAILED,
SERVER_HELLO,
SERVER_OK,
SERVER_REFRESH,
ServerCommand
} from "../actions/ServerAction";
import {stateFromPb} from "./MapFromPb";
import {syncableActionFromPb} from "./SyncableActionFromPb";
export function serverFromPb(pb: ServerCommandPB): ServerCommand {
if (pb.hello) {
if (!pb.hello.state) {
throw Error("No state for Server Hello")
}
return {
type: SERVER_HELLO,
version:pb.hello.version,
state: stateFromPb(pb.hello.state),
}
} else if (pb.refresh) {
if (!pb.refresh.state) {
throw Error("No state for Server Refresh")
}
return {
type: SERVER_REFRESH,
state: stateFromPb(pb.refresh.state),
}
} else if (pb.ok) {
return {
type: SERVER_OK,
ids: pb.ok.ids,
}
} else if (pb.failed) {
return {
type: SERVER_FAILED,
ids: pb.failed.ids,
error: pb.failed.error,
}
} else if (pb.act) {
return {
type: SERVER_ACT,
actions: pb.act.actions.map(syncableActionFromPb)
}
} else {
throw Error("No actual commands set on command")
}
}

@ -0,0 +1,35 @@
import {ClientActionPB, ServerActionPB} from "../proto/action";
import {SyncableAction} from "../actions/ServerAction";
import {SendableAction} from "../actions/ClientAction";
import {unpackHexColor} from "../util/ColorUtils";
import {USER_ACTIVE_COLOR} from "../actions/UserAction";
import {CELL_COLOR} from "../actions/CellAction";
import {storageCoordsFromPb} from "./MapFromPb";
function sendableActionFromPB(action: ClientActionPB): SendableAction {
if (action.cellSetColor) {
if (!action.cellSetColor.at) {
throw Error("No location set in cellSetColor")
}
return {
type: CELL_COLOR,
at: storageCoordsFromPb(action.cellSetColor.at),
color: unpackHexColor(action.cellSetColor.color),
}
} else if (action.userSetActiveColor) {
return {
type: USER_ACTIVE_COLOR,
color: unpackHexColor(action.userSetActiveColor.color)
}
} else {
throw Error("No action set in ClientAction")
}
}
export function syncableActionFromPb(action: ServerActionPB): SyncableAction {
if (action.client) {
return sendableActionFromPB(action.client)
} else {
throw Error("No action set in ServerAction")
}
}

@ -0,0 +1,26 @@
import {ClientActionPB} from "../proto/action";
import {SendableAction} from "../actions/ClientAction";
import {packHexColor} from "../util/ColorUtils";
import {storageCoordsToPb} from "./MapToPb";
import {USER_ACTIVE_COLOR} from "../actions/UserAction";
import {CELL_COLOR} from "../actions/CellAction";
export function sendableActionToPB(action: SendableAction): ClientActionPB {
switch (action.type) {
case CELL_COLOR:
return {
cellSetColor: {
at: storageCoordsToPb(action.at),
color: packHexColor(action.color),
},
userSetActiveColor: undefined,
}
case USER_ACTIVE_COLOR:
return {
userSetActiveColor: {
color: packHexColor(action.color)
},
cellSetColor: undefined,
}
}
}

@ -15,7 +15,7 @@ export function replaceCell(oldMap: HexMap, {line, cell}: StorageCoordinates, ne
if (areCellsEquivalent(getCell(oldMap, {line, cell}), newCell)) {
return oldMap
}
const oldLines = oldMap.lineCells
const oldLines = oldMap.layer
const oldLine = oldLines[line]
const newLine = [
...oldLine.slice(0, cell),
@ -29,7 +29,7 @@ export function replaceCell(oldMap: HexMap, {line, cell}: StorageCoordinates, ne
]
return {
...oldMap,
lineCells: newLines
layer: newLines
}
}
@ -40,6 +40,4 @@ export function hexMapReducer(oldState: HexMap, action: MapAction): HexMap {
case CELL_REMOVE:
return replaceCell(oldState, action.at, null)
}
}
export type HexMapReducer = typeof hexMapReducer;
}

@ -1,10 +1,10 @@
import {SyncedState} from "../state/SyncedState";
import {SyncableAction} from "../actions/NetworkAction";
import {isMapAction, MapAction} from "../actions/MapAction";
import {hexMapReducer} from "./HexMapReducer";
import {isUserAction, UserAction} from "../actions/UserAction";
import {userReducer} from "./UserReducer";
import {exhaustivenessCheck} from "../util/TypeUtils";
import {SyncableAction} from "../actions/ServerAction";
export function syncedStateReducer(state: SyncedState, action: (MapAction|UserAction)): SyncedState {
if (isMapAction(action)) {

@ -1,22 +1,4 @@
/** Cubic (3-dimensional) coordinates for algorithms. */
import {HexagonOrientation, HexMapRepresentation, LineParity} from "./HexMap";
export interface CubicCoordinates {
/** The cubic x-coordinate. */
readonly x: number
/** The cubic y-coordinate. */
readonly y: number
/** The cubic z-coordinate. */
readonly z: number
}
/** Axial (2-dimensional cube variant) coordinates for display. */
export interface AxialCoordinates {
/** The axial x-coordinate. */
readonly q: number
/** The axial y-coordinate. */
readonly r: number
}
import {HexagonOrientation, HexLayout, LineParity} from "./HexMap";
/** Staggered (storage) coordinates for accessing cell storage. */
export interface StorageCoordinates {
@ -72,7 +54,7 @@ export interface RenderOffsets {
/** How big each hexagon should be. The "radius" from the center to any vertex. */
readonly size: number
/** The way the hex map should be displayed. Usually the same as the origin map. */
readonly displayMode: HexMapRepresentation
readonly layout: HexLayout
}
export interface RenderSize {
@ -84,7 +66,7 @@ export interface RenderSize {
const POINTY_AXIS_FACTOR = 2;
const FLAT_AXIS_FACTOR = Math.sqrt(3);
export function storageCoordinatesToRenderCoordinates({line, cell}: StorageCoordinates, renderOffsets: RenderOffsets): RenderCoordinates {
const {orientation, indentedLines} = renderOffsets.displayMode;
const {orientation, indentedLines} = renderOffsets.layout;
const flatLength = renderOffsets.size * FLAT_AXIS_FACTOR;
const pointyLength = renderOffsets.size * POINTY_AXIS_FACTOR;
@ -123,7 +105,7 @@ export function sizeFromLinesAndCells({offsets, lines, cells, rightMargin = 0, b
const {
top: topMargin,
left: leftMargin,
displayMode: {
layout: {
orientation,
indentedLines
}
@ -136,12 +118,12 @@ export function sizeFromLinesAndCells({offsets, lines, cells, rightMargin = 0, b
const hasIndents = lines > 1 || indentedLines === LineParity.EVEN
// Every line will be 3/4 of a cell length apart in the pointy direction;
// Every cell will be 3/4 of a cell length apart in the pointy direction;
// however, the last line is still one full pointy cell long.
const pointyLength = pointyMargins + ((cells - 1) * pointyCellLength * 3 / 4) + pointyCellLength;
// Every cell will be one full cell length apart in the flat direction;
const pointyLength = pointyMargins + ((lines - 1) * pointyCellLength * 3 / 4) + pointyCellLength;
// Every line will be one full cell length apart in the flat direction;
// however, if there are indents, another half cell is needed to accommodate them.
const flatLength = flatMargins + lines * flatCellLength + (hasIndents ? flatCellLength / 2 : 0);
const flatLength = flatMargins + cells * flatCellLength + (hasIndents ? flatCellLength / 2 : 0);
return orientation === HexagonOrientation.FLAT_TOP ? { width: pointyLength, height: flatLength } : { width: flatLength, height: pointyLength }
}

@ -36,7 +36,7 @@ export enum LineParity {
}
/** The type of map this map is. */
export interface HexMapRepresentation {
export interface HexLayout {
readonly orientation: HexagonOrientation
readonly indentedLines: LineParity
}
@ -44,7 +44,7 @@ export interface HexMapRepresentation {
/** Data corresponding to an entire hex map. */
export interface HexMap {
/** The way the map is displayed, which also affects how coordinates are calculated. */
readonly displayMode: HexMapRepresentation
readonly layout: HexLayout
/**
* The number of lines on the map.
* In ROWS and EVEN_ROWS mode, this is the height of the map.
@ -63,7 +63,7 @@ export interface HexMap {
* In COLUMNS and EVEN_COLUMNS mode, lines represent columns.
* In ROWS and EVEN_ROWS mode, lines represent rows.
*/
readonly lineCells: readonly HexLine[]
readonly layer: readonly HexLine[]
/**
* A unique identifier in https://github.com/rs/xid format for this map. Lets the client know when it is connecting
* to a different map with the same name as this one, and its old map has been destroyed.
@ -71,20 +71,20 @@ export interface HexMap {
readonly xid: string
}
export function initializeMap({lines, cellsPerLine, displayMode, xid}: {lines: number, cellsPerLine: number, displayMode: HexMapRepresentation, xid: string}): HexMap {
const lineCells: HexLine[] = [];
export function initializeMap({lines, cellsPerLine, layout, xid}: {lines: number, cellsPerLine: number, layout: HexLayout, xid: string}): HexMap {
const layer: HexLine[] = [];
const emptyLine: HexCell[] = [];
for (let cell = 0; cell < cellsPerLine; cell += 1) {
emptyLine.push(EMPTY_CELL)
}
for (let line = 0; line < lines; line += 1) {
lineCells.push(emptyLine)
layer.push(emptyLine)
}
return {
lines,
cellsPerLine: cellsPerLine,
displayMode,
lineCells,
cellsPerLine,
layout,
layer,
xid
}
}
@ -102,5 +102,5 @@ export function getCell(map: HexMap, {line, cell}: StorageCoordinates): HexCell|
if (!isValidCoordinate(map, {line, cell})) {
return null
}
return map.lineCells[line][cell]
return map.layer[line][cell]
}

@ -1,7 +1,3 @@
export function arrayShallowEqual<T>(left: readonly T[], right: readonly T[]): boolean {
return left.length === right.length && arrayShallowStartsWith(left, right)
}
export function arrayShallowStartsWith<T>(target: readonly T[], prefix: readonly T[]): boolean {
return target.length >= prefix.length && prefix.every((value, index) => target[index] === value)
}

@ -0,0 +1,27 @@
export function normalizeColor(hex: string): string {
hex = hex.toUpperCase()
if (hex.length === 4) {
return `#${hex[1]}${hex[1]}${hex[2]}${hex[2]}${hex[3]}${hex[3]}FF`
}
if (hex.length === 5) {
return `#${hex[1]}${hex[1]}${hex[2]}${hex[2]}${hex[3]}${hex[3]}${hex[4]}${hex[4]}`
}
if (hex.length === 7) {
return `${hex}FF`
}
return hex
}
export function packHexColor(color: string): number {
return parseInt(normalizeColor(color).substring(1), 16)
}
export function unpackHexColor(color: number): string {
if (color > 2**32 || Math.floor(color) !== color) {
throw Error("Packed color was too large or not an integer")
}
// this is 1 << 32, so it will produce a single hex digit above the others, even if the
// R/G/B is 0 - which we can then trim off and replace with our #
// a neat insight from https://stackoverflow.com/a/13397771
return "#" + ((color + 0x100000000).toString(16).substring(1))
}

@ -0,0 +1,31 @@
{
"compilerOptions": {
"target": "es5",
"lib": [
"esnext"
],
"baseUrl": "src",
"paths": {
"~common/*": ["./*"]
},
"downlevelIteration": true,
"allowJs": false,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
},
"include": [
"src"
],
"exclude": [
"*.test.ts"
]
}

@ -1,45 +0,0 @@
package action
import (
"git.reya.zone/reya/hexmap/server/state"
"go.uber.org/zap/zapcore"
)
const (
CellColorType SyncableType = "CELL_COLOR"
)
// CellColor is the action sent when a cell of the map has been colored a different color.
type CellColor struct {
// At is the location of the cell in storage coordinates.
At state.StorageCoordinates `json:"at"`
// Color is the color the cell has been changed to.
Color state.HexColor `json:"color"`
}
func (c CellColor) MarshalLogObject(encoder zapcore.ObjectEncoder) error {
encoder.AddString("type", string(CellColorType))
err := encoder.AddObject("at", c.At)
encoder.AddString("color", c.Color.String())
return err
}
func (c CellColor) Type() SyncableType {
return CellColorType
}
// Apply sets the target cell's color, or returns ErrNoOp if it can't.
func (c CellColor) Apply(s *state.Synced) error {
if c.Color.A < 0xF {
return ErrNoTransparentColors
}
cell, err := s.Map.LineCells.GetCellAt(c.At)
if err != nil {
return err
}
if cell.Color == c.Color {
return ErrNoOp
}
cell.Color = c.Color
return nil
}

@ -1,43 +0,0 @@
package action
import (
"errors"
"git.reya.zone/reya/hexmap/server/state"
"go.uber.org/zap/zapcore"
)
var (
// ErrNoOp is returned when an action has no effect.
ErrNoOp = errors.New("action's effects were already applied, or it's an empty action")
// ErrNoTransparentColors is returned when a user tries to set their active color or a cell color to transparent.
// Transparent here is defined as having an alpha component of less than 15 (0xF).
ErrNoTransparentColors = errors.New("transparent colors not allowed")
)
type SyncableType string
// Syncable is the interface for actions that can be shared between clients.
type Syncable interface {
zapcore.ObjectMarshaler
// Type gives the Javascript type that is sent over the wire.
Type() SyncableType
// Apply causes the action's effects to be applied to s, mutating it in place.
// All syncable.Actions must conform to the standard that if an action can't be correctly applied, or if it would
// have no effect, it returns an error without changing s.
// If an action can be correctly applied but would have no effect, it should return ErrNoOp.
// If an action is correctly applied and has an effect, it should return nil.
Apply(s *state.Synced) error
}
type SyncableSlice []Syncable
func (s SyncableSlice) MarshalLogArray(encoder zapcore.ArrayEncoder) error {
var finalErr error = nil
for _, a := range s {
err := encoder.AppendObject(a)
if err != nil && finalErr == nil {
finalErr = err
}
}
return finalErr
}

@ -1,37 +0,0 @@
package action
import (
"git.reya.zone/reya/hexmap/server/state"
"go.uber.org/zap/zapcore"
)
const (
UserActiveColorType = "USER_ACTIVE_COLOR"
)
// UserActiveColor is the action sent when the user's current color, the one being painted with, changes.
type UserActiveColor struct {
// Color is the color that is now active.
Color state.HexColor `json:"color"`
}
func (c UserActiveColor) Type() SyncableType {
return UserActiveColorType
}
func (c UserActiveColor) MarshalLogObject(encoder zapcore.ObjectEncoder) error {
encoder.AddString("color", c.Color.String())
return nil
}
// Apply sets the user's active color, or returns ErrNoOp if it can't.
func (c UserActiveColor) Apply(s *state.Synced) error {
if c.Color.A < 0xF {
return ErrNoTransparentColors
}
if s.User.ActiveColor == c.Color {
return ErrNoOp
}
s.User.ActiveColor = c.Color
return nil
}

@ -1,9 +0,0 @@
module git.reya.zone/reya/hexmap/server
go 1.16
require (
github.com/gorilla/websocket v1.4.2
github.com/rs/xid v1.3.0
go.uber.org/zap v1.18.1
)

@ -1,49 +0,0 @@
github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLju8=
github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc=
github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rs/xid v1.3.0 h1:6NjYksEUlhurdVehpc7S7dk6DAmcKv8V9gG0FsVN2U4=
github.com/rs/xid v1.3.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
go.uber.org/atomic v1.7.0 h1:ADUqmZGgLDDfbSL9ZmPxKTybcoEYHgpYfELNoN+7hsw=
go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
go.uber.org/goleak v1.1.10 h1:z+mqJhf6ss6BSfSM671tgKyZBFPTTJM+HLxnhPC3wu0=
go.uber.org/goleak v1.1.10/go.mod h1:8a7PlsEVH3e/a/GLqe5IIrQx6GzcnRmZEufDUTk4A7A=
go.uber.org/multierr v1.6.0 h1:y6IPFStTAIT5Ytl7/XYmHvzXQ7S3g/IeZW9hyZ5thw4=
go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU=
go.uber.org/zap v1.18.1 h1:CSUJ2mjFszzEWt4CdKISEuChVIXGBn3lAPwkRGyVrc4=
go.uber.org/zap v1.18.1/go.mod h1:xg/QME4nWcxGxrpdeYfq7UvYrLh66cuVKdrbD1XF/NI=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/lint v0.0.0-20190930215403-16217165b5de h1:5hukYrvBGR8/eNkX5mdUezrA6JiaEZDtJb9Ei+1LlBs=
golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20191108193012-7d206e10da11 h1:Yq9t9jnGoR+dBuitxdo9l6Q7xh/zOyNnYUtDKaQ3x0E=
golang.org/x/tools v0.0.0-20191108193012-7d206e10da11/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

@ -1 +0,0 @@
package persistence

@ -1,273 +0,0 @@
package room
import (
"git.reya.zone/reya/hexmap/server/action"
"git.reya.zone/reya/hexmap/server/state"
"github.com/rs/xid"
"go.uber.org/zap"
)
// act is the meat and potatoes of the room - it's responsible for actually running the room.
// It will gracefully remove all clients before shutting down.
func (r *room) act() {
defer r.gracefulShutdown()
r.logger.Info("Room starting up, listening for incoming actions")
for {
raw := <-r.incomingChannel
client := raw.ClientID()
msgLogger := r.logger.With(zap.Stringer("client", client))
msgLogger.Debug("Message received, handling", zap.Object("message", raw))
switch msg := raw.(type) {
case JoinRequest:
r.addClient(msg.id, msg.returnChannel, msg.broadcast, msg.privateChannel)
r.acknowledgeJoin(msg.id, msg.wantCurrentState)
case RefreshRequest:
r.sendRefresh(msg.id)
case ApplyRequest:
msgLogger.Debug("Received action to apply from client", zap.Int("actionId", msg.action.ID))
result := r.applyAction(msg.action.Action)
if result != nil {
r.broadcastAction(client, msg.action.ID, msg.action.Action)
}
r.acknowledgeAction(client, msg.action.ID, result)
case LeaveRequest:
// So long, then. We can close immediately here; they promised not to send any more messages after this
// unless we were shutting down, which we're not.
r.acknowledgeLeave(client)
r.closeClient(client)
case StopRequest:
// As requested, we shut down. Our deferred gracefulShutdown will catch us as we fall.
msgLogger.Info("Received StopRequest from client, shutting down")
return
case ShutdownResponse:
// Uh... thank... you. I'm not... Never mind. I guess this means you're leaving?
msgLogger.Error("Received unexpected ShutdownResponse from client while not shutting down")
r.closeClient(client)
default:
msgLogger.Warn("Ignoring unhandled message", zap.Object("message", msg))
}
msgLogger.Debug("Message handled, resuming listening")
}
}
// addClient records a client's presence in the client map.
func (r *room) addClient(id xid.ID, returnChannel chan<- Message, broadcast bool, privateChannel bool) {
logger := r.logger.With(zap.Stringer("client", id))
logger.Debug("Adding client")
if client, ok := r.clients[id]; ok {
if client.outgoingChannel == returnChannel {
if broadcast == client.broadcast && privateChannel == client.privateChannel {
logger.Warn("Already have client when adding client")
} else {
logger.Error("Already have client but with different settings when adding client")
}
} else {
logger.Error("Already have a different client with the same id when adding client")
}
return
}
r.clients[id] = internalClient{
id: id,
outgoingChannel: returnChannel,
broadcast: broadcast,
privateChannel: privateChannel,
}
}
// stateCopy creates and returns a fresh copy of the current state.
// This avoids concurrent modification of the state while clients are reading it.
func (r *room) stateCopy() *state.Synced {
s := r.currentState.Copy()
return &s
}
// acknowledgeJoin composes and sends a JoinResponse to the given client.
func (r *room) acknowledgeJoin(id xid.ID, includeState bool) {
logger := r.logger.With(zap.Stringer("client", id))
client, ok := r.clients[id]
if !ok {
logger.Error("No such client when acknowledging join")
return
}
var s *state.Synced = nil
if includeState {
logger.Debug("Preparing state copy for client")
s = r.stateCopy()
}
logger.Debug("Sending JoinResponse to client")
client.outgoingChannel <- JoinResponse{
id: r.id,
currentState: s,
}
}
// sendRefresh composes and sends a RefreshResponse to the given client.
func (r *room) sendRefresh(id xid.ID) {
logger := r.logger.With(zap.Stringer("client", id))
client, ok := r.clients[id]
if !ok {
logger.Error("No such client when sending refresh")
return
}
var s *state.Synced = nil
logger.Debug("Preparing state copy for client")
s = r.stateCopy()
logger.Debug("Sending RefreshResponse to client")
client.outgoingChannel <- RefreshResponse{
id: r.id,
currentState: s,
}
}
// applyAction applies an action to the state and returns the result of it.
func (r *room) applyAction(action action.Syncable) error {
r.logger.Debug("Applying action", zap.Object("action", action))
return action.Apply(&r.currentState)
}
// broadcastAction sends an action to everyone other than the original client which requested it.
func (r *room) broadcastAction(originalClientID xid.ID, originalActionID int, action action.Syncable) {
logger := r.logger.With(zap.Stringer("originalClient", originalClientID), zap.Int("actionID", originalActionID), zap.Object("action", action))
broadcast := ActionBroadcast{
id: r.id,
originalClientID: originalClientID,
originalActionID: originalActionID,
action: action,
}
logger.Debug("Broadcasting action to all clients")
for id, client := range r.clients {
if id.Compare(originalClientID) != 0 {
logger.Debug("Sending ActionBroadcast to client", zap.Stringer("client", id))
client.outgoingChannel <- broadcast
}
}
}
// acknowledgeAction sends a response to the original client which requested an action.
func (r *room) acknowledgeAction(id xid.ID, actionID int, error error) {
logger := r.logger.With(zap.Stringer("id", id), zap.Int("actionId", actionID), zap.Error(error))
logger.Debug("Responding to client with the status of its action")
client, ok := r.clients[id]
if !ok {
logger.Error("No such client when acknowledging action")
return
}
logger.Debug("Sending ApplyResponse to client")
client.outgoingChannel <- ApplyResponse{
id: id,
actionID: actionID,
result: error,
}
}
// acknowledgeLeave causes the room to signal to the client that it has received and acknowledged the client's LeaveRequest,
// and will not send any further messages.
func (r *room) acknowledgeLeave(id xid.ID) {
logger := r.logger.With(zap.Stringer("client", id))
logger.Debug("Acknowledging client's leave request")
client, ok := r.clients[id]
if !ok {
logger.Error("No such client when acknowledging leave request")
return
}
logger.Debug("Sending LeaveResponse to client")
client.outgoingChannel <- LeaveResponse{id: r.id}
}
// closeClient causes the room to remove the client with the given id from its clients.
// This should only be used after a shutdown handshake between this client and the room has taken place.
func (r *room) closeClient(id xid.ID) {
logger := r.logger.With(zap.Stringer("client", id))
logger.Debug("Closing client")
client, ok := r.clients[id]
if !ok {
logger.Error("Attempted to close a client that didn't exist")
return
}
if client.privateChannel {
logger.Debug("Closing outgoingChannel, as client has a privateChannel")
close(client.outgoingChannel)
}
delete(r.clients, id)
}
// gracefulShutdown causes the room to shut down cleanly, making sure that all clients have been removed.
func (r *room) gracefulShutdown() {
defer r.finalShutdown()
if len(r.clients) == 0 {
// Nothing to do, we've already won.
r.logger.Debug("No remaining clients, so just shutting down")
return
}
r.requestShutdown()
for len(r.clients) > 0 {
raw := <-r.incomingChannel
client := raw.ClientID()
msgLogger := r.logger.With(zap.Stringer("client", client))
msgLogger.Debug("Post-shutdown message received, handling", zap.Object("message", raw))
switch msg := raw.(type) {
case JoinRequest:
// Don't you hate it when someone comes to the desk right as you're getting ready to pack up?
// Can't ignore them - they have our channel, and they might be sending things to it. We have to add them
// and then immediately send them a ShutdownRequest and wait for them to answer it.
msgLogger.Debug("Received join request from client while shutting down")
r.addClient(msg.id, msg.returnChannel, msg.broadcast, msg.privateChannel)
r.requestShutdownFrom(client)
case RefreshRequest:
// Ugh, seriously, now? Fine. You can have this - you might be our friend the persistence actor.
r.sendRefresh(client)
case LeaveRequest:
// We sent them a shutdown already, so unfortunately, we can't close them immediately. We have to wait for
// them to tell us they've heard that we're shutting down.
msgLogger.Debug("Received leave request from client while shutting down")
r.acknowledgeLeave(client)
case StopRequest:
// Yes. We're doing that. Check your inbox, I already sent you the shutdown.
msgLogger.Debug("Received stop request from client while shutting down")
case ShutdownResponse:
// The only way we would be getting one of these is if the client knows it doesn't have to send us anything
// else. Therefore, we can remove them now.
// Similarly, we know that they'll receive the LeaveResponse they need and shut down.
// Like us, even if it sent a LeaveRequest before realizing we were shutting down, it would have gotten our
// ShutdownRequest and sent this before it could read the LeaveResponse, but it will wait for the
// LeaveResponse regardless.
msgLogger.Debug("Received shutdown confirmation from client")
r.closeClient(client)
default:
msgLogger.Debug("Ignoring irrelevant message from client while shutting down", zap.Object("message", raw))
}
msgLogger.Debug("Message handled, resuming listening and waiting to be safe to shut down", zap.Int("clientsLeft", len(r.clients)))
}
r.logger.Debug("All clients have acknowledged the ShutdownRequest, now shutting down")
}
// requestShutdown produces a ShutdownRequest and sends it to all clients to indicate that the room is shutting down.
func (r *room) requestShutdown() {
r.logger.Debug("Alerting clients that shutdown is in progress", zap.Int("clientsLeft", len(r.clients)))
for id := range r.clients {
r.requestShutdownFrom(id)
}
}
// requestShutdownFrom produces a ShutdownRequest and sends it to the client with id to indicate that the room is
// shutting down.
func (r *room) requestShutdownFrom(id xid.ID) {
clientField := zap.Stringer("client", id)
r.logger.Debug("Alerting client that shutdown is in progress", clientField)
shutdown := ShutdownRequest{
id: r.id,
}
client, ok := r.clients[id]
if !ok {
r.logger.Error("No such client when requesting shutdown from client", clientField)
}
client.outgoingChannel <- shutdown
}
// finalShutdown causes the room to do any final cleanup not involving its clients before stopping.
// Use gracefulShutdown instead, which calls this once it's safe to do so.
func (r *room) finalShutdown() {
r.logger.Debug("Closing incoming channel")
close(r.incomingChannel)
r.logger.Info("Shut down")
}

@ -1,165 +0,0 @@
package room
import (
"github.com/rs/xid"
"go.uber.org/zap"
)
// internalClient is used by the room itself to track information about a client.
type internalClient struct {
// id is the id that the client identifies itself with in all clientMessage instances it sends.
id xid.ID
// outgoingChannel is a channel that the room can send messages to the client on.
outgoingChannel chan<- Message
// privateChannel is true iff the room can close the outgoingChannel when the client and room have completed their
// close handshake.
privateChannel bool
// broadcast is true iff the client requested to be included on broadcasts on creation.
broadcast bool
}
type NewClientOptions struct {
// IncomingChannel is the channel to use as the room's channel to send messages to - the new Client's IncomingChannel.
// If this is non-nil, the room will not automatically close the IncomingChannel after a shutdown is negotiated.
// If this is nil, a new channel will be allocated on join and closed on shutdown.
IncomingChannel chan Message
// If AcceptBroadcasts is true, the room will send all broadcasts originating from other clients to this client.
AcceptBroadcasts bool
// If RequestStartingState is true, the room will send a copy of the current state as of when the JoinRequest was
// received in the JoinResponse that will be the first message the Client receives.
RequestStartingState bool
// If sets,
Logger *zap.Logger
}
// Client is the structure used by clients external to the Room package to communicate with the Room.
// It is not expected to be parallel-safe; to run it in parallel, use the NewClient method and send the new client to
// the new goroutine.
type Client struct {
// id is the ClientID used by the client for all communications.
id xid.ID
// roomId is the unique ID of the room (not its map).
roomId xid.ID
// incomingChannel is the channel that this client receives messages on.
incomingChannel <-chan Message
// outgoingChannel is the channel that this client sends messages on.
// Becomes nil if the client has been completely shut down.
outgoingChannel chan<- ClientMessage
// Once Leave or AcknowledgeShutdown have been triggered, this flag is set, preventing use of other messages.
shuttingDown bool
}
// ID is the ID used by this client to identify itself to the Room.
func (c *Client) ID() xid.ID {
return c.id
}
// RoomID is the ID used by the room to differentiate itself from other rooms.
// It is not the map's internal ID.
func (c *Client) RoomID() xid.ID {
return c.id
}
// IncomingChannel is the channel the client can listen on for messages from the room.
func (c *Client) IncomingChannel() <-chan Message {
return c.incomingChannel
}
// OutgoingChannel is the channel the client can send messages to the room on.
func (c *Client) OutgoingChannel() chan<- ClientMessage {
if c.outgoingChannel == nil {
panic("Already finished shutting down; no new messages should be sent")
}
return c.outgoingChannel
}
// newClientForRoom uses the necessary parameters to create and join a Client for the given room.
func newClientForRoom(roomId xid.ID, outgoingChannel chan<- ClientMessage, opts NewClientOptions) *Client {
var privateChannel bool
var incomingChannel chan Message
if opts.IncomingChannel != nil {
incomingChannel = opts.IncomingChannel
privateChannel = false
} else {
incomingChannel = make(chan Message, 1)
privateChannel = true
}
result := Client{
id: xid.New(),
roomId: roomId,
incomingChannel: incomingChannel,
outgoingChannel: outgoingChannel,
shuttingDown: false,
}
result.outgoingChannel <- JoinRequest{
id: result.id,
returnChannel: incomingChannel,
privateChannel: privateChannel,
broadcast: opts.AcceptBroadcasts,
wantCurrentState: opts.RequestStartingState,
}
return &result
}
// NewClient creates a new client belonging to the same room as this client with a random ID.
// The new client will be automatically joined to the channel.
func (c *Client) NewClient(opts NewClientOptions) *Client {
if c.shuttingDown {
panic("Already started shutting down; no new messages should be sent")
}
return newClientForRoom(c.roomId, c.outgoingChannel, opts)
}
// The message created by Refresh causes the client to request a fresh copy of the state.
func (c *Client) Refresh() RefreshRequest {
if c.shuttingDown {
panic("Already started shutting down; no new messages should be sent")
}
return RefreshRequest{
id: c.id,
}
}
// The message created by Leave causes the local client to signal that it is shutting down.
// It is important to Leave to avoid dangling clients having messages sent to nothing.
// After sending Leave, the client must confirm that it has been removed by waiting for a LeaveResponse, accompanied by
// the closing of the Client's IncomingChannel if it was a private channel.
// No further messages should be sent after Leave except AcknowledgeShutdown if Leave and requestShutdown crossed paths in midair.
func (c *Client) Leave() LeaveRequest {
if c.shuttingDown {
panic("Already started shutting down; no new messages should be sent")
}
c.shuttingDown = true
return LeaveRequest{
id: c.id,
}
}
// The message created by Stop causes the local client to signal that it is shutting down.
// It is important to Stop when the room needs to be shut down.
// After sending Stop, the client must confirm that it has been removed by waiting for a ShutdownRequest, which should
// be handled normally.
// No further messages should be sent after Stop except AcknowledgeShutdown.
func (c *Client) Stop() StopRequest {
if c.shuttingDown {
panic("Already started shutting down; no new messages should be sent")
}
c.shuttingDown = true
return StopRequest{
id: c.id,
}
}
// AcknowledgeShutdown causes the local client to signal that it has acknowledged that the room is shutting down.
// No further messages can be sent after AcknowledgeShutdown; attempting to do so will block forever, as the
// OutgoingChannel has become nil.
func (c *Client) AcknowledgeShutdown() ShutdownResponse {
if c.outgoingChannel == nil {
panic("Already finished shutting down; no new messages should be sent")
}
c.shuttingDown = true
c.outgoingChannel = nil
return ShutdownResponse{
id: c.id,
}
}

@ -1,124 +0,0 @@
package room
import (
"git.reya.zone/reya/hexmap/server/websocket"
"github.com/rs/xid"
"go.uber.org/zap/zapcore"
)
// ClientMessage marks messages coming from clients to the room.
type ClientMessage interface {
zapcore.ObjectMarshaler
// SourceID is the id of the client sending the message.
ClientID() xid.ID
}
// JoinRequest is the message sent on the room's IncomingChannel by a new client joining the room.
type JoinRequest struct {
// id is the SourceID the client will use to identify itself in future messages.
id xid.ID
// returnChannel is a buffered channel the client is ready to receive messages from the room on.
// This becomes the Client's OutgoingChannel.
returnChannel chan<- Message
// privateChannel is true iff the room can close returnChannel after completing a shutdown handshake.
// This permits extra safety by causing channels that somehow leak into other contexts to become noticeable by
// causing panics.
privateChannel bool
// broadcast is true iff the room should send action.Syncable from other clients to this one.
broadcast bool
// wantCurrentState indicates that the client would like the room to include a copy of the current state of the room
// when it joins.
wantCurrentState bool
}
func (j JoinRequest) MarshalLogObject(encoder zapcore.ObjectEncoder) error {
encoder.AddString("type", "JoinRequest")
encoder.AddString("id", j.id.String())
encoder.AddBool("broadcast", j.broadcast)
encoder.AddBool("wantCurrentState", j.wantCurrentState)
return nil
}
func (j JoinRequest) ClientID() xid.ID {
return j.id
}
// RefreshRequest is the message sent on the room's IncomingChannel by a client which needs the current value.
type RefreshRequest struct {
id xid.ID
}
func (r RefreshRequest) MarshalLogObject(encoder zapcore.ObjectEncoder) error {
encoder.AddString("type", "RefreshRequest")
encoder.AddString("id", r.id.String())
return nil
}
func (r RefreshRequest) ClientID() xid.ID {
return r.id
}
// ApplyRequest is the message sent on the room's IncomingChannel by a client which has received an action from the
// websocket.
type ApplyRequest struct {
id xid.ID
action websocket.IDed
}
func (f ApplyRequest) MarshalLogObject(encoder zapcore.ObjectEncoder) error {
encoder.AddString("type", "ApplyRequest")
encoder.AddString("id", f.id.String())
return encoder.AddObject("action", f.action)
}
func (f ApplyRequest) ClientID() xid.ID {
return f.id
}
// LeaveRequest is the message sent on the room's IncomingChannel by a client which is shutting down.
// The client is indicating that it will send no messages except a possible ShutdownResponse, in the event that a
// LeaveRequest and a ShutdownRequest cross paths midflight.
type LeaveRequest struct {
id xid.ID
}
func (l LeaveRequest) MarshalLogObject(encoder zapcore.ObjectEncoder) error {
encoder.AddString("type", "LeaveRequest")
encoder.AddString("id", l.id.String())
return nil
}
func (l LeaveRequest) ClientID() xid.ID {
return l.id
}
// StopRequest is the message sent on the room's IncomingChannel by a client which wants to make the room shut down.
// The response to a StopRequest is a ShutdownRequest, which should be handled as normal.
type StopRequest struct {
id xid.ID
}
func (s StopRequest) MarshalLogObject(encoder zapcore.ObjectEncoder) error {
encoder.AddString("type", "StopRequest")
encoder.AddString("id", s.id.String())
return nil
}
func (s StopRequest) ClientID() xid.ID {
return s.id
}
// ShutdownResponse is the message sent on the room's IncomingChannel by a client which has accepted the room's ShutdownRequest.
type ShutdownResponse struct {
id xid.ID
}
func (s ShutdownResponse) MarshalLogObject(encoder zapcore.ObjectEncoder) error {
encoder.AddString("type", "ShutdownResponse")
encoder.AddString("id", s.id.String())
return nil
}
func (s ShutdownResponse) ClientID() xid.ID {
return s.id
}

@ -1,147 +0,0 @@
package room
import (
"git.reya.zone/reya/hexmap/server/action"
"git.reya.zone/reya/hexmap/server/state"
"github.com/rs/xid"
"go.uber.org/zap/zapcore"
)
// Message marks messages going to clients from the room.
type Message interface {
zapcore.ObjectMarshaler
// RoomID marks the ID of the room this Message originated from, in case the Client has a shared IncomingChannel.
RoomID() xid.ID
}
// JoinResponse is the message sent by the room on a new client's IncomingChannel after it joins.
type JoinResponse struct {
id xid.ID
// currentState is a pointer to a copy of the room's current state.
// If the client refused the room state in its join message, this will be a nil pointer instead.
currentState *state.Synced
}
func (j JoinResponse) MarshalLogObject(encoder zapcore.ObjectEncoder) error {
encoder.AddString("type", "JoinResponse")
encoder.AddString("id", j.id.String())
return encoder.AddObject("currentState", j.currentState)
}
func (j JoinResponse) RoomID() xid.ID {
return j.id
}
// CurrentState returns the state of the room as of when the JoinRequest was processed.
func (j JoinResponse) CurrentState() *state.Synced {
return j.currentState
}
// RefreshResponse is the message sent by the room after a client requests it, or immediately on join.
type RefreshResponse struct {
id xid.ID
// currentState is a pointer to a copy of the room's current state.
currentState *state.Synced
}
func (r RefreshResponse) MarshalLogObject(encoder zapcore.ObjectEncoder) error {
encoder.AddString("type", "JoinResponse")
encoder.AddString("id", r.id.String())
return encoder.AddObject("currentState", r.currentState)
}
func (r RefreshResponse) RoomID() xid.ID {
return r.id
}
// CurrentState returns the state of the room as of when the RefreshRequest was processed.
func (r RefreshResponse) CurrentState() *state.Synced {
return r.currentState
}
// ApplyResponse returns the result of an action to _only_ the one that sent the ApplyRequest.
type ApplyResponse struct {
id xid.ID
// actionID is the ID of the action that completed or failed.
actionID int
// result is nil if the action was completed, or an error if it failed.
result error
}
func (a ApplyResponse) MarshalLogObject(encoder zapcore.ObjectEncoder) error {
encoder.AddString("type", "ApplyResponse")
encoder.AddString("id", a.id.String())
encoder.AddInt("actionId", a.actionID)
encoder.AddBool("success", a.result == nil)
if a.result != nil {
encoder.AddString("failure", a.result.Error())
}
return nil
}
func (a ApplyResponse) RoomID() xid.ID {
return a.id
}
// Success returns true if the action succeeded, false if it failed.
func (a ApplyResponse) Success() bool {
return a.result == nil
}
// Failure returns the error if the action failed, or nil if it succeeded.
func (a ApplyResponse) Failure() error {
return a.result
}
// ActionBroadcast is sent to all clients _other_ than the one that sent the ApplyRequest when an action succeeds.
type ActionBroadcast struct {
id xid.ID
// originalClientID is the client that sent the action in the first place.
originalClientID xid.ID
// originalActionID is the ID that the client that sent the action sent.
originalActionID int
// action is the action that succeeded.
action action.Syncable
}
func (a ActionBroadcast) MarshalLogObject(encoder zapcore.ObjectEncoder) error {
encoder.AddString("type", "ActionBroadcast")
encoder.AddString("id", a.id.String())
encoder.AddString("originalClientId", a.originalClientID.String())
encoder.AddInt("originalActionId", a.originalActionID)
return encoder.AddObject("action", a.action)
}
func (a ActionBroadcast) RoomID() xid.ID {
return a.id
}
// LeaveResponse is the message sent by the room when it has accepted that a client has left, and will send it no further messages.
type LeaveResponse struct {
id xid.ID
}
func (l LeaveResponse) MarshalLogObject(encoder zapcore.ObjectEncoder) error {
encoder.AddString("type", "LeaveResponse")
encoder.AddString("id", l.id.String())
return nil
}
func (l LeaveResponse) RoomID() xid.ID {
return l.id
}
// ShutdownRequest is the message sent by the room when something causes it to shut down. It will send the client no further messages except a possible LeaveResponse.
type ShutdownRequest struct {
id xid.ID
}
func (s ShutdownRequest) MarshalLogObject(encoder zapcore.ObjectEncoder) error {
encoder.AddString("type", "ShutdownRequest")
encoder.AddString("id", s.id.String())
return nil
}
func (s ShutdownRequest) RoomID() xid.ID {
return s.id
}

@ -1,54 +0,0 @@
package room
import (
"git.reya.zone/reya/hexmap/server/state"
"github.com/rs/xid"
"go.uber.org/zap"
)
// NewOptions is the set of information used to control what a room starts with.
type NewOptions struct {
// BaseLogger is the logger that the room should attach its data to.
BaseLogger *zap.Logger
// StartingState is a state.Synced that defines the state of the room on creation.
StartingState *state.Synced
// StartingClientOptions sets the configuration of the first client to be created, the one that will be returned
// from New.
StartingClientOptions NewClientOptions
}
// room is a room as seen from within - the information needed for the room process to do its duties.
type room struct {
// id is the room's internal ID - not to be confused with the ID of the map it is serving.
id xid.ID
// incomingChannel is the channel the room uses to receive messages. The room itself owns this channel,
// so when the clients map is empty, it can be closed.
incomingChannel chan ClientMessage
// clients contains the map of active clients, each of which is known to have a reference to this room.
clients map[xid.ID]internalClient
// currentState contains the active state being used by actions right now.
currentState state.Synced
// logger is the logger that this room will use. It contains context fields for the room's important fields.
logger *zap.Logger
}
// New creates and starts up a new room, joins a new client to it and returns that client.
func New(opts NewOptions) *Client {
logger := opts.BaseLogger.Named("Room")
id := xid.New()
r := room{
id: id,
incomingChannel: make(chan ClientMessage),
clients: make(map[xid.ID]internalClient),
currentState: *opts.StartingState,
logger: logger,
}
go r.act()
return r.newClient(opts.StartingClientOptions)
}
// newClient creates a new client belonging to this room with a random ID.
// The new client will be automatically joined to the channel.
func (r *room) newClient(opts NewClientOptions) *Client {
return newClientForRoom(r.id, r.incomingChannel, opts)
}

@ -1,17 +0,0 @@
package state
import "go.uber.org/zap/zapcore"
// StorageCoordinates gives the coordinates of a cell in a form optimized for storage.
type StorageCoordinates struct {
// Line is the index from 0 to Lines - 1 of the HexLine in the HexLayer.
Line uint8 `json:"line"`
// Cell is the index from 0 to CellsPerLine - 1 of the HexCell in the HexLine.
Cell uint8 `json:"cell"`
}
func (s StorageCoordinates) MarshalLogObject(encoder zapcore.ObjectEncoder) error {
encoder.AddUint8("line", s.Line)
encoder.AddUint8("cell", s.Cell)
return nil
}

@ -1,104 +0,0 @@
package state
import "fmt"
// HexColor is an internal representation of a hexadecimal color string.
// It can take one of these formats:
// #RRGGBBAA
// #RRGGBB
// #RGBA
// #RGB
// When marshaling, it will always choose the most efficient format, but any format can be used when unmarshaling.
type HexColor struct {
// R is the red component of the color.
R uint8
// G is the green component of the color.
G uint8
// B is the blue component of the color.
B uint8
// A is the alpha component of the color.
A uint8
}
// HexColorFromString decodes a hexadecimal string into a hex color.
func HexColorFromString(text string) (HexColor, error) {
var hex HexColor
if err := (&hex).UnmarshalText([]byte(text)); err != nil {
return hex, err
}
return hex, nil
}
func (h *HexColor) UnmarshalText(text []byte) error {
var count, expected int
var short bool
var scanErr error
switch len(text) {
case 9:
// Long form with alpha: #RRGGBBAA
expected = 4
short = false
count, scanErr = fmt.Sscanf(string(text), "#%02X%02X%02X%02X", &h.R, &h.G, &h.B, &h.A)
case 7:
// Long form: #RRGGBB
expected = 3
h.A = 0xFF
count, scanErr = fmt.Sscanf(string(text), "#%02X%02X%02X", &h.R, &h.G, &h.B)
case 5:
// Short form with alpha: #RGBA
expected = 4
short = true
count, scanErr = fmt.Sscanf(string(text), "#%01X%01X%01X%01X", &h.R, &h.G, &h.B, &h.A)
case 4:
// Short form: #RGB
expected = 3
h.A = 0xF
short = true
count, scanErr = fmt.Sscanf(string(text), "#%01X%01X%01X", &h.R, &h.G, &h.B)
default:
return fmt.Errorf("can't decode %s as HexColor: wrong length", text)
}
if scanErr != nil {
return scanErr
}
if count != expected {
return fmt.Errorf("can't decode %s as HexColor: missing components", text)
}
if short {
h.R *= 0x11
h.G *= 0x11
h.B *= 0x11
h.A *= 0x11
}
return nil
}
// MarshalText marshals the HexColor into a small string.
func (h HexColor) MarshalText() (text []byte, err error) {
return []byte(h.String()), nil
}
// String prints the HexColor as an abbreviated notation.
// Specifically, short form is used when possible (i.e., when all components are evenly divisible by 0x11).
// The alpha component is left out if it's 0xFF.
func (h HexColor) String() string {
if h.R%0x11 == 0 && h.G%0x11 == 0 && h.B%0x11 == 0 && h.A%0x11 == 0 {
// Short form works.
if h.A == 0xFF {
// It's great when it's easy!
return fmt.Sprintf("#%01X%01X%01X", h.R/0x11, h.G/0x11, h.B/0x11)
} else {
// Just need to add the alpha.
return fmt.Sprintf("#%01X%01X%01X%01X", h.R/0x11, h.G/0x11, h.B/0x11, h.A/0x11)
}
} else {
// Gotta use long form.
if h.A == 0xFF {
// Can skip the alpha channel, though.
return fmt.Sprintf("#%02X%02X%02X", h.R, h.G, h.B)
} else {
// Doing things the hard way.
return fmt.Sprintf("#%02X%02X%02X%02X", h.R, h.G, h.B, h.A)
}
}
}

@ -1,131 +0,0 @@
package state
import (
"fmt"
"github.com/rs/xid"
"go.uber.org/zap/zapcore"
)
// HexMapRepresentation combines HexOrientation and LineParity to represent a map's display mode.
type HexMapRepresentation struct {
Orientation HexOrientation `json:"orientation"`
IndentedLines LineParity `json:"indentedLines"`
}
func (h HexMapRepresentation) MarshalLogObject(encoder zapcore.ObjectEncoder) error {
encoder.AddString("orientation", h.Orientation.String())
encoder.AddString("indentedLines", h.IndentedLines.String())
return nil
}
// HexCell contains data for a single cell of the map.
type HexCell struct {
// Color contains the color of the cell, in hex notation.
Color HexColor `json:"color"`
}
func (h HexCell) MarshalLogObject(encoder zapcore.ObjectEncoder) error {
encoder.AddString("color", h.Color.String())
return nil
}
// HexLine is a line of cells which are adjacent by flat sides in a vertical or horizontal direction.
type HexLine []HexCell
func (l HexLine) MarshalLogArray(encoder zapcore.ArrayEncoder) error {
var finalErr error
for _, cell := range l {
err := encoder.AppendObject(cell)
if err != nil && finalErr == nil {
finalErr = err
}
}
return finalErr
}
// Copy creates a deep copy of this HexLine.
func (l HexLine) Copy() HexLine {
duplicate := make(HexLine, len(l))
for index, value := range l {
duplicate[index] = value
}
return duplicate
}
// HexLayer is a two-dimensional plane of cells which are arranged into lines.
type HexLayer []HexLine
func (l HexLayer) MarshalLogArray(encoder zapcore.ArrayEncoder) error {
var finalErr error
for _, line := range l {
err := encoder.AppendArray(line)
if err != nil && finalErr == nil {
finalErr = err
}
}
return finalErr
}
// GetCellAt returns a reference to the cell at the given coordinates.
// If the coordinates are out of bounds for this map, an error will be returned.
func (l HexLayer) GetCellAt(c StorageCoordinates) (*HexCell, error) {
if int(c.Line) > len(l) {
return nil, fmt.Errorf("line %d out of bounds (%d)", c.Line, len(l))
}
line := l[c.Line]
if int(c.Cell) > len(line) {
return nil, fmt.Errorf("cell %d out of bounds (%d)", c.Cell, len(line))
}
return &(line[c.Cell]), nil
}
// Copy creates a deep copy of this HexLayer.
func (l HexLayer) Copy() HexLayer {
duplicate := make(HexLayer, len(l))
for index, value := range l {
duplicate[index] = value.Copy()
}
return duplicate
}
// HexMap contains the data for a map instance.
type HexMap struct {
// XID is the unique id of the HexMap, used to encourage clients not to blindly interact with a different map.
XID xid.ID `json:"xid"`
// Lines is the rough number of rows (in PointyTop orientation) or columns (in FlatTop orientation) in the map.
// Because different lines will be staggered, it's somewhat hard to see.
Lines uint8 `json:"lines"`
// CellsPerLine is the rough number of columns (in PointyTop orientation) or rows (in FlatTop orientation).
// This is the number of cells joined together, flat-edge to flat-edge, in each line.
CellsPerLine uint8 `json:"cellsPerLine"`
// DisplayMode is the orientation and line parity used to display the map.
DisplayMode HexMapRepresentation `json:"displayMode"`
// LineCells contains the actual map data.
// LineCells itself is a slice with Lines elements, each of which is a line;
// each of those lines is a slice of CellsPerLine cells.
LineCells HexLayer `json:"lineCells"`
}
func (m HexMap) MarshalLogObject(encoder zapcore.ObjectEncoder) error {
encoder.AddString("id", m.XID.String())
encoder.AddUint8("lines", m.Lines)
encoder.AddUint8("cellsPerLine", m.CellsPerLine)
displayModeErr := encoder.AddObject("displayMode", m.DisplayMode)
lineCellsErr := encoder.AddArray("lineCells", m.LineCells)
if displayModeErr != nil {
return displayModeErr
} else {
return lineCellsErr
}
}
// Copy creates a deep copy of this HexMap.
func (m HexMap) Copy() HexMap {
return HexMap{
XID: m.XID,
Lines: m.Lines,
CellsPerLine: m.CellsPerLine,
DisplayMode: m.DisplayMode,
LineCells: m.LineCells.Copy(),
}
}

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

Loading…
Cancel
Save