convert everything to TypeScript

pull/2842/head
Bogdan Savluk 5 years ago
parent fc4be88646
commit c29c389a72

10
.gitignore vendored

@ -4,14 +4,14 @@
node_modules
*.map
/src/compile/internal-exports.ts
/compiler.js
/index.js
/compiler.*
/index.*
/internal.*
/store.*
/easing.js
/easing.*
/motion.*
/transition.js
/animate.js
/transition.*
/animate.*
/scratch/
/coverage/
/coverage.lcov/

@ -1,10 +0,0 @@
export {
onMount,
onDestroy,
beforeUpdate,
afterUpdate,
setContext,
getContext,
tick,
createEventDispatcher
} from './internal';

@ -30,7 +30,7 @@
"prepare": "npm run build && npm run tsd",
"dev": "rollup -cw",
"pretest": "npm run build",
"posttest": "agadoo src/internal/index.js",
"posttest": "agadoo internal.mjs",
"prepublishOnly": "export PUBLISH=true && npm run lint && npm test",
"tsd": "tsc -d src/store.ts --outDir .",
"typecheck": "tsc --noEmit"

@ -9,10 +9,19 @@ import pkg from './package.json';
const is_publish = !!process.env.PUBLISH;
const tsPlugin = is_publish
? typescript({
include: 'src/**',
typescript: require('typescript')
})
: sucrase({
transforms: ['typescript']
});
export default [
/* internal.[m]js */
{
input: `src/internal/index.js`,
input: `src/internal/index.ts`,
output: [
{
file: `internal.mjs`,
@ -26,19 +35,22 @@ export default [
}
],
external: id => id.startsWith('svelte/'),
plugins: [{
generateBundle(options, bundle) {
const mod = bundle['internal.mjs'];
if (mod) {
fs.writeFileSync('src/compile/internal-exports.ts', `// This file is automatically generated\nexport default new Set(${JSON.stringify(mod.exports)});`);
plugins: [
tsPlugin,
{
generateBundle(options, bundle) {
const mod = bundle['internal.mjs'];
if (mod) {
fs.writeFileSync('src/compile/internal-exports.ts', `// This file is automatically generated\nexport default new Set(${JSON.stringify(mod.exports)});`);
}
}
}
}]
}]
},
/* compiler.js */
{
input: 'src/index.ts',
input: 'src/compiler.ts',
plugins: [
replace({
__VERSION__: pkg.version
@ -48,15 +60,7 @@ export default [
include: ['node_modules/**']
}),
json(),
is_publish
? typescript({
include: 'src/**',
exclude: 'src/internal/**',
typescript: require('typescript')
})
: sucrase({
transforms: ['typescript']
})
tsPlugin
],
output: {
file: 'compiler.js',
@ -71,7 +75,7 @@ export default [
/* motion.mjs */
{
input: `src/motion/index.js`,
input: `src/motion/index.ts`,
output: [
{
file: `motion.mjs`,
@ -84,46 +88,30 @@ export default [
paths: id => id.startsWith('svelte/') && id.replace('svelte', '.')
}
],
plugins: [
tsPlugin
],
external: id => id.startsWith('svelte/')
},
/* store.mjs */
{
input: `src/store.ts`,
// everything else
...['index', 'easing', 'transition', 'animate', 'store'].map(name => ({
input: `src/${name}.ts`,
output: [
{
file: `store.mjs`,
file: `${name}.mjs`,
format: 'esm',
paths: id => id.startsWith('svelte/') && id.replace('svelte', '.')
},
{
file: `store.js`,
file: `${name}.js`,
format: 'cjs',
paths: id => id.startsWith('svelte/') && id.replace('svelte', '.')
}
],
plugins: [
is_publish
? typescript({
include: 'src/**',
exclude: 'src/internal/**',
typescript: require('typescript')
})
: sucrase({
transforms: ['typescript']
})
tsPlugin
],
external: id => id.startsWith('svelte/')
},
// everything else
...['index', 'easing', 'transition', 'animate'].map(name => ({
input: `${name}.mjs`,
output: {
file: `${name}.js`,
format: 'cjs',
paths: id => id.startsWith('svelte/') && id.replace('svelte', '.')
},
external: id => id !== `${name}.mjs`
}))
];

@ -1,5 +1,5 @@
import { cubicOut } from './easing';
import { is_function } from './internal';
import { cubicOut } from 'svelte/easing';
import { is_function } from 'svelte/internal';
export function flip(node, animation, params) {
const style = getComputedStyle(node);
@ -22,4 +22,4 @@ export function flip(node, animation, params) {
easing,
css: (t, u) => `transform: ${transform} translate(${u * dx}px, ${u * dy}px);`
};
}
}

@ -1,4 +1,4 @@
import { assign } from '../internal';
import { assign } from '../internal/index';
import Stats from '../Stats';
import parse from '../parse/index';
import render_dom from './render-dom/index';

@ -0,0 +1,6 @@
export { default as compile } from './compile/index';
export { default as parse } from './parse/index';
export { default as preprocess } from './preprocess/index';
export { walk } from 'estree-walker';
export const VERSION = '__VERSION__';

@ -3,7 +3,7 @@ Adapted from https://github.com/mattdesl
Distributed under MIT License https://github.com/mattdesl/eases/blob/master/LICENSE.md
*/
export { identity as linear } from './internal';
export { identity as linear } from 'svelte/internal';
export function backInOut(t) {
const s = 1.70158 * 1.525;

@ -1,6 +1,10 @@
export { default as compile } from './compile/index';
export { default as parse } from './parse/index';
export { default as preprocess } from './preprocess/index';
export { walk } from 'estree-walker';
export const VERSION = '__VERSION__';
export {
onMount,
onDestroy,
beforeUpdate,
afterUpdate,
setContext,
getContext,
tick,
createEventDispatcher
} from 'svelte/internal';

@ -1,7 +1,23 @@
import { add_render_callback, flush, schedule_update, dirty_components } from './scheduler.js';
import { current_component, set_current_component } from './lifecycle.js';
import { blank_object, is_function, run, run_all, noop } from './utils.js';
import { children } from './dom.js';
import { add_render_callback, flush, schedule_update, dirty_components } from './scheduler';
import { current_component, set_current_component } from './lifecycle';
import { blank_object, is_function, run, run_all, noop } from './utils';
import { children } from './dom';
interface T$$ {
dirty: null;
ctx: null|any;
bound: any;
update: () => void;
callbacks: any;
after_render: any[];
props: any;
fragment: null|any;
not_equal: any;
before_render: any[];
context: Map<any, any>;
on_mount: any[];
on_destroy: any[]
}
export function bind(component, name, callback) {
if (component.$$.props.indexOf(name) === -1) return;
@ -59,7 +75,7 @@ export function init(component, options, instance, create_fragment, not_equal, p
const props = options.props || {};
const $$ = component.$$ = {
const $$: T$$ = component.$$ = {
fragment: null,
ctx: null,
@ -99,9 +115,9 @@ export function init(component, options, instance, create_fragment, not_equal, p
if (options.target) {
if (options.hydrate) {
$$.fragment.l(children(options.target));
$$.fragment!.l(children(options.target));
} else {
$$.fragment.c();
$$.fragment!.c();
}
if (options.intro && component.$$.fragment.i) component.$$.fragment.i();
@ -115,13 +131,16 @@ export function init(component, options, instance, create_fragment, not_equal, p
export let SvelteElement;
if (typeof HTMLElement !== 'undefined') {
SvelteElement = class extends HTMLElement {
$$: T$$;
constructor() {
super();
this.attachShadow({ mode: 'open' });
}
connectedCallback() {
// @ts-ignore todo: improve typings
for (const key in this.$$.slotted) {
// @ts-ignore todo: improve typings
this.appendChild(this.$$.slotted[key]);
}
}
@ -153,6 +172,8 @@ if (typeof HTMLElement !== 'undefined') {
}
export class SvelteComponent {
$$: T$$;
$destroy() {
destroy(this, true);
this.$destroy = noop;

@ -1,6 +1,6 @@
import { identity as linear, noop, now } from './utils.js';
import { loop } from './loop.js';
import { create_rule, delete_rule } from './style_manager.js';
import { identity as linear, noop, now } from './utils';
import { loop } from './loop';
import { create_rule, delete_rule } from './style_manager';
export function create_animation(node, from, fn, params) {
if (!from) return noop;
@ -90,4 +90,4 @@ export function fix_position(node) {
node.style.transform = `${transform} translate(${a.left - b.left}px, ${a.top - b.top}px)`;
}
}
}
}

@ -1,11 +1,11 @@
import { assign, is_promise } from './utils.js';
import { check_outros, group_outros, on_outro } from './transitions.js';
import { flush } from '../internal/scheduler.js';
import { assign, is_promise } from './utils';
import { check_outros, group_outros, on_outro } from './transitions';
import { flush } from '../internal/scheduler';
export function handle_promise(promise, info) {
const token = info.token = {};
function update(type, index, key, value) {
function update(type, index, key?, value?) {
if (info.token !== token) return;
info.resolved = key && { [key]: value };
@ -61,4 +61,4 @@ export function handle_promise(promise, info) {
info.resolved = { [info.value]: promise };
}
}
}

@ -1,28 +1,28 @@
export function append(target, node) {
export function append(target:Node, node:Node) {
target.appendChild(node);
}
export function insert(target, node, anchor) {
export function insert(target: Node, node: Node, anchor?:Node) {
target.insertBefore(node, anchor || null);
}
export function detach(node) {
export function detach(node: Node) {
node.parentNode.removeChild(node);
}
export function detach_between(before, after) {
export function detach_between(before: Node, after: Node) {
while (before.nextSibling && before.nextSibling !== after) {
before.parentNode.removeChild(before.nextSibling);
}
}
export function detach_before(after) {
export function detach_before(after:Node) {
while (after.previousSibling) {
after.parentNode.removeChild(after.previousSibling);
}
}
export function detach_after(before) {
export function detach_after(before:Node) {
while (before.nextSibling) {
before.parentNode.removeChild(before.nextSibling);
}
@ -34,25 +34,30 @@ export function destroy_each(iterations, detaching) {
}
}
export function element(name) {
return document.createElement(name);
export function element<K extends keyof HTMLElementTagNameMap>(name: K) {
return document.createElement<K>(name);
}
export function object_without_properties(obj, exclude) {
const target = {};
export function object_without_properties<T,K extends keyof T>(obj:T, exclude: K[]) {
const target = {} as Pick<T, Exclude<keyof T, K>>;
for (const k in obj) {
if (Object.prototype.hasOwnProperty.call(obj, k) && exclude.indexOf(k) === -1) {
if (
Object.prototype.hasOwnProperty.call(obj, k)
// @ts-ignore
&& exclude.indexOf(k) === -1
) {
// @ts-ignore
target[k] = obj[k];
}
}
return target;
}
export function svg_element(name) {
export function svg_element(name:string):SVGElement {
return document.createElementNS('http://www.w3.org/2000/svg', name);
}
export function text(data) {
export function text(data:string) {
return document.createTextNode(data);
}
@ -64,7 +69,7 @@ export function empty() {
return text('');
}
export function listen(node, event, handler, options) {
export function listen(node: Node, event: string, handler: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions | EventListenerOptions) {
node.addEventListener(event, handler, options);
return () => node.removeEventListener(event, handler, options);
}
@ -72,6 +77,7 @@ export function listen(node, event, handler, options) {
export function prevent_default(fn) {
return function(event) {
event.preventDefault();
// @ts-ignore
return fn.call(this, event);
};
}
@ -79,16 +85,17 @@ export function prevent_default(fn) {
export function stop_propagation(fn) {
return function(event) {
event.stopPropagation();
// @ts-ignore
return fn.call(this, event);
};
}
export function attr(node, attribute, value) {
export function attr(node: Element, attribute: string, value?: string) {
if (value == null) node.removeAttribute(attribute);
else node.setAttribute(attribute, value);
}
export function set_attributes(node, attributes) {
export function set_attributes(node: HTMLElement, attributes: { [x: string]: string; }) {
for (const key in attributes) {
if (key === 'style') {
node.style.cssText = attributes[key];
@ -243,8 +250,8 @@ export function toggle_class(element, name, toggle) {
element.classList[toggle ? 'add' : 'remove'](name);
}
export function custom_event(type, detail) {
const e = document.createEvent('CustomEvent');
export function custom_event<T=any>(type: string, detail?: T) {
const e: CustomEvent<T> = document.createEvent('CustomEvent');
e.initCustomEvent(type, false, false, detail);
return e;
}

@ -1,12 +0,0 @@
export * from './animations.js';
export * from './await-block.js';
export * from './dom.js';
export * from './keyed-each.js';
export * from './lifecycle.js';
export * from './loop.js';
export * from './scheduler.js';
export * from './spread.js';
export * from './ssr.js';
export * from './transitions.js';
export * from './utils.js';
export * from './Component.js';

@ -0,0 +1,12 @@
export * from './animations';
export * from './await-block';
export * from './dom';
export * from './keyed-each';
export * from './lifecycle';
export * from './loop';
export * from './scheduler';
export * from './spread';
export * from './ssr';
export * from './transitions';
export * from './utils';
export * from './Component';

@ -1,4 +1,4 @@
import { on_outro } from './transitions.js';
import { on_outro } from './transitions';
export function destroy_block(block, lookup) {
block.d(1);
@ -110,4 +110,4 @@ export function measure(blocks) {
let i = blocks.length;
while (i--) rects[blocks[i].key] = blocks[i].node.getBoundingClientRect();
return rects;
}
}

@ -1,4 +1,6 @@
import { now } from './utils.js';
import { now } from './utils';
export interface Task { abort(): void; promise: Promise<undefined> }
const tasks = new Set();
let running = false;
@ -21,7 +23,7 @@ export function clear_loops() {
running = false;
}
export function loop(fn) {
export function loop(fn: (number)=>void): Task {
let task;
if (!running) {
@ -30,11 +32,11 @@ export function loop(fn) {
}
return {
promise: new Promise(fulfil => {
promise: new Promise<undefined>(fulfil => {
tasks.add(task = [fn, fulfil]);
}),
abort() {
tasks.delete(task);
}
};
}
}

@ -1,5 +1,5 @@
import { run_all } from './utils.js';
import { set_current_component } from './lifecycle.js';
import { run_all } from './utils';
import { set_current_component } from './lifecycle';
export const dirty_components = [];
export const intros = { enabled: false };

@ -1,5 +1,5 @@
import { set_current_component, current_component } from './lifecycle.js';
import { run_all, blank_object } from './utils.js';
import { set_current_component, current_component } from './lifecycle';
import { run_all, blank_object } from './utils';
export const invalid_attribute_name_character = /[\s'">/=\u{FDD0}-\u{FDEF}\u{FFFE}\u{FFFF}\u{1FFFE}\u{1FFFF}\u{2FFFE}\u{2FFFF}\u{3FFFE}\u{3FFFF}\u{4FFFE}\u{4FFFF}\u{5FFFE}\u{5FFFF}\u{6FFFE}\u{6FFFF}\u{7FFFE}\u{7FFFF}\u{8FFFE}\u{8FFFF}\u{9FFFE}\u{9FFFF}\u{AFFFE}\u{AFFFF}\u{BFFFE}\u{BFFFF}\u{CFFFE}\u{CFFFF}\u{DFFFE}\u{DFFFF}\u{EFFFE}\u{EFFFF}\u{FFFFE}\u{FFFFF}\u{10FFFE}\u{10FFFF}]/u;
// https://html.spec.whatwg.org/multipage/syntax.html#attributes-2
@ -117,4 +117,4 @@ export function get_store_value(store) {
let value;
store.subscribe(_ => value = _)();
return value;
}
}

@ -1,4 +1,4 @@
import { element } from './dom.js';
import { element } from './dom';
let stylesheet;
let active = 0;
@ -43,7 +43,7 @@ export function create_rule(node, a, b, duration, delay, ease, fn, uid = 0) {
return name;
}
export function delete_rule(node, name) {
export function delete_rule(node, name?) {
node.style.animation = (node.style.animation || '')
.split(', ')
.filter(name
@ -62,4 +62,4 @@ export function clear_rules() {
while (i--) stylesheet.deleteRule(i);
current_rules = {};
});
}
}

@ -1,8 +1,8 @@
import { identity as linear, noop, now, run_all } from './utils.js';
import { loop } from './loop.js';
import { create_rule, delete_rule } from './style_manager.js';
import { custom_event } from './dom.js';
import { add_render_callback } from './scheduler.js';
import { identity as linear, noop, now, run_all } from './utils';
import { loop } from './loop';
import { create_rule, delete_rule } from './style_manager';
import { custom_event } from './dom';
import { add_render_callback } from './scheduler';
let promise;
@ -229,6 +229,7 @@ export function create_bidirectional_transition(node, fn, params, intro) {
};
if (!b) {
// @ts-ignore todo: improve typings
program.group = outros;
outros.remaining += 1;
}
@ -309,4 +310,4 @@ export function create_bidirectional_transition(node, fn, params, intro) {
running_program = pending_program = null;
}
};
}
}

@ -80,11 +80,11 @@ export function exclude_internal_props(props) {
return result;
}
export let now = typeof window !== 'undefined'
export let now: () => number = typeof window !== 'undefined'
? () => window.performance.now()
: () => Date.now();
// used internally for testing
export function set_now(fn) {
now = fn;
}
}

@ -1,2 +0,0 @@
export * from './spring.js';
export * from './tweened.js';

@ -0,0 +1,2 @@
export * from './spring';
export * from './tweened';

@ -1,6 +1,6 @@
import { writable } from 'svelte/store'; // eslint-disable-line import/no-unresolved
import { loop, now } from 'svelte/internal'; // eslint-disable-line import/no-unresolved
import { is_date } from './utils.js';
import { Readable, writable } from 'svelte/store';
import { loop, now, Task } from 'svelte/internal';
import { is_date } from './utils';
function tick_spring(ctx, last_value, current_value, target_value) {
if (typeof current_value === 'number' || is_date(current_value)) {
@ -27,25 +27,41 @@ function tick_spring(ctx, last_value, current_value, target_value) {
next_value[k] = tick_spring(ctx, last_value[k], current_value[k], target_value[k]);
return next_value;
} else {
throw new Error(`Cannot spring ${typeof value} values`);
throw new Error(`Cannot spring ${typeof current_value} values`);
}
}
export function spring(value, opts = {}) {
interface SpringOpts {
stiffness?: number,
damping?: number,
precision?: number,
}
type SpringUpdateOpts = { hard?: any; soft?: string | number | boolean; };
interface Spring<T=any> extends Readable<T>{
set: (new_value: T, opts?: SpringUpdateOpts) => (Promise<T> | Promise<T>);
precision: number;
update: (fn, opts: SpringUpdateOpts) => Promise<T>;
damping: number;
stiffness: number
}
export function spring<T=any>(value: T, opts: SpringOpts = {}) {
const store = writable(value);
const { stiffness = 0.15, damping = 0.8, precision = 0.01 } = opts;
let last_time;
let task;
let current_token;
let last_value = value;
let target_value = value;
let last_time: number;
let task: Task;
let current_token: object;
let last_value:T = value;
let target_value:T = value;
let inv_mass = 1;
let inv_mass_recovery_rate = 0;
let cancel_task = false;
function set(new_value, opts = {}) {
function set(new_value: any, opts: SpringUpdateOpts={}) {
target_value = new_value;
const token = current_token = {};
@ -100,9 +116,9 @@ export function spring(value, opts = {}) {
});
}
const spring = {
const spring: Spring = {
set,
update: (fn, opts) => set(fn(target_value, value), opts),
update: (fn, opts:SpringUpdateOpts) => set(fn(target_value, value), opts),
subscribe: store.subscribe,
stiffness,
damping,

@ -1,7 +1,7 @@
import { writable } from 'svelte/store'; // eslint-disable-line import/no-unresolved
import { assign, loop, now } from 'svelte/internal'; // eslint-disable-line import/no-unresolved
import { linear } from 'svelte/easing'; // eslint-disable-line import/no-unresolved
import { is_date } from './utils.js';
import { is_date } from './utils';
function get_interpolator(a, b) {
if (a === b || a !== a) return () => a;
@ -109,4 +109,4 @@ export function tweened(value, defaults = {}) {
update: (fn, opts) => set(fn(target_value, value), opts),
subscribe: store.subscribe
};
}
}

@ -1,3 +1,3 @@
export function is_date(obj) {
export function is_date(obj: any) {
return Object.prototype.toString.call(obj) === '[object Date]';
}
}

@ -1,4 +1,4 @@
import { run_all, noop, safe_not_equal, is_function } from './internal/utils';
import { run_all, noop, safe_not_equal, is_function } from 'svelte/internal';
/** Callback to inform of a value updates. */
type Subscriber<T> = (value: T) => void;

@ -1,5 +1,5 @@
import { cubicOut, cubicInOut } from './easing';
import { assign, is_function } from './internal';
import { cubicOut, cubicInOut } from 'svelte/easing';
import { assign, is_function } from 'svelte/internal';
export function fade(node, {
delay = 0,
@ -179,4 +179,4 @@ export function crossfade({ fallback, ...defaults }) {
transition(to_send, to_receive, false),
transition(to_receive, to_send, true)
];
}
}

@ -54,4 +54,4 @@ export function add_indentation(code: MagicString, node: Node, levels = 1) {
code.appendLeft(index + 1, indent);
}
}
}

@ -7,12 +7,17 @@
"allowJs": true,
"lib": ["es5", "es6", "dom"],
"importHelpers": true,
"moduleResolution": "node"
"moduleResolution": "node",
"baseUrl": ".",
"paths": {
"svelte/*": ["./src/*"]
}
},
"include": [
"src"
],
"exclude": [
"./*.*js",
"node_modules"
]
}

Loading…
Cancel
Save