Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
40 commits
Select commit Hold shift + click to select a range
a441b74
Refactor repository
rustkas Nov 27, 2021
8692f60
Update README.md
rustkas Nov 27, 2021
b9e6a7e
Update README.md
rustkas Nov 27, 2021
391b6ce
Update README.md
rustkas Nov 27, 2021
0be590e
Update README.md
rustkas Nov 27, 2021
5556376
Как устроен Компонент в Svelte?
rustkas Nov 27, 2021
e107749
Update README.md
rustkas Nov 27, 2021
b856532
Жизненный цикл Svelte компонента
rustkas Nov 27, 2021
5a53665
Merge branch 'main' of https://github.com/rustkas/svelte-todo
rustkas Nov 27, 2021
67fbf82
add dots.
rustkas Nov 27, 2021
6af1375
Update README.md
rustkas Nov 27, 2021
e48ad31
Update README.md
rustkas Nov 27, 2021
06090e9
Update README.md
rustkas Nov 27, 2021
0dfcb61
Optimize phone numbers example code
rustkas Nov 27, 2021
ce7c276
Update README.md
rustkas Nov 27, 2021
5aa7990
HTML шаблоны в Svelte
rustkas Nov 29, 2021
9442e83
Как работать с событиями в Svelte?
rustkas Nov 29, 2021
3c33737
add item
rustkas Nov 29, 2021
1420ccc
Update README.md
rustkas Nov 29, 2021
ab58a0e
Update README.md
rustkas Nov 29, 2021
cc34bf9
Привязки (Bindings)
rustkas Nov 30, 2021
2f1b810
Merge branch 'main' of https://github.com/rustkas/svelte-todo
rustkas Nov 30, 2021
d00eb09
Update README.md
rustkas Nov 30, 2021
d965988
Update README.md
rustkas Nov 30, 2021
d06f090
Update README.md
rustkas Nov 30, 2021
b39b919
Хранилище (Store)
rustkas Dec 1, 2021
dcf6657
Анимации и переходы (Motion, Transition and Animation)
rustkas Dec 2, 2021
f739881
Update README.md
rustkas Dec 2, 2021
7043507
update example list
rustkas Dec 2, 2021
3a5fe24
Действия и директива use (Actions)
rustkas Dec 3, 2021
6989651
Update README.md
rustkas Dec 3, 2021
ac76785
Слоты - Svelte slots. Context Модуль.
rustkas Dec 4, 2021
abfebca
Update README.md
rustkas Dec 4, 2021
fe18b55
API контекста (Context API)
rustkas Dec 4, 2021
7c4f27a
Merge branch 'main' of https://github.com/rustkas/svelte-todo
rustkas Dec 4, 2021
db71583
Update README.md
rustkas Dec 4, 2021
0a40e78
update projects
rustkas Dec 4, 2021
2d93cac
Merge branch 'main' of https://github.com/rustkas/svelte-todo
rustkas Dec 4, 2021
1443886
Специальные элементы (Special elements)
rustkas Dec 5, 2021
e30ad28
remove unused project
rustkas Dec 5, 2021
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Действия и директива use (Actions)
  • Loading branch information
rustkas committed Dec 3, 2021
commit 3a5fe243c57b00657ba91d1cc1214f649bee2125
1 change: 1 addition & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@
6. [Привязки (Bindings).](projects/video06)
7. [Хранилище (Store).](projects/video07)
8. [Анимации и переходы (Motion, Transition and Animation).](projects/video08)
9. [Действия и директива use (Actions).](projects/video09)
17 changes: 17 additions & 0 deletions examples/projects/video09/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Действия и директива use (Actions)

[![Действия и директива use - Svelte Actions](https://img.youtube.com/vi/tx-o1QNHcCo/0.jpg)](https://youtu.be/tx-o1QNHcCo "Действия и директива use - Svelte Actions")

В этом видео рассматриваем действия в Svelte, для чего они нужно и как ими пользоваться. Добавляем в проект директиву `use`, отправляем события из Действия и реализовываем функции Действий - `destroy` и `update`.

Действие - это подолнительные возможности элементов. С их помощью можно вызывать всплывающие подсказки и реализовывать дополнительные действия.

## Команда запуска приложения
`npm run dev`

## Адрес приложения
`http://localhost:5000/`

## Примеры

1. [Пример №1](code/svelte-todo-01)
4 changes: 4 additions & 0 deletions examples/projects/video09/code/svelte-todo-01/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/node_modules/
/public/build/

.DS_Store
5 changes: 5 additions & 0 deletions examples/projects/video09/code/svelte-todo-01/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Действия.

Реализуем перемещение элемента по экрану с помощью мыши. На основе этого примера можно сделать загрузгу картинок методом drag-and-drop.

Действие описывается с помощью директивы `use`.
25 changes: 25 additions & 0 deletions examples/projects/video09/code/svelte-todo-01/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"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": {
"d3-interpolate": "^3.0.1",
"sirv-cli": "^1.0.0",
"uuid": "^8.3.2"
}
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
64 changes: 64 additions & 0 deletions examples/projects/video09/code/svelte-todo-01/public/global.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
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 changes: 18 additions & 0 deletions examples/projects/video09/code/svelte-todo-01/public/index.html
Original file line number Diff line number Diff line change
@@ -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 changes: 76 additions & 0 deletions examples/projects/video09/code/svelte-todo-01/rollup.config.js
Original file line number Diff line number Diff line change
@@ -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
}
};
Original file line number Diff line number Diff line change
@@ -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.")
}
Loading