initial commit

This commit is contained in:
2021-07-13 22:46:05 +02:00
commit 109f78be7f
21 changed files with 2612 additions and 0 deletions

4
.gitignore vendored Normal file
View File

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

0
.idea/.gitignore generated vendored Normal file
View File

12
.idea/MeItServ.iml generated Normal file
View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/temp" />
<excludeFolder url="file://$MODULE_DIR$/.tmp" />
<excludeFolder url="file://$MODULE_DIR$/tmp" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

8
.idea/modules.xml generated Normal file
View File

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

73
.idea/workspace.xml generated Normal file
View File

@@ -0,0 +1,73 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ChangeListManager">
<list default="true" id="ef8b1e1b-ebaf-40d3-8e5b-bfe813f4128b" name="Changes" comment="" />
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="FileTemplateManagerImpl">
<option name="RECENT_TEMPLATES">
<list>
<option value="Header" />
<option value="Footer" />
<option value="Tabs" />
<option value="CreatePollForm" />
<option value="Button" />
</list>
</option>
</component>
<component name="ProjectId" id="1vGvjJPfoEQS7Sr5c6wISTBpD8s" />
<component name="ProjectViewState">
<option name="hideEmptyMiddlePackages" value="true" />
<option name="showLibraryContents" value="true" />
</component>
<component name="PropertiesComponent">
<property name="RunOnceActivity.OpenProjectViewOnStart" value="true" />
<property name="RunOnceActivity.ShowReadmeOnStart" value="true" />
<property name="WebServerToolWindowFactoryState" value="false" />
<property name="last_opened_file_path" value="$PROJECT_DIR$" />
<property name="node.js.detected.package.eslint" value="true" />
<property name="node.js.detected.package.tslint" value="true" />
<property name="node.js.selected.package.eslint" value="(autodetect)" />
<property name="node.js.selected.package.tslint" value="(autodetect)" />
<property name="nodejs_package_manager_path" value="npm" />
<property name="settings.editor.selected.configurable" value="preferences.keymap" />
<property name="vue.rearranger.settings.migration" value="true" />
</component>
<component name="RunManager">
<configuration name="dev" type="js.build_tools.npm" temporary="true" nameIsGenerated="true">
<package-json value="$PROJECT_DIR$/package.json" />
<command value="run" />
<scripts>
<script value="dev" />
</scripts>
<node-interpreter value="project" />
<envs />
<method v="2" />
</configuration>
<recent_temporary>
<list>
<item itemvalue="npm.dev" />
</list>
</recent_temporary>
</component>
<component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" />
<component name="TaskManager">
<task active="true" id="Default" summary="Default task">
<changelist id="ef8b1e1b-ebaf-40d3-8e5b-bfe813f4128b" name="Changes" comment="" />
<created>1626201375143</created>
<option name="number" value="Default" />
<option name="presentableId" value="Default" />
<updated>1626201375143</updated>
<workItem from="1626201376810" duration="120000" />
<workItem from="1626201521289" duration="503000" />
<workItem from="1626202032728" duration="4745000" />
</task>
<servers />
</component>
<component name="TypeScriptGeneratedFilesManager">
<option name="version" value="3" />
</component>
</project>

105
README.md Normal file
View File

@@ -0,0 +1,105 @@
*Looking for a shareable component template? Go here --> [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:5000](http://localhost:5000). 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
```
## 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
```

1822
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

23
package.json Normal file
View File

@@ -0,0 +1,23 @@
{
"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": {
"sirv-cli": "^1.0.0"
}
}

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%;
}
body {
color: #333;
margin: 0;
/*padding: 8px;*/
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;
}

18
public/index.html Normal file
View File

@@ -0,0 +1,18 @@
<!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='/build/bundle.css'>
<script defer src='/build/bundle.js'></script>
</head>
<body>
</body>
</html>

76
rollup.config.js Normal file
View File

@@ -0,0 +1,76 @@
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';
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
}
}),
// 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.")
}

64
src/App.svelte Normal file
View File

