Initial import

This commit is contained in:
wlee221
2020-09-23 15:40:20 -07:00
commit 2dcbf9d23d
24 changed files with 5918 additions and 0 deletions

20
.gitignore vendored Normal file
View File

@@ -0,0 +1,20 @@
/node_modules/
/public/build/
.DS_Store
#amplify
amplify/\#current-cloud-backend
amplify/.config/local-*
amplify/mock-data
amplify/backend/amplify-meta.json
amplify/backend/awscloudformation
build/
dist/
node_modules/
aws-exports.js
awsconfiguration.json
amplifyconfiguration.json
amplify-build-config.json
amplify-gradle-config.json
amplifytools.xcconfig

12
.graphqlconfig.yml Normal file
View File

@@ -0,0 +1,12 @@
projects:
mysvelteproject:
schemaPath: src/graphql/schema.json
includes:
- src/graphql/**/*.js
excludes:
- ./amplify/**
extensions:
amplify:
codeGenTarget: javascript
generatedFileName: ''
docsFilePath: src/graphql

104
README.md Normal file
View File

@@ -0,0 +1,104 @@
*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`.
## 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
```

View File

@@ -0,0 +1,17 @@
{
"projectName": "mysvelteproject",
"version": "3.0",
"frontend": "javascript",
"javascript": {
"framework": "none",
"config": {
"SourceDir": "src",
"DistributionDir": "dist",
"BuildCommand": "npm run-script build",
"StartCommand": "npm run-script start"
}
},
"providers": [
"awscloudformation"
]
}

View File

@@ -0,0 +1,5 @@
{
"AppSyncApiName": "mysvelteproject",
"DynamoDBBillingMode": "PAY_PER_REQUEST",
"DynamoDBEnableServerSideEncryption": "false"
}

View File

@@ -0,0 +1,5 @@
type Todo @model {
id: ID!
done: Boolean!
description: String
}

View File

@@ -0,0 +1,61 @@
{
"AWSTemplateFormatVersion": "2010-09-09",
"Description": "An auto-generated nested stack.",
"Metadata": {},
"Parameters": {
"AppSyncApiId": {
"Type": "String",
"Description": "The id of the AppSync API associated with this project."
},
"AppSyncApiName": {
"Type": "String",
"Description": "The name of the AppSync API",
"Default": "AppSyncSimpleTransform"
},
"env": {
"Type": "String",
"Description": "The environment name. e.g. Dev, Test, or Production",
"Default": "NONE"
},
"S3DeploymentBucket": {
"Type": "String",
"Description": "The S3 bucket containing all deployment assets for the project."
},
"S3DeploymentRootKey": {
"Type": "String",
"Description": "An S3 key relative to the S3DeploymentBucket that points to the root\nof the deployment directory."
}
},
"Resources": {
"EmptyResource": {
"Type": "Custom::EmptyResource",
"Condition": "AlwaysFalse"
}
},
"Conditions": {
"HasEnvironmentParameter": {
"Fn::Not": [
{
"Fn::Equals": [
{
"Ref": "env"
},
"NONE"
]
}
]
},
"AlwaysFalse": {
"Fn::Equals": [
"true",
"false"
]
}
},
"Outputs": {
"EmptyOutput": {
"Description": "An empty output. You may delete this if you have at least one resource above.",
"Value": ""
}
}
}

View File

@@ -0,0 +1,4 @@
{
"Version": 5,
"ElasticsearchWarning": true
}

View File

@@ -0,0 +1,20 @@
{
"api": {
"mysvelteproject": {
"service": "AppSync",
"providerPlugin": "awscloudformation",
"output": {
"authConfig": {
"additionalAuthenticationProviders": [],
"defaultAuthentication": {
"authenticationType": "API_KEY",
"apiKeyConfig": {
"description": "",
"apiKeyExpirationDays": 7
}
}
}
}
}
}
}

View File

@@ -0,0 +1,15 @@
{
"dev": {
"awscloudformation": {
"AuthRoleName": "amplify-mysvelteproject-dev-105419-authRole",
"UnauthRoleArn": "arn:aws:iam::739164709218:role/amplify-mysvelteproject-dev-105419-unauthRole",
"AuthRoleArn": "arn:aws:iam::739164709218:role/amplify-mysvelteproject-dev-105419-authRole",
"Region": "us-west-2",
"DeploymentBucketName": "amplify-mysvelteproject-dev-105419-deployment",
"UnauthRoleName": "amplify-mysvelteproject-dev-105419-unauthRole",
"StackName": "amplify-mysvelteproject-dev-105419",
"StackId": "arn:aws:cloudformation:us-west-2:739164709218:stack/amplify-mysvelteproject-dev-105419/cf853660-fdc5-11ea-a52a-06822d005ce6",
"AmplifyAppId": "dvck908riea1a"
}
}
}

1534
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",
"scripts": {
"build": "rollup -c",
"dev": "rollup -c -w",
"start": "sirv public"
},
"devDependencies": {
"@rollup/plugin-commonjs": "^14.0.0",
"@rollup/plugin-json": "^4.1.0",
"@rollup/plugin-node-resolve": "^8.0.0",
"rollup": "^2.3.4",
"rollup-plugin-livereload": "^2.0.0",
"rollup-plugin-svelte": "^6.0.0",
"rollup-plugin-terser": "^7.0.0",
"svelte": "^3.26.0"
},
"dependencies": {
"@aws-amplify/api": "^3.2.4",
"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>

78
rollup.config.js Normal file
View File

@@ -0,0 +1,78 @@
import svelte from "rollup-plugin-svelte";
import resolve from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import livereload from "rollup-plugin-livereload";
import json from "@rollup/plugin-json";
import { terser } from "rollup-plugin-terser";
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({
// 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: (css) => {
css.write("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,
preferBuiltins: false, // new!
dedupe: ["svelte"],
}),
json(),
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,
},
};

128
scripts/setupTypeScript.js Normal file
View File

@@ -0,0 +1,128 @@
// @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": "^1.0.0",
"svelte-preprocess": "^4.0.0",
"@rollup/plugin-typescript": "^6.0.0",
"typescript": "^3.9.3",
"tslib": "^2.0.0",
"@tsconfig/svelte": "^1.0.0"
})
// Add script for checking
packageJSON.scripts = Object.assign(packageJSON.scripts, {
"validate": "svelte-check"
})
// 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 preprocess to the svelte config, this is tricky because there's no easy signifier.
// Instead we look for `css:` then the next `}` and add the preprocessor to that
let foundCSS = false
let match
// https://regex101.com/r/OtNjwo/1
const configEditor = new RegExp(/css:.|\n*}/gmi)
while (( match = configEditor.exec(rollupConfig)) != null) {
if (foundCSS) {
const endOfCSSIndex = match.index + 1
rollupConfig = rollupConfig.slice(0, endOfCSSIndex) + ",\n preprocess: sveltePreprocess()," + rollupConfig.slice(endOfCSSIndex);
break
}
if (match[0].includes("css:")) foundCSS = true
}
// 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)
// 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"))
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.")
}

161
src/App.svelte Normal file
View File

@@ -0,0 +1,161 @@
<script>
import API, { graphqlOperation } from "@aws-amplify/api";
import awsconfig from "./aws-exports";
import { listTodos } from "./graphql/queries";
import { createTodo, deleteTodo, updateTodo } from "./graphql/mutations";
import { quintOut } from "svelte/easing";
import { crossfade } from "svelte/transition";
import { flip } from "svelte/animate";
API.configure(awsconfig);
const [send, receive] = crossfade({
fallback(node, params) {
const style = getComputedStyle(node);
const transform = style.transform === "none" ? "" : style.transform;
return {
duration: 600,
easing: quintOut,
css: (t) => `
transform: ${transform} scale(${t});
opacity: ${t}
`,
};
},
});
let todos = [];
let uid = todos.length + 1;
import { onMount } from "svelte";
function fetchList() {
return API.graphql(graphqlOperation(listTodos)).then(({ data }) => {
console.log({ data });
todos = data.listTodos.items || [];
});
}
onMount(fetchList);
function add(input) {
const todo = {
// id: uid++,
done: false,
description: input.value,
};
todos = [todo, ...todos];
input.value = "";
return API.graphql(graphqlOperation(createTodo, { input: todo }));
}
function remove(todo) {
console.log(todo);
return API.graphql(graphqlOperation(deleteTodo, { input: { id: todo.id } })).then(fetchList);
}
function mark(todo, done) {
todo.done = done;
return API.graphql(
graphqlOperation(updateTodo, {
input: {
id: todo.id,
done: todo.done,
},
})
).then(fetchList);
}
</script>
<style>
.new-todo {
font-size: 1.4em;
width: 100%;
margin: 2em 0 1em 0;
}
.board {
max-width: 36em;
margin: 0 auto;
}
.left,
.right {
float: left;
width: 50%;
padding: 0 1em 0 0;
box-sizing: border-box;
}
h2 {
font-size: 2em;
font-weight: 200;
user-select: none;
}
label {
top: 0;
left: 0;
display: block;
font-size: 1em;
line-height: 1;
padding: 0.5em;
margin: 0 auto 0.5em auto;
border-radius: 2px;
background-color: #eee;
user-select: none;
}
input {
margin: 0;
}
.right label {
background-color: rgb(180, 240, 100);
}
button {
float: right;
height: 1em;
box-sizing: border-box;
padding: 0 0.5em;
line-height: 1;
background-color: transparent;
border: none;
color: rgb(170, 30, 30);
opacity: 0;
transition: opacity 0.2s;
}
label:hover button {
opacity: 1;
}
</style>
<div class="board">
<input
class="new-todo"
placeholder="what needs to be done?"
on:keydown={(event) => event.key === 'Enter' && add(event.target)} />
<div class="left">
<h2>todo</h2>
{#each todos.filter((t) => !t.done) as todo (todo.id)}
<label in:receive={{ key: todo.id }} out:send={{ key: todo.id }} animate:flip>
<input type="checkbox" bind:checked={todo.done} on:change={() => mark(todo, todo.done)} />
{todo.description}
<button on:click={() => remove(todo)}>x</button>
</label>
{/each}
</div>
<div class="right">
<h2>done</h2>
{#each todos.filter((t) => t.done) as todo (todo.id)}
<label in:receive={{ key: todo.id }} out:send={{ key: todo.id }} animate:flip>
<input type="checkbox" bind:checked={todo.done} on:change={() => mark(todo, todo.done)} />
{todo.description}
<button on:click={() => remove(todo)}>x</button>
</label>
{/each}
</div>
</div>

45
src/graphql/mutations.js Normal file
View File

@@ -0,0 +1,45 @@
/* eslint-disable */
// this is an auto generated file. This will be overwritten
export const createTodo = /* GraphQL */ `
mutation CreateTodo(
$input: CreateTodoInput!
$condition: ModelTodoConditionInput
) {
createTodo(input: $input, condition: $condition) {
id
done
description
createdAt
updatedAt
}
}
`;
export const updateTodo = /* GraphQL */ `
mutation UpdateTodo(
$input: UpdateTodoInput!
$condition: ModelTodoConditionInput
) {
updateTodo(input: $input, condition: $condition) {
id
done
description
createdAt
updatedAt
}
}
`;
export const deleteTodo = /* GraphQL */ `
mutation DeleteTodo(
$input: DeleteTodoInput!
$condition: ModelTodoConditionInput
) {
deleteTodo(input: $input, condition: $condition) {
id
done
description
createdAt
updatedAt
}
}
`;

