Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add wrapper scope van #10

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,4 @@
"email": "[email protected]"
},
"homepage": "https://vanjs.org/minivan"
}
}
8 changes: 7 additions & 1 deletion src/shared.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,10 @@ export interface VanObj {
readonly add: Function;
readonly tags: Record<string, Function> & ((namespaceURI: string) => Record<string, Function>);
}
export {};

export declare function getVan(): VanObj
export declare function vanWrap<T>(van: VanObj, cb: (van: VanObj) => T): T
export declare function vanWrapper<CB extends (...opts: any[]) => any>(cb: CB): CB

type removeFromGlobal = () => void
export declare function useGlobalVan(cb: VanObj): removeFromGlobal
31 changes: 30 additions & 1 deletion src/shared.js
Original file line number Diff line number Diff line change
@@ -1 +1,30 @@
export {};
const ctx = [];

export function getVan() {
const van = ctx[ctx.length - 1];
if (van) {
return van;
}
throw new Error('getVan() must be called in a wrapper function')
}

export function vanWrap(van, cb) {
ctx.push(van);
try {
const ret = cb(van);
return ret;
} finally {
ctx.pop();
}
}


export function vanWrapper(cb) {
const van = getVan();
return (...opt) => vanWrap(van, () => cb(...opt));
}

export function useGlobalVan(van) {
ctx.push(van);
return () => ctx.splice(ctx.indexOf(van), 1);
}
7 changes: 7 additions & 0 deletions src/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,10 @@ export interface VanObj {
readonly add: Function
readonly tags: Record<string, Function> & ((namespaceURI: string) => Record<string, Function>)
}

export declare function getVan(): VanObj
export declare function vanWrap<T>(van: VanObj, cb: (van: VanObj) => T): T
export declare function vanWrapper<CB extends (...opts: any[]) => any>(cb: CB): CB

type removeFromGlobal = () => void
export declare function useGlobalVan(cb: VanObj): removeFromGlobal