@@ -0,0 +1,64 @@
<script>
import Header from './components/Header.svelte'
import Footer from './components/Footer.svelte'
import CreatePollForm from './components/CreatePollForm.svelte';
import Tabs from './shared/Tabs.svelte';
export let name;
let items = ['Current Polls', 'Add New Poll']
let activeITem = 'Current Polls';
const tabChangeFunc = (e) => {
activeITem = e.detail
};
let polls = [
{
id: 1,
question: 'PYthon or JS?',
answerA: 'Python',
answerB: 'JS',
votesA: 9,
votesB: 15,
},
]
const handleAdd = (e) => {
const poll = e.detail;
polls = [poll, ...polls];
console.log(polls);
};
</script>
<Header />
<main>
<h1>Hello {name}!</h1>
<p>Visit the <a href="https://svelte.dev/tutorial">Svelte tutorial</a> to learn how to build Svelte apps.</p>
<Tabs {activeITem} {items} on:tabChange={tabChangeFunc}/>
{#if activeITem === 'Current Polls'}
<p>Poll list component goes here</p>
{:else if activeITem === 'Add New Poll'}
<CreatePollForm on:add={handleAdd}/>
{/if}
</main>
<Footer />
<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,87 @@
<script>
import { createEventDispatcher} from 'svelte';
const dispatch = createEventDispatcher();
import Button from '../shared/Button.svelte'
let fields = {question: '', answerA: '', answerB: ''};
let errors = {question: '', answerA: '', answerB: ''};
let valid = false;
const submitHandler = () => {
valid = true;
// validate question
if (fields.question.trim().length < 5) {
valid = false;
errors.question = 'Question is too short (5).';
} else {
errors.question = '';
}
// validate answer A
if (fields.answerA.trim().length < 1) {
valid = false;
errors.answerA = 'Answer A cannot be empty';
} else {
errors.answerA = '';
}
// validate answer B
if (fields.answerB.trim().length < 1) {
valid = false;
errors.answerB = 'Answer B cannot be empty';
} else {
errors.answerB = '';
}
if (valid){
let poll = {...fields, votesA:0, votesB: 0, id: Math.random()};
dispatch('add', poll);
console.log('valid', fields);
}
}
</script>
<form on:submit|preventDefault={submitHandler}>
<div class="form-field">
<label for="question">Poll Question:</label>
<input type="text" id="question" bind:value={fields.question}>
<div class="error">{ errors.question }</div>
</div>
<div class="form-field">
<label for="answer-a">Answer A:</label>
<input type="text" id="answer-a" bind:value={fields.answerA}>
<div class="error">{ errors.answerA }</div>
</div>
<div class="form-field">
<label for="answer-b">Answer B:</label>
<input type="text" id="answer-b" bind:value={fields.answerB}>
<div class="error">{ errors.answerB }</div>
</div>
<Button type="secondary" flat={true} inverse={true}>Add Poll</Button>
</form>
<style>
form{
width: 400px;
margin: 0 auto;
text-align: center;
}
.form-field{
margin: 18px auto;
}
input{
width: 100%;
border-radius: 6px;
}
label{
margin: 10px auto;
text-align: left;
}
.error{
font-weight: bold;
font-size: 12px;
color: #d91b42;
}
</style>

View File

@@ -0,0 +1,17 @@
<footer>
<div class="copyright">Copyright 2021 Tobias Kurze</div>
</footer>
<style>
footer {
padding: 40px;
text-align: center;
}
.copyright {
color: #aaa;
font-size: 14px;
display: inline-block;
padding: 20px;
border-top: 1px solid #ddd;
}
</style>

View File

@@ -0,0 +1,24 @@
<script>
</script>
<header>
<h1>
<img src="/img/" alt="Poll Ninja Logo">
</h1>
</header>
<style>
header {
background: #f7f7f7;
padding: 20px;
}
h1 {
margin: 0;
text-align: center;
}
img {
max-width: 180px;
}
</style>

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;

44
src/shared/Button.svelte Normal file
View File

@@ -0,0 +1,44 @@
<script>
export let type = 'primary';
export let flat = false;
export let inverse = false;
</script>
<button class={type} class:flat={flat} class:inverse={inverse}>
<slot></slot>
</button>
<style>
button{
border: 0;
cursor: pointer;
border-radius: 6px;
padding: 8px 12px;
font-weight: bold;
box-shadow: 1px 2px 3px rgba(0,0,0,0.2);
}
.primary{
background: #d91b42;
color: white;
}
.secondary{
background: #45c496;
color: white;
}
.flat{
box-shadow: none;
}
.primary.inverse{
color: #d91b42;
background: white;
border: 2px solid #d91b42;
}
.secondary.inverse{
color: #45c496;
background: white;
border: 2px solid #45c496;
}
</style>

40
src/shared/Tabs.svelte Normal file
View File

@@ -0,0 +1,40 @@
<script>
import { createEventDispatcher} from 'svelte';
const dispatch = createEventDispatcher();
export let items;
export let activeITem;
</script>
<div class="tabs">
<ul>
{#each items as item}
<li on:click={() => dispatch('tabChange', item)}>
<div class:active={item === activeITem}>{item}</div>
</li>
{/each}
</ul>
</div>
<style>
.tabs {
margin-bottom: 40px;
}
ul{
display: flex;
justify-content: center;
padding: 0;
list-style-type: none;
}
li{
margin: 0 16px;
font-size: 18px;
color: #555;
cursor: pointer;
}
.active {
color: #d91b42;
border-bottom: 2px solid #d91b42;
padding-bottom: 8px;
}
</style>

1
src/views/nested.svelte Normal file
View File

@@ -0,0 +1 @@
<p>This is another paragraph in ./views</p>