Skip to content

Commit

Permalink
fix: types
Browse files Browse the repository at this point in the history
  • Loading branch information
chen season authored and chen season committed May 16, 2023
1 parent 98f0623 commit c16cf6e
Show file tree
Hide file tree
Showing 23 changed files with 5,112 additions and 4,022 deletions.
2 changes: 1 addition & 1 deletion .eslintrc.js → .eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ module.exports = {
},
overrides: [
{
files: ['*.js'],
files: ['**/*.js', '**/*.mjs', '**/*.cjs'],
// parser: '@babel/eslint-parser',
plugins: ['import', 'prettier'],
extends: [
Expand Down
File renamed without changes.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ import { InjectionContext } from 'pinia-di';
export const TestStore = ({ onUnmounted }: InjectionContext) => {
const useTestStore = defineStore(useStoreId('test'), () => {
const state = reactive({});
const dispose = async (isCreated) => {
const dispose = async () => {
console.log('dispose');
};

Expand Down
16 changes: 1 addition & 15 deletions dist/pinia-di.esm-browser.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

338 changes: 159 additions & 179 deletions dist/pinia-di.esm.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { getCurrentInstance, inject, provide, onUnmounted, defineComponent } from 'vue';
import { getActivePinia } from 'pinia';

/*! *****************************************************************************
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
Expand All @@ -14,196 +14,176 @@ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) {
return value instanceof P ? value : new P(function (resolve) {
resolve(value);
});
}
***************************************************************************** */
/* global Reflect, Promise */


function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}

return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
let injectorId = 0;
// service injector
class Injector {
constructor(providers, opts = {}) {
// injector id
this.id = '';
// injector nme
this.name = '';
// parent injector
this.parent = null;
// 当前 injector 上的服务记录
this.records = new Map();
const { parent = null, name = '' } = opts;
this.id = `${injectorId++}`;
this.name = name;
this.parent = parent;
// provider records
providers.forEach((provider) => {
let record = null;
if (typeof provider === 'object') {
record = Object.assign(Object.assign({}, provider), { disposes: [], disposeOnUnmounted: provider.disposeOnUnmounted !== false });
}
else if (typeof provider === 'function') {
// [class]
const p = provider;
record = {
creator: p,
disposes: [],
disposeOnUnmounted: true
};
}
if (!record) {
throw new Error(`Error provider onfig [${provider.$id || provider.toString()}]!`);
}
this.records.set(record.creator, record);
});
}

function rejected(value) {
try {
step(generator["throw"](value));
} catch (e) {
reject(e);
}
get(provide, args) {
const record = this.records.get(provide);
let store = null;
// not register on self
if (!record) {
if (this.parent)
store = this.parent.get(provide, args);
}
else {
// lazy init service
if (typeof record.use === 'undefined') {
this._initRecord(record);
}
store = (record === null || record === void 0 ? void 0 : record.use) ? record === null || record === void 0 ? void 0 : record.use() : null;
}
if (!store && !(args === null || args === void 0 ? void 0 : args.optional)) {
throw new Error(`Store<${provide.$id || provide.toString()}> not be provided, and not optional!`);
}
return store;
}

function step(result) {
result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
_initRecord(record) {
const ctx = {
getStore: (provide, opts) => {
return this.get(provide, opts);
},
onUnmounted: (fn) => {
record.disposes.push(fn);
const remove = () => {
const i = record.disposes.indexOf(fn);
if (i !== -1) {
record.disposes.splice(i, 1);
}
};
return remove;
},
useStoreId: (id) => {
return this.name
? `${id}~[${this.name}]~<${this.id}>`
: `${id}~<${this.id}>`;
}
};
record.use = record.creator(ctx);
}
dispose() {
return __awaiter(this, void 0, void 0, function* () {
const { records } = this;
const keys = records.keys();
for (const key of keys) {
const record = records.get(key);
if (!record || !record.use)
return;
const activePinia = getActivePinia();
if (!activePinia)
return;
// store created
const hasCreated = activePinia._s.has(record.use.$id);
if (!hasCreated)
return;
const disposes = (record === null || record === void 0 ? void 0 : record.disposes) || [];
for (const dispose of disposes) {
yield dispose();
}
record.use().$dispose();
}
});
}

step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}

let injectorId = 0;
// service injector
class Injector {
constructor(providers, opts = {}) {
// injector id
this.id = '';
// injector nme
this.name = '';
// parent injector
this.parent = null;
// 当前 injector 上的服务记录
this.records = new Map();
const { parent = null, name = '' } = opts;
this.id = `${injectorId++}`;
this.name = name;
this.parent = parent;
// provider records
providers.forEach((provider) => {
let record = null;
if (typeof provider === 'object') {
record = Object.assign(Object.assign({}, provider), { disposes: [], disposeOnUnmounted: provider.disposeOnUnmounted !== false });
}
else if (typeof provider === 'function') {
// [class]
const p = provider;
record = {
creator: p,
disposes: [],
disposeOnUnmounted: true
};
}
if (!record) {
throw new Error(`Error provider onfig [${provider.$id || provider.toString()}]!`);
}
this.records.set(record.creator, record);
});
}
get(provide, args) {
const record = this.records.get(provide);
let store = null;
// not register on self
if (!record) {
if (this.parent)
store = this.parent.get(provide, args);
}
else {
// lazy init service
if (typeof record.use === 'undefined') {
this._initRecord(record);
}
store = (record === null || record === void 0 ? void 0 : record.use) ? record === null || record === void 0 ? void 0 : record.use() : null;
}
if (!store && !(args === null || args === void 0 ? void 0 : args.optional)) {
throw new Error(`Store<${provide.$id || provide.toString()}> not be provided, and not optional!`);
}
return store;
}
_initRecord(record) {
const ctx = {
getStore: (provide, opts) => {
return this.get(provide, opts);
},
onUnmounted: (fn) => {
record.disposes.push(fn);
const remove = () => {
const i = record.disposes.indexOf(fn);
if (i !== -1) {
record.disposes.splice(i, 1);
}
};
return remove;
},
useStoreId: (id) => {
return this.name
? `${id}~[${this.name}]~<${this.id}>`
: `${id}~<${this.id}>`;
}
};
record.use = record.creator(ctx);
}
dispose() {
return __awaiter(this, void 0, void 0, function* () {
const { records } = this;
const keys = records.keys();
for (const key of keys) {
const record = records.get(key);
if (!record || !record.use)
return;
const activePinia = getActivePinia();
if (!activePinia)
return;
// store created
const hasCreated = activePinia._s.has(record.use.$id);
const disposes = (record === null || record === void 0 ? void 0 : record.disposes) || [];
for (const dispose of disposes) {
yield dispose(hasCreated);
}
if (!hasCreated)
return;
record.use().$dispose();
}
});
}
}

const injectorKey = Symbol('Injector Key');

const useProvideStores = (props) => {
const instance = getCurrentInstance();
const parentInjector = inject(injectorKey, null);
const injector = new Injector(props.stores, {
parent: parentInjector,
name: props.name
});
if (instance) {
instance.__PINIA_DI_INJECTOR__ = injector;
}
provide(injectorKey, injector);
onUnmounted(() => {
injector.dispose();
});
return {
getStore: (provide, opts) => {
return injector.get(provide, opts);
}
};
};
function useStore(provide, opts) {
var _a;
const instance = getCurrentInstance();
const ctxInjector = inject(injectorKey, null);
const injector = ((_a = instance) === null || _a === void 0 ? void 0 : _a.__PINIA_DI_INJECTOR__) || ctxInjector;
if (!injector) {
if (!opts || !opts.optional) {
throw new Error(`Never register any injector for ${provide.$id || provide.toString()}!`);
}
return null;
}
return injector.get(provide, opts);
const useProvideStores = (props) => {
const instance = getCurrentInstance();
const parentInjector = inject(injectorKey, null);
const injector = new Injector(props.stores, {
parent: parentInjector,
name: props.name
});
if (instance) {
instance.__PINIA_DI_INJECTOR__ = injector;
}
provide(injectorKey, injector);
onUnmounted(() => {
injector.dispose();
});
return {
getStore: (provide, opts) => {
return injector.get(provide, opts);
}
};
};
function useStore(provide, opts) {
const instance = getCurrentInstance();
const ctxInjector = inject(injectorKey, null);
const injector = (instance === null || instance === void 0 ? void 0 : instance.__PINIA_DI_INJECTOR__) || ctxInjector;
if (!injector) {
if (!opts || !opts.optional) {
throw new Error(`Never register any injector for ${provide.$id || provide.toString()}!`);
}
return null;
}
return injector.get(provide, opts);
}

const getProvideArgs = (providers, name = '') => {
const injector = new Injector(providers, { name });
return [injectorKey, injector];
const getProvideArgs = (providers, name = '') => {
const injector = new Injector(providers, { name });
return [injectorKey, injector];
};

const StoreProvider = defineComponent({
props: {
stores: { type: Object, required: true },
name: { type: String, requred: false }
},
setup(props) {
useProvideStores({
stores: props.stores,
name: props.name
});
}
const StoreProvider = defineComponent({
props: {
stores: { type: Object, required: true },
name: { type: String, requred: false }
},
setup(props) {
useProvideStores({
stores: props.stores,
name: props.name
});
}
});

export { Injector, StoreProvider, getProvideArgs, injectorKey, useProvideStores, useStore };
Loading

0 comments on commit c16cf6e

Please sign in to comment.