32
src/graphql/queries.js Normal file
View File

@@ -0,0 +1,32 @@
/* eslint-disable */
// this is an auto generated file. This will be overwritten
export const getTodo = /* GraphQL */ `
query GetTodo($id: ID!) {
getTodo(id: $id) {
id
done
description
createdAt
updatedAt
}
}
`;
export const listTodos = /* GraphQL */ `
query ListTodos(
$filter: ModelTodoFilterInput
$limit: Int
$nextToken: String
) {
listTodos(filter: $filter, limit: $limit, nextToken: $nextToken) {
items {
id
done
description
createdAt
updatedAt
}
nextToken
}
}
`;

2192
src/graphql/schema.json Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,36 @@
/* eslint-disable */
// this is an auto generated file. This will be overwritten
export const onCreateTodo = /* GraphQL */ `
subscription OnCreateTodo {
onCreateTodo {
id
done
description
createdAt
updatedAt
}
}
`;
export const onUpdateTodo = /* GraphQL */ `
subscription OnUpdateTodo {
onUpdateTodo {
id
done
description
createdAt
updatedAt
}
}
`;
export const onDeleteTodo = /* GraphQL */ `
subscription OnDeleteTodo {
onDeleteTodo {
id
done
description
createdAt
updatedAt
}
}
`;

7
src/main.js Normal file
View File

@@ -0,0 +1,7 @@
import App from "./App.svelte";
const app = new App({
target: document.body,
});
export default app;

1338
yarn.lock Normal file

File diff suppressed because it is too large Load Diff