This commit is contained in:
djerom 2022-03-17 10:36:15 +05:00
parent b0cb3e60d6
commit 5fc055a05d
28 changed files with 3007 additions and 17 deletions

4
.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
/node_modules/
/public/build/
.DS_Store

109
README.md Normal file
View File

@ -0,0 +1,109 @@
*Psst — looking for a more complete solution? Check out [SvelteKit](https://kit.svelte.dev), the official framework for building web applications of all sizes, with a beautiful development experience and flexible filesystem-based routing.*
*Looking for a shareable component template instead? You can [use SvelteKit for that as well](https://kit.svelte.dev/docs#packaging) or the older [sveltejs/component-template](https://github.com/sveltejs/component-template)*
---
# svelte app
This is a project template for [Svelte](https://svelte.dev) apps. It lives at https://github.com/sveltejs/template.
To create a new project based on this template using [degit](https://github.com/Rich-Harris/degit):
```bash
npx degit sveltejs/template svelte-app
cd svelte-app
```
*Note that you will need to have [Node.js](https://nodejs.org) installed.*
## Get started
Install the dependencies...
```bash
cd svelte-app
npm install
```
...then start [Rollup](https://rollupjs.org):
```bash
npm run dev
```
Navigate to [localhost:8080](http://localhost:8080). You should see your app running. Edit a component file in `src`, save it, and reload the page to see your changes.
By default, the server will only respond to requests from localhost. To allow connections from other computers, edit the `sirv` commands in package.json to include the option `--host 0.0.0.0`.
If you're using [Visual Studio Code](https://code.visualstudio.com/) we recommend installing the official extension [Svelte for VS Code](https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode). If you are using other editors you may need to install a plugin in order to get syntax highlighting and intellisense.
## Building and running in production mode
To create an optimised version of the app:
```bash
npm run build
```
You can run the newly built app with `npm run start`. This uses [sirv](https://github.com/lukeed/sirv), which is included in your package.json's `dependencies` so that the app will work when you deploy to platforms like [Heroku](https://heroku.com).
## Single-page app mode
By default, sirv will only respond to requests that match files in `public`. This is to maximise compatibility with static fileservers, allowing you to deploy your app anywhere.
If you're building a single-page app (SPA) with multiple routes, sirv needs to be able to respond to requests for *any* path. You can make it so by editing the `"start"` command in package.json:
```js
"start": "sirv public --single"
```
## Using TypeScript
This template comes with a script to set up a TypeScript development environment, you can run it immediately after cloning the template with:
```bash
node scripts/setupTypeScript.js
```
Or remove the script via:
```bash
rm scripts/setupTypeScript.js
```
If you want to use `baseUrl` or `path` aliases within your `tsconfig`, you need to set up `@rollup/plugin-alias` to tell Rollup to resolve the aliases. For more info, see [this StackOverflow question](https://stackoverflow.com/questions/63427935/setup-tsconfig-path-in-svelte).
## Deploying to the web
### With [Vercel](https://vercel.com)
Install `vercel` if you haven't already:
```bash
npm install -g vercel
```
Then, from within your project folder:
```bash
cd public
vercel deploy --name my-project
```
### With [surge](https://surge.sh/)
Install `surge` if you haven't already:
```bash
npm install -g surge
```
Then, from within your project folder:
```bash
npm run build
surge public my-project.surge.sh
```

14
file.js
View File

@ -1,14 +0,0 @@
export default {
download(filename, text) {
var element = document.createElement("a");
element.setAttribute("href", "data:text/plain;charset=utf-8," + encodeURIComponent(text));
element.setAttribute("download", filename);
element.style.display = "none";
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
},
};

View File

@ -1,3 +0,0 @@
const file = import("./file.js")
console.log(file)

2
js/js-snackbar.min.css vendored Normal file

File diff suppressed because one or more lines are too long

4
js/js-snackbar.min.js vendored Normal file

File diff suppressed because one or more lines are too long

1925
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

26
package.json Normal file
View File

@ -0,0 +1,26 @@
{
"name": "svelte-app",
"version": "1.0.0",
"private": true,
"scripts": {
"build": "rollup -c",
"dev": "rollup -c -w",
"start": "sirv public --no-clear"
},
"devDependencies": {
"@rollup/plugin-commonjs": "^17.0.0",
"@rollup/plugin-node-resolve": "^11.0.0",
"rollup": "^2.3.4",
"rollup-plugin-css-only": "^3.1.0",
"rollup-plugin-livereload": "^2.0.0",
"rollup-plugin-svelte": "^7.0.0",
"rollup-plugin-terser": "^7.0.0",
"svelte": "^3.0.0"
},
"dependencies": {
"@rollup/plugin-json": "^4.1.0",
"axios": "^0.26.1",
"sirv-cli": "^2.0.0",
"svelte-toasts": "^1.1.2"
}
}

7
public/bootstrap.min.css vendored Normal file

File diff suppressed because one or more lines are too long

BIN
public/favicon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

63
public/global.css Normal file
View File

@ -0,0 +1,63 @@
html, body {
position: relative;
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
body {
color: #333;
box-sizing: border-box;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
}
a {
color: rgb(0,100,200);
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
a:visited {
color: rgb(0,80,160);
}
label {
display: block;
}
input, button, select, textarea {
font-family: inherit;
font-size: inherit;
-webkit-padding: 0.4em 0;
padding: 0.4em;
margin: 0 0 0.5em 0;
box-sizing: border-box;
border: 1px solid #ccc;
border-radius: 2px;
}
input:disabled {
color: #ccc;
}
button {
color: #333;
background-color: #f4f4f4;
outline: none;
}
button:disabled {
color: #999;
}
button:not(:disabled):active {
background-color: #ddd;
}
button:focus {
border-color: #666;
}

19
public/index.html Normal file
View File

@ -0,0 +1,19 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset='utf-8'>
<meta name='viewport' content='width=device-width,initial-scale=1'>
<title>Svelte app</title>
<link rel='icon' type='image/png' href='/favicon.png'>
<link rel='stylesheet' href='/global.css'>
<link rel='stylesheet' href='/bootstrap.min.css'>
<link rel='stylesheet' href='/build/bundle.css'>
<script defer src='/build/bundle.js'></script>
</head>
<body>
</body>
</html>

79
rollup.config.js Normal file
View File

@ -0,0 +1,79 @@
import svelte from 'rollup-plugin-svelte';
import commonjs from '@rollup/plugin-commonjs';
import resolve from '@rollup/plugin-node-resolve';
import livereload from 'rollup-plugin-livereload';
import { terser } from 'rollup-plugin-terser';
import css from 'rollup-plugin-css-only';
import json from '@rollup/plugin-json';
const production = !process.env.ROLLUP_WATCH;
function serve() {
let server;
function toExit() {
if (server) server.kill(0);
}
return {
writeBundle() {
if (server) return;
server = require('child_process').spawn('npm', ['run', 'start', '--', '--dev'], {
stdio: ['ignore', 'inherit', 'inherit'],
shell: true
});
process.on('SIGTERM', toExit);
process.on('exit', toExit);
}
};
}
export default {
input: 'src/main.js',
output: {
sourcemap: true,
format: 'iife',
name: 'app',
file: 'public/build/bundle.js'
},
plugins: [
svelte({
compilerOptions: {
// enable run-time checks when not in production
dev: !production
}
}),
json(),
// we'll extract any component CSS out into
// a separate file - better for performance
css({ output: 'bundle.css' }),
// If you have external dependencies installed from
// npm, you'll most likely need these plugins. In
// some cases you'll need additional configuration -
// consult the documentation for details:
// https://github.com/rollup/plugins/tree/master/packages/commonjs
resolve({
browser: true,
dedupe: ['svelte']
}),
commonjs(),
// In dev mode, call `npm run start` once
// the bundle has been generated
!production && serve(),
// Watch the `public` directory and refresh the
// browser on changes when not in production
!production && livereload('public'),
// If we're building for production (npm run build
// instead of npm run dev), minify
production && terser()
],
watch: {
clearScreen: false
}
};

121
scripts/setupTypeScript.js Normal file
View File

@ -0,0 +1,121 @@
// @ts-check
/** This script modifies the project to support TS code in .svelte files like:
<script lang="ts">
export let name: string;
</script>
As well as validating the code for CI.
*/
/** To work on this script:
rm -rf test-template template && git clone sveltejs/template test-template && node scripts/setupTypeScript.js test-template
*/
const fs = require("fs")
const path = require("path")
const { argv } = require("process")
const projectRoot = argv[2] || path.join(__dirname, "..")
// Add deps to pkg.json
const packageJSON = JSON.parse(fs.readFileSync(path.join(projectRoot, "package.json"), "utf8"))
packageJSON.devDependencies = Object.assign(packageJSON.devDependencies, {
"svelte-check": "^2.0.0",
"svelte-preprocess": "^4.0.0",
"@rollup/plugin-typescript": "^8.0.0",
"typescript": "^4.0.0",
"tslib": "^2.0.0",
"@tsconfig/svelte": "^2.0.0"
})
// Add script for checking
packageJSON.scripts = Object.assign(packageJSON.scripts, {
"check": "svelte-check --tsconfig ./tsconfig.json"
})
// Write the package JSON
fs.writeFileSync(path.join(projectRoot, "package.json"), JSON.stringify(packageJSON, null, " "))
// mv src/main.js to main.ts - note, we need to edit rollup.config.js for this too
const beforeMainJSPath = path.join(projectRoot, "src", "main.js")
const afterMainTSPath = path.join(projectRoot, "src", "main.ts")
fs.renameSync(beforeMainJSPath, afterMainTSPath)
// Switch the app.svelte file to use TS
const appSveltePath = path.join(projectRoot, "src", "App.svelte")
let appFile = fs.readFileSync(appSveltePath, "utf8")
appFile = appFile.replace("<script>", '<script lang="ts">')
appFile = appFile.replace("export let name;", 'export let name: string;')
fs.writeFileSync(appSveltePath, appFile)
// Edit rollup config
const rollupConfigPath = path.join(projectRoot, "rollup.config.js")
let rollupConfig = fs.readFileSync(rollupConfigPath, "utf8")
// Edit imports
rollupConfig = rollupConfig.replace(`'rollup-plugin-terser';`, `'rollup-plugin-terser';
import sveltePreprocess from 'svelte-preprocess';
import typescript from '@rollup/plugin-typescript';`)
// Replace name of entry point
rollupConfig = rollupConfig.replace(`'src/main.js'`, `'src/main.ts'`)
// Add preprocessor
rollupConfig = rollupConfig.replace(
'compilerOptions:',
'preprocess: sveltePreprocess({ sourceMap: !production }),\n\t\t\tcompilerOptions:'
);
// Add TypeScript
rollupConfig = rollupConfig.replace(
'commonjs(),',
'commonjs(),\n\t\ttypescript({\n\t\t\tsourceMap: !production,\n\t\t\tinlineSources: !production\n\t\t}),'
);
fs.writeFileSync(rollupConfigPath, rollupConfig)
// Add TSConfig
const tsconfig = `{
"extends": "@tsconfig/svelte/tsconfig.json",
"include": ["src/**/*"],
"exclude": ["node_modules/*", "__sapper__/*", "public/*"]
}`
const tsconfigPath = path.join(projectRoot, "tsconfig.json")
fs.writeFileSync(tsconfigPath, tsconfig)
// Add global.d.ts
const dtsPath = path.join(projectRoot, "src", "global.d.ts")
fs.writeFileSync(dtsPath, `/// <reference types="svelte" />`)
// Delete this script, but not during testing
if (!argv[2]) {
// Remove the script
fs.unlinkSync(path.join(__filename))
// Check for Mac's DS_store file, and if it's the only one left remove it
const remainingFiles = fs.readdirSync(path.join(__dirname))
if (remainingFiles.length === 1 && remainingFiles[0] === '.DS_store') {
fs.unlinkSync(path.join(__dirname, '.DS_store'))
}
// Check if the scripts folder is empty
if (fs.readdirSync(path.join(__dirname)).length === 0) {
// Remove the scripts folder
fs.rmdirSync(path.join(__dirname))
}
}
// Adds the extension recommendation
fs.mkdirSync(path.join(projectRoot, ".vscode"), { recursive: true })
fs.writeFileSync(path.join(projectRoot, ".vscode", "extensions.json"), `{
"recommendations": ["svelte.svelte-vscode"]
}
`)
console.log("Converted to TypeScript.")
if (fs.existsSync(path.join(projectRoot, "node_modules"))) {
console.log("\nYou will need to re-run your dependency manager to get started.")
}

237
src/App.svelte Normal file
View File

@ -0,0 +1,237 @@
<script>
import { onMount } from "svelte";
import axios from "axios";
import { toasts, ToastContainer, FlatToast } from "svelte-toasts";
// import file_lib from './libs/file'
import SvgNodes from "./svgmap/SvgNodes";
import SvgMapUI from "./svgmap/SvgMapUI";
import file_lib from "./libs/file";
import Modal from "./components/Modal.svelte";
import MapApp from './services/map'
import get_bbox from './libs/bbox'
const back_url = "http://localhost:4000";
let cur_map = null;
import styles from './moc/styles.json'
let map_host;
let map;
onMount(() => {
map = new SvgMapUI(map_host);
});
let WellsRenderer = {
// [{x,y}]
heads(wells, r, style) {
return wells.map((w) => SvgNodes.circle(r).set_style(style).move(w.x, w.y));
},
// [{x,y,name}]
names(wells, style, shift) {
return wells.map((w) =>
SvgNodes.text(w.name)
.set_style(style)
.move(w.x + shift.x, w.y + shift.y)
);
},
// {x,y,ring[1,2,3,4,5]}
ring(x, y, r0, r1, a0, a1, style) {
return SvgNodes.ring_sector(r0, r1, a0, a1).move(x, y).set_style(style);
},
};
function save() {
file_lib.download("map.svg", cur_map);
// console.log(cur_map);
}
async function upload_file_wells() {
const form = `Выберите файл скважин для загрузки<br>
<input type="file" name="file"/>`; // multiple
let res = await ui.modal.show(form, ["ok", "cancel"]);
console.log(res);
// console.log(res.form['some'].value)
let file = await file_lib.toBase64(res.form["file"]);
let ans = await axios.post(`${back_url}/import/excel`, { name: "wells", file });
console.log(ans);
toasts.add({
description: "File loaded",
type: 'success',
});
// ui.modal.show(`Hallo ${res.form['some'].value}`, ['ok'])
}
async function upload_file_mer() {
const form = `Выберите файл мэр для загрузки<br>
<input type="file" name="file"/>`; // multiple
let res = await ui.modal.show(form, ["ok", "cancel"]);
console.log(res);
// console.log(res.form['some'].value)
let file = await file_lib.toBase64(res.form["file"]);
let ans = await axios.post(`${back_url}/import/excel`, { name: "production_injection", file });
console.log(ans);
// ui.modal.show(`Hallo ${res.form['some'].value}`, ['ok'])
toasts.add({
description: "File loaded",
type: 'success',
});
}
let ui = {
modal: {},
};
// ui.modal.show('<div>Выберите файл для загрузки в базу<br><ui-filedialog name="file1"></ui-filedialog></div>', ['ok', 'cancel'])
// ui.modal.hide()
// file_lib.download()
/**
*
* @param r0
* @param r1
* @param a0
* @param a1
* @param { [{v, style}] } rings
*/
function sectored_ring(r0, r1, rings){
let sum = rings.reduce((s,c) => s + c.v, 0)
let angs = rings.reduce((s, c, i) => [...s, {...c, a0: i && s[i - 1].a1, a1: c.v + (i && s[i - 1].a1)}], [])
let items = angs.map(x => SvgNodes.ring_sector(r0, r1, x.a0 * 360 / sum, x.a1 * 360 / sum).set_style(x.style))
return SvgNodes.group(items)
}
async function build_map() {
const query = "SELECT * FROM wells";
let wells = await axios.post(`${back_url}/proxy/sqlite`, { query }).then((x) => x.data.data);
const mapscale = 1 / 1;
const scale = (w) => w * mapscale;
const whr = 10;
const shift = { x: 10, y: -10 };
// map = new map()
let bbox = get_bbox(wells.map(w => ({x: w.whx, y: w.why})))
console.log(bbox);
let scaled_wells = wells.map((x) => ({ ...x, whx: scale(x.whx - bbox.l), why: scale(x.why - bbox.t) }));
let r0 = 0;
let r1 = 30;
let a0 = 0;
let a1 = 130;
let layer_gpt = scaled_wells.map((w) =>
SvgNodes.ring_sector(r0, r1, a0, a1).move(w.whx, w.why).set_style(styles.gpt)
);
let layer_wells = scaled_wells.map((w) =>
SvgNodes.circle(whr).set_attrs({ cx: w.whx, cy: w.why }).set_style(styles.wellhead)
);
let layer_wellnames = scaled_wells.map((w) =>
SvgNodes.text(w.well)
.set_style(styles.style_wellhead)
.move(w.whx + shift.x, w.why + shift.y)
);
let layer_rings = scaled_wells.map((w) =>
sectored_ring(0, 50, [{v: 10, style: styles.gpt}, {v: 20, style: styles.opt}, {v: 30, style: styles.wopt}]).move(w.whx, w.why)
);
// let layer_wells_wpr = wells.map((w) => svg_sector(70, 0, 70).set_style(style_wir).move(w.whx, w.why).render());
// let layer_wells_gpr = wells.map((w) =>
// svg_sector(70, 70, 130).set_style(style_gpr).move(w.whx, w.why).render()
// );
// let layer_wells_opr = wells.map((w) =>
// svg_sector(70, 130, 360).set_style(style_opr).move(w.whx, w.why).render()
// );
// let layer_well_names = wells.map((w) =>
// svg_text(w.well)
// .set_style(style_wellhead_text)
// .move(w.whx + 10, w.why - 10)
// .render()
// );
// let layers = [...layer_wells, ...layer_wells_wpr, ...layer_well_names]
// let layers = layer_wells_wpr
let svg = SvgNodes.svg(); //.set_attr("viewBox", `${bbox.l} ${bbox.t} ${bbox.r - bbox.l} ${bbox.b - bbox.t}`);
console.log(svg);
// svg.append(layer_gpt);
svg.append(layer_rings)
svg.append(layer_wells);
svg.append(layer_wellnames);
cur_map = svg.render();
map.set(cur_map);
}
function func() {
toasts.add({
title: "Message title",
description: "Message body",
});
}
</script>
<main>
<Modal bind:this={ui.modal} />
<ToastContainer {toasts} let:data>
<FlatToast {data} />
</ToastContainer>
<button on:click={() => upload_file_wells()}>Upload file Wells</button>
<button on:click={() => upload_file_mer()}>Upload file mer(prod_inj)</button>
<button on:click={() => build_map()}>Build map</button>
<button on:click={() => save()}>Download</button>
<button on:click={() => func()}>Func</button>
<div bind:this={map_host} style="border: 1px solid #f00;" />
</main>
<style>
main {
text-align: center;
padding: 1em;
max-width: 240px;
margin: 0 auto;
}
h1 {
color: #ff3e00;
text-transform: uppercase;
font-size: 4em;
font-weight: 100;
}
@media (min-width: 640px) {
main {
max-width: none;
}
}
</style>

View File

@ -0,0 +1,50 @@
<script>
import { onMount } from "svelte";
// export function init() {
// document.body.appendChild(_dialog);
// }
export function show(html, buttons) {
_html = html
_visible = true
_buttons = buttons
return new Promise(resolve => _resolve = resolve)
}
export function hide(code) {
_visible = false
_resolve({code, form: _form})
}
let _dialog, _form, _html, _visible = false, _buttons = [], _resolve
onMount(() => {
document.body.appendChild(_dialog);
})
</script>
<!-- <div class="modal" tabindex="-1" role="dialog" bind:this={dialog}> -->
<div class="modal fade show" style="display: {_visible ? 'block' : 'none'};" tabindex="-1" role="dialog" bind:this={_dialog}> -->
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close" on:click={() => hide()}>
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<form bind:this={_form}>
{@html _html}
</form>
</div>
<div class="modal-footer">
{#each _buttons as b}
<button type="button" class="btn btn-primary" on:click={hide(b)}>{b}</button>
{/each}
</div>
</div>
</div>
</div>

View File

@ -0,0 +1,8 @@
<script>
import { onMount } from "svelte";
</script>
<div>
</div>

View File

11
src/libs/bbox.js Normal file
View File

@ -0,0 +1,11 @@
module.exports = function (data) {
return data.reduce(
(s, c) => ({
l: Math.min(s.l, c.x),
t: Math.min(s.t, c.y),
r: Math.max(s.r, c.x),
b: Math.max(s.b, c.y),
}),
{ l: data[0].x, t: data[0].y, r: data[0].x, b: data[0].y }
);
};

56
src/libs/file.js Normal file
View File

@ -0,0 +1,56 @@
export default {
/**
* Downloads file
* @param {*} filename
* @param {*} data
*/
download(filename, data) {
var element = document.createElement("a");
element.setAttribute("href", "data:text/plain;charset=utf-8," + encodeURIComponent(data));
element.setAttribute("download", filename);
element.style.display = "none";
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
},
/**
* Convert data of file selected in input to base64 string
* @param {*} input
*/
async toBase64(input) {
console.log(input)
return new Promise((resolve) => {
if (input.files.length == 0){
resolve(null)
}
else if (input.files.length == 1){
this.fileToBase64(input.files[0]).then(resolve)
}
else
Promise.all(Array(...input.files).map(this.fileToBase64)).then(resolve)
}
);
},
/**
* Convert data of file selected in input to base64 string
* @param {*} input
*/
async fileToBase64(file) {
return new Promise((resolve, reject) => {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
resolve(reader.result)
};
reader.onerror = function (error) {
reject(error)
};
});
}
};

10
src/main.js Normal file
View File

@ -0,0 +1,10 @@
import App from './App.svelte';
const app = new App({
target: document.body,
props: {
name: 'world'
}
});
export default app;

22
src/moc/styles.json Normal file
View File

@ -0,0 +1,22 @@
{
"wellhead": {
"stroke-width": 1,
"stroke": "#000",
"fill": "#fff"
},
"gpt": {
"stroke-width": 0,
"stroke": "#ff0",
"fill": "#ff0"
},
"opt": {
"stroke-width": 1,
"stroke": "#f00",
"fill": "#00f"
},
"wpt": {
"stroke-width": 1,
"stroke": "#f00",
"fill": "#00f"
}
}

26
src/services/map.js Normal file
View File

@ -0,0 +1,26 @@
module.exports = class {
set_scale(scale){
this.scale = scale
}
get_bbox(data){
return data.reduce(
(s, c) => ({
l: Math.min(s.l, c.x),
t: Math.min(s.t, c.y),
r: Math.max(s.r, c.x),
b: Math.max(s.b, c.y),
}),
{ l: data[0].x, t: data[0].y, r: data[0].x, b: data[0].y }
)
}
wells_layer(wells){
}
render(){
}
}

9
src/services/wells.js Normal file
View File

@ -0,0 +1,9 @@
module.exports = class {
constructor(url){
this.url = url
}
get_wells(){
}
}

87
src/svgmap/SvgMapUI.js Normal file
View File

@ -0,0 +1,87 @@
export default class SvgMapUI {
constructor(host) {
this.host = host
this.scale = 1
this.pos = { x: 0, y: 0 }
console.log(host)
this.host.onwheel = this.handle_wheel.bind(this)
this.host.onmousedown = this.handle_mousedown.bind(this)
this.host.onmousemove = this.handle_mousemove.bind(this)
this.host.onmouseup = this.handle_mouseup.bind(this)
this.is_down = false
this.set_scale(1)
}
set(html){
this.host.innerHTML = html
}
handle_mousedown(event) {
this.is_down = true
this.downin = { x: event.clientX, y: event.clientY }
console.log(event)
// clientX: 451, clientY: 297
// layerX: 451, layerY: 297
}
handle_mousemove(event) {
if (this.is_down) {
event.preventDefault()
let dx = event.clientX - this.downin.x
let dy = event.clientY - this.downin.y
this.pos.x -= dx * this.scale
this.pos.y -= dy * this.scale
this.set_scale(this.scale)
this.downin = { x: event.clientX, y: event.clientY }
// this.downin = {x: event.clientX, y: event.clientY}
}
// console.log(event.x, event.clientX + this.pos.x, this.scale)
}
handle_mouseup(event) {
this.is_down = false
}
handle_wheel(event) {
event.preventDefault()
if (event.ctrlKey) {
if (event.deltaY > 0) {
this.scale_up()
}
else
this.scale_down()
}
else if (event.shiftKey) {
console.log('shifted')
}
else {
}
console.log(event)
}
set_scale(scale) {
this.scale = scale
if (!this.host.childNodes.length) return;
this.host.childNodes[0].setAttribute("viewBox", `${this.pos.x} ${this.pos.y} ${2000 * this.scale} ${2000 * this.scale}`)
// this.host.childNodes[0].setAttribute("width", `1000`)
// this.host.childNodes[0].setAttribute("height", `1000`)
}
scale_up() {
this.set_scale(this.scale * 1.1)
}
scale_down() {
this.set_scale(this.scale * 0.9)
}
}

61
src/svgmap/SvgNode.js Normal file
View File

@ -0,0 +1,61 @@
export default class SvgNode {
constructor(tag, attrs, items) {
this.tag = tag
this.attrs = attrs || {}
this.items = items || []
}
append(items){
this.items.push(items)
return this
}
set_attr(attr, value) {
this.attrs[attr] = value
return this
}
set_attrs(attrs) {
this.attrs = { ...this.attrs, ...attrs }
return this
}
set_style(style) {
this.style = { ...this.style || {}, ...style }
return this
}
clear_style(style) {
this.style = null
return this
}
move(x, y) {
this.transform = { x, y }
return this
}
get(attr) {
}
_render_node(node) {
// console.log(typeof node)
// if (typeof node == 'undefined') return ''
if (typeof node == 'string') return node
else if (typeof node == 'object' && node.tag) return node.render()
else if (Array.isArray(node)) return node.map(this._render_node).join('')
else return ''
}
render() {
let attrs = Object.keys(this.attrs).map(x => ` ${x}="${this.attrs[x]}"`).join('')
// console.log(this.style ? Object.keys(this.style).map(x => `${x}:${this.style[x]}`) : '')
let style = this.style ? ' style="' + Object.keys(this.style).map(x => `${x}:${this.style[x]}`).join('; ') + '"' : ''
let transfrom = this.transform ? ` transform="translate(${this.transform.x},${this.transform.y})"` : ''
let items = this.items ? this.items.map(x => this._render_node(x)).join('') : ''
// console.log('this.items', this.items, items)
return `<${this.tag}${attrs}${style}${transfrom}>${items}</${this.tag}>`
}
}

71
src/svgmap/SvgNodes.js Normal file
View File

@ -0,0 +1,71 @@
import SvgNode from "./SvgNode";
export default {
// sector(r, a0, a1) {
// const k = Math.PI / 180;
// let s0 = -Math.sin(a0 * k) * r;
// let c0 = Math.cos(a0 * k) * r;
// let s1 = -Math.sin(a1 * k) * r;
// let c1 = Math.cos(a1 * k) * r;
// var aa = a1 - a0 > 180 ? 1 : 0;
// // var p = new TimalSvg.Data.SvgPath(string.Format("M0 0 L{0} 0 A {0} {0} 0 {3} 0 {1} {2} z", FN(r), ca, sa, aa));
// // p.Transform = string.Format("rotate({0})", FN(ang / 2));
// return `<path d="M0 0 L${c0} ${s0} A ${r} ${r} 0 ${aa} 0 ${c1} ${s1} z" stroke-width="3" stroke="#f00" fill="#0f0"/>`;
// },
svg(){
return new SvgNode('svg', {
version: "1.1",
xmlns: "http://www.w3.org/2000/svg"
// viewBox: "0 0 2000 2000"
})
},
group(items){
return new SvgNode("g", null, items)
},
circle(r) {
return new SvgNode("circle", {r})
},
sector(r, a0, a1) {
const k = Math.PI / 180;
let s0 = -Math.sin(a0 * k) * r;
let c0 = Math.cos(a0 * k) * r;
let s1 = -Math.sin(a1 * k) * r;
let c1 = Math.cos(a1 * k) * r;
var aa = a1 - a0 > 180 ? 1 : 0;
// var p = new TimalSvg.Data.SvgPath(string.Format("M0 0 L{0} 0 A {0} {0} 0 {3} 0 {1} {2} z", FN(r), ca, sa, aa));
// p.Transform = string.Format("rotate({0})", FN(ang / 2));
return new SvgNode("path", { d: `M0 0 L${c0} ${s0} A ${r} ${r} 0 ${aa} 0 ${c1} ${s1} z` });
},
ring_sector(r0, r1, a0, a1) {
const k = Math.PI / 180;
let s0 = -Math.sin(a0 * k);
let c0 = Math.cos(a0 * k);
let s1 = -Math.sin(a1 * k);
let c1 = Math.cos(a1 * k);
var aa = a1 - a0 > 180 ? 1 : 0;
return new SvgNode("path", {
d: `M${c0 * r0} ${s0 * r0}
A ${r0} ${r0} 0 ${aa} 0 ${c1 * r0} ${s1 * r0}
L${c1 * r1} ${s1 * r1}
A ${r1} ${r1} 0 ${aa} 1 ${c0 * r1} ${s0 * r1} z`,
});
},
text(text) {
let node = new SvgNode("text");
node.items = [text];
node.set_attrs({x: 0, y: 0})
return node;
},
};

0
src/svgmap/index.js Normal file
View File