From 7ee67bbcd7f484cf2610cbff5406fd711bf00779 Mon Sep 17 00:00:00 2001 From: swyx Date: Sun, 1 Nov 2020 22:08:57 +0800 Subject: [PATCH] readme --- .gitignore | 118 ++++++++++++++++++++++++++++++++++++++++ LICENSE | 21 ++++++++ README.md | 58 ++++++++++++++++++++ package-lock.json | 20 +++++++ package.json | 32 +++++++++++ src/index.ts | 135 ++++++++++++++++++++++++++++++++++++++++++++++ tsconfig.json | 69 ++++++++++++++++++++++++ 7 files changed, 453 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 README.md create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 src/index.ts create mode 100644 tsconfig.json diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..99aa2c6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,118 @@ +dist + +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +lerna-debug.log* + +# Diagnostic reports (https://nodejs.org/api/report.html) +report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json + +# Runtime data +pids +*.pid +*.seed +*.pid.lock + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage +*.lcov + +# nyc test coverage +.nyc_output + +# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# Bower dependency directory (https://bower.io/) +bower_components + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (https://nodejs.org/api/addons.html) +build/Release + +# Dependency directories +node_modules/ +jspm_packages/ + +# Snowpack dependency directory (https://snowpack.dev/) +web_modules/ + +# TypeScript cache +*.tsbuildinfo + +# Optional npm cache directory +.npm + +# Optional eslint cache +.eslintcache + +# Microbundle cache +.rpt2_cache/ +.rts2_cache_cjs/ +.rts2_cache_es/ +.rts2_cache_umd/ + +# Optional REPL history +.node_repl_history + +# Output of 'npm pack' +*.tgz + +# Yarn Integrity file +.yarn-integrity + +# dotenv environment variables file +.env +.env.test + +# parcel-bundler cache (https://parceljs.org/) +.cache +.parcel-cache + +# Next.js build output +.next +out + +# Nuxt.js build / generate output +.nuxt +dist + +# Gatsby files +.cache/ +# Comment in the public line in if your project uses Gatsby and not Next.js +# https://nextjs.org/blog/next-9-1#public-directory-support +# public + +# vuepress build output +.vuepress/dist + +# Serverless directories +.serverless/ + +# FuseBox cache +.fusebox/ + +# DynamoDB Local files +.dynamodb/ + +# TernJS port file +.tern-port + +# Stores VSCode versions used for testing VSCode extensions +.vscode-test + +# yarn v2 +.yarn/cache +.yarn/unplugged +.yarn/build-state.yml +.yarn/install-state.gz +.pnp.* diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..449c902 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License Copyright (c) 2020 swyx + +Permission is hereby granted, free of +charge, to any person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice +(including the next paragraph) shall be included in all copies or substantial +portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO +EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR +OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..4a69f0b --- /dev/null +++ b/README.md @@ -0,0 +1,58 @@ +# svelte-actions + +prototype svelte actions for inclusion into official actions + +See RFC: https://github.com/sveltejs/rfcs/pull/24 + +do not rely on this library yet! + +## Included Actions + +### `clickOutside` + +to be completed + +### `longpress` + +`export function longpress(node: HTMLElement, duration: number): ReturnType` + +Creates `longpress` event when mousedown above `duration` milliseconds. + +Demo: https://svelte.dev/tutorial/adding-parameters-to-actions + +```svelte + + + +``` + +### `pannable` + +`export function pannable(node: HTMLElement): ReturnType` + +Creates `panStart`, `panMove`, `panEnd` events so you can drag elements. Demo: https://svelte.dev/tutorial/actions + +### `lazyLoad` + +`export function lazyLoad(node: HTMLElement, attributes: Object): ReturnType` + +Lazily attach properties to any DOM element when it is in the window. Useful for lazy loading images, and other properties. + +Demo: https://svelte.dev/repl/f12988de576b4bf9b541a2a59eb838f6?version=3.23.2 + +```svelte + + + +``` + + +## Actions for Consideration + +- `closeOnEscape`/`closeOnScroll`/`closeOnFocusOutside`: https://github.com/sveltejs/rfcs/pull/24#issuecomment-645094235 +- `selectTextOnFocus`/`clearTextOnEscape`/`blurOnEscape`/`blurOnEnter`: +- `viewport`: creates `enterViewport`/`leaveViewport` events https://github.com/sveltejs/rfcs/pull/24#issuecomment-645392769 \ No newline at end of file diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..2d34003 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,20 @@ +{ + "name": "svelte-actions", + "version": "1.0.0", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "svelte": { + "version": "3.29.4", + "resolved": "https://registry.npmjs.org/svelte/-/svelte-3.29.4.tgz", + "integrity": "sha512-oW0fGHlyFFMvzRtIvOs84b0fOc0gmZNQcL5Is3hxuTpvaYX3pfd8oHy4KnOvbq4Ca6SG6AHdRMk7OhApTo0NqA==", + "dev": true + }, + "typescript": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.0.5.tgz", + "integrity": "sha512-ywmr/VrTVCmNTJ6iV2LwIrfG1P+lv6luD8sUJs+2eI9NLGigaN+nUQc13iHqisq7bra9lnmUSYqbJvegraBOPQ==", + "dev": true + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..795c323 --- /dev/null +++ b/package.json @@ -0,0 +1,32 @@ +{ + "name": "svelte-actions", + "version": "0.0.1", + "module": "dist/index.mjs", + "main": "dist/index.js", + "types": "dist/index.d.ts", + "scripts": { + "build": "tsc" + }, + "keywords": [ + "svelte" + ], + "files": [ + "src", + "dist" + ], + "author": "swyx", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/sw-yx/svelte-actions.git" + }, + "bugs": { + "url": "https://github.com/sw-yx/svelte-actions/issues" + }, + "homepage": "https://github.com/sw-yx/svelte-actions#readme", + "description": "", + "devDependencies": { + "svelte": "^3.29.4", + "typescript": "^4.0.5" + } +} diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 0000000..56eb6d4 --- /dev/null +++ b/src/index.ts @@ -0,0 +1,135 @@ +type Action = (node: HTMLElement, parameters: any) => { + update?: (parameters: any) => void, + destroy?: () => void +} + + +// export function clickOutside(): ReturnType { + +// } + + +/** + * Creates `longpress` event when mousedown above `duration` milliseconds. + * + * Usage: + * + * + * + * Demo: https://svelte.dev/tutorial/adding-parameters-to-actions + */ +export function longpress(node: HTMLElement, duration: number): ReturnType { + let timer: number; + + const handleMousedown = () => { + timer = setTimeout(() => { + node.dispatchEvent( + new CustomEvent('longpress') + ); + }, duration); + }; + + const handleMouseup = () => { + clearTimeout(timer) + }; + + node.addEventListener('mousedown', handleMousedown); + node.addEventListener('mouseup', handleMouseup); + + return { + update(newDuration) { + duration = newDuration; + }, + destroy() { + node.removeEventListener('mousedown', handleMousedown); + node.removeEventListener('mouseup', handleMouseup); + } + }; +} + +/** + * Creates panStart, panMove, panEnd events so you can drag elements. + * + * Demo: https://svelte.dev/tutorial/actions + * + */ +export function pannable(node: HTMLElement): ReturnType { + let x: number; + let y: number; + + function handleMousedown(event: MouseEvent) { + x = event.clientX; + y = event.clientY; + + node.dispatchEvent(new CustomEvent('panstart', { + detail: { x, y } + })); + + window.addEventListener('mousemove', handleMousemove); + window.addEventListener('mouseup', handleMouseup); + } + + function handleMousemove(event: MouseEvent) { + const dx = event.clientX - x; + const dy = event.clientY - y; + x = event.clientX; + y = event.clientY; + + node.dispatchEvent(new CustomEvent('panmove', { + detail: { x, y, dx, dy } + })); + } + + function handleMouseup(event: MouseEvent) { + x = event.clientX; + y = event.clientY; + + node.dispatchEvent(new CustomEvent('panend', { + detail: { x, y } + })); + + window.removeEventListener('mousemove', handleMousemove); + window.removeEventListener('mouseup', handleMouseup); + } + + node.addEventListener('mousedown', handleMousedown); + + return { + destroy() { + node.removeEventListener('mousedown', handleMousedown); + } + }; +} + + +/** + * Attach onto any image to lazy load it + * + * + * + * Demo: https://svelte.dev/repl/f12988de576b4bf9b541a2a59eb838f6?version=3.23.2 + * + */ +export function lazyLoad(node: HTMLElement, attributes: Object): ReturnType { + let intersecting = false; + + const handleIntersection: IntersectionObserverCallback = (entries) => { + intersecting = entries[0].isIntersecting; + if (entries[0].intersectionRatio > 0) { + Object.assign(node, attributes) + } + if (intersecting) { + observer.unobserve(node); + } + } + const observer = new IntersectionObserver(handleIntersection); + observer.observe(node); + return { + destroy() { + observer.unobserve(node); + } + }; +} \ No newline at end of file diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..e39eeee --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,69 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig.json to read more about this file */ + + /* Basic Options */ + // "incremental": true, /* Enable incremental compilation */ + "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */ + "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */ + "lib": ["esnext", "dom"], /* Specify library files to be included in the compilation. */ + // "allowJs": true, /* Allow javascript files to be compiled. */ + // "checkJs": true, /* Report errors in .js files. */ + // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ + "declaration": true, /* Generates corresponding '.d.ts' file. */ + // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ + // "sourceMap": true, /* Generates corresponding '.map' file. */ + // "outFile": "./", /* Concatenate and emit output to single file. */ + "outDir": "dist", /* Redirect output structure to the directory. */ + // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ + // "composite": true, /* Enable project compilation */ + // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ + // "removeComments": true, /* Do not emit comments to output. */ + // "noEmit": true, /* Do not emit outputs. */ + // "importHelpers": true, /* Import emit helpers from 'tslib'. */ + // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ + // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ + + /* Strict Type-Checking Options */ + "strict": true, /* Enable all strict type-checking options. */ + // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ + // "strictNullChecks": true, /* Enable strict null checks. */ + // "strictFunctionTypes": true, /* Enable strict checking of function types. */ + // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ + // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ + // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ + // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ + + /* Additional Checks */ + // "noUnusedLocals": true, /* Report errors on unused locals. */ + // "noUnusedParameters": true, /* Report errors on unused parameters. */ + // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ + // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ + + /* Module Resolution Options */ + // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ + // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ + // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ + // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ + // "typeRoots": [], /* List of folders to include type definitions from. */ + // "types": [], /* Type declaration files to be included in compilation. */ + // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ + "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ + // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ + // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ + + /* Source Map Options */ + // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ + // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ + // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ + // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ + + /* Experimental Options */ + // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ + // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ + + /* Advanced Options */ + "skipLibCheck": true, /* Skip type checking of declaration files. */ + "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ + } +}