UNPKG

@muban/muban

Version:

Writing components for server-rendered HTML

53 lines (52 loc) 2.11 kB
/* eslint-disable @typescript-eslint/no-explicit-any */ import { isFunction } from 'isntnt'; import { getCurrentComponentInstance } from '../Component'; export function provide(key, value) { const currentInstance = getCurrentComponentInstance(); if (!currentInstance) { // eslint-disable-next-line no-console console.error(`provide() can only be used inside setup().`); } else { // TS doesn't allow symbol as index type currentInstance.provides[key] = value; } } export function inject(key, defaultValue, treatDefaultAsFactory = false) { // fallback to `currentRenderingInstance` so that this can be called in // a functional component const currentInstance = getCurrentComponentInstance(); if (currentInstance) { // #2400 // to support `app.use` plugins, // fallback to appContext's `provides` if the instance is at root const provides = currentInstance.parent == null ? currentInstance.appContext && currentInstance.appContext.provides : currentInstance.parent.provides; if (provides && key in provides) { // TS doesn't allow symbol as index type return provides[key]; } if (arguments.length > 1) { return treatDefaultAsFactory && isFunction(defaultValue) ? defaultValue() : defaultValue; } // eslint-disable-next-line no-console console.error(`injection "${String(key)}" not found.`); } else { // eslint-disable-next-line no-console console.error(`inject() can only be used inside setup() or functional components.`); } } /** * Helper function around provide/inject to create a typed pair with a curried "key" and default values */ export function createContext(key, defaultValue) { const provideContext = (value) => { provide(key, value || defaultValue); }; const useContext = (defaultInjectValue, treatDefaultAsFactory) => { return inject(key, defaultInjectValue, treatDefaultAsFactory); }; return [provideContext, useContext]; }