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

feat: provide core package #44

Merged
merged 3 commits into from
Apr 29, 2023
Merged
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
1 change: 1 addition & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,5 @@
"tooltip": "Fix Auto ESLint"
},
],
"references.preferredLocation": "peek",
}
11 changes: 11 additions & 0 deletions packages/vue/provide/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# `@oku-ui/provide`

## Installation

```sh
$ pnpm add @oku-ui/provide
```

## Usage

This is an internal utility, not intended for public usage.
41 changes: 41 additions & 0 deletions packages/vue/provide/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
{
"name": "@oku-ui/provide",
"version": "1.0.0",
"license": "MIT",
"source": "src/index.ts",
"type": "module",
"module": "dist/provide.js",
"types": "dist/types/index.d.ts",
"main": "dist/provide.cjs",
"files": [
"dist",
"README.md"
],
"exports": {
".": {
"import": "./dist/provide.js",
"types": "./dist/types/index.d.ts",
"require": "./dist/provide.cjs"
}
},
"scripts": {
"clean": "rm -rf dist",
"build": "vite build --mode production",
"dev": "vite build --mode production --watch"
},
"peerDependencies": {
"vue": "^3.3.0-beta.2"
},
"homepage": "https://oku-ui.com/primitives",
"repository": {
"type": "git",
"url": "git+https://github.com/oku-ui/primitives.git"
},
"bugs": {
"url": "https://github.com/oku-ui/primitives/issues"
},
"funding": "https://github.com/sponsors/productdevbook",
"devDependencies": {
"tsconfig": "workspace:^"
}
}
141 changes: 141 additions & 0 deletions packages/vue/provide/src/createProvide.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
import type { ComputedRef, InjectionKey } from 'vue'
import { computed, defineComponent, inject, provide, reactive } from 'vue'

function createProvide<ProvideValueType extends object | null>(
rootComponentName: string,
defaultProvide?: ProvideValueType,
) {
const Provide = Symbol(rootComponentName)
const Provider = defineComponent({
name: `${rootComponentName}Provider`,
inheritAttrs: false,
setup(props, { attrs, slots }) {
const value = reactive(attrs) as ProvideValueType
provide(Provide, value)
if (!slots || !slots.default)
throw new Error(`\`${rootComponentName}Provider\` must have a default slot :(`)

return () => slots.default?.()
},
})

function useContext(consumerName: string) {
const provide = inject(Provide)
if (provide)
return provide
if (defaultProvide !== undefined)
return defaultProvide
// if a defaultProvide wasn't specified, it's a required provide.
throw new Error(`\`${consumerName}\` must be used within \`${rootComponentName}\``)
}

return [Provider, useContext] as const
}

/* -------------------------------------------------------------------------------------------------
* createProvideScope
* ----------------------------------------------------------------------------------------------- */

type Scope<C = any> = { [scopeName: string]: { key: InjectionKey<C>; value: C }[] }

type ScopeHook = (scope: Scope) => ComputedRef<{ [__scopeProp: string]: Scope }>
interface CreateScope {
scopeName: string
(): ScopeHook
}

// function createInjectKey<ContextValueType extends object | null>(name: string): InjectionKey<ContextValueType> {
// return Symbol(name) as InjectionKey<ContextValueType>
// }

// type RefType<T> = ComputedRef<T> | Ref<T>

function createProvideScope(scopeName: string, createProvideScopeDeps: CreateScope[] = []) {
let defaultProviders: Scope[] = []
/* -----------------------------------------------------------------------------------------------
* createContext
* --------------------------------------------------------------------------------------------- */

function createProvide<ProvideValueType extends object | null>(
rootComponentName: string,
defaultValue?: ProvideValueType,
) {
const BaseProvideKey: InjectionKey<ProvideValueType | null> = Symbol(rootComponentName)
// const BaseProvide = provide(BaseProvideKey, defaultValue)
const BaseScope = { key: BaseProvideKey, value: defaultValue }
console.log('BaseScope', BaseScope)
const index = defaultProviders.length
defaultProviders = [...defaultProviders, { [scopeName]: [{ key: BaseProvideKey, value: defaultValue }] }]

function Provider(
props: ProvideValueType & { scope: Scope<ProvideValueType> },
) {
const { scope, ...context } = props as any
const Provide = scope?.[scopeName][index] || BaseScope.key as ProvideValueType

const value = computed<ProvideValueType>(() => context)

provide(Provide, value)
}

function useInject(consumerName: string, scope: Scope<ProvideValueType | undefined>): ComputedRef<ProvideValueType> {
const Provide = scope?.[scopeName][index] || BaseScope as ProvideValueType
const provide = inject(Provide.key)
if (provide)
return provide as ComputedRef<ProvideValueType>
if (defaultValue !== undefined)
return computed(() => defaultValue)

// // if a defaultProvide wasn't specified, it's a required provide.
throw new Error(`\`${consumerName}\` must be used within \`${rootComponentName}\``)
}

return [Provider, useInject] as const
}

/* -----------------------------------------------------------------------------------------------
* createScope
* --------------------------------------------------------------------------------------------- */
const createScope: CreateScope = () => {
const scopeProviders = defaultProviders
return function useScope(scope: Scope) {
const providers = scope?.[scopeName] || scopeProviders

return computed(() => ({ [`__scope${scopeName}`]: { ...scope, [scopeName]: providers } }))
}
}

createScope.scopeName = scopeName
return [createProvide, composeContextScopes(createScope, ...createProvideScopeDeps)] as const
}

function composeContextScopes(...scopes: CreateScope[]) {
const baseScope = scopes[0]
if (scopes.length === 1)
return baseScope

const createScope: CreateScope = () => {
const scopeHooks = scopes.map(createScope => ({
useScope: createScope(),
scopeName: createScope.scopeName,
}))

return function useComposedScopes(overrideScopes) {
const nextScopes = scopeHooks.reduce((nextScopes, { useScope, scopeName }) => {
// We are calling a hook inside a callback which React warns against to avoid inconsistent
// renders, however, scoping doesn't have render side effects so we ignore the rule.
const scopeProps = useScope(overrideScopes)
const currentScope = computed(() => scopeProps.value[`__scope${scopeName}`])
return { ...nextScopes, ...currentScope }
}, {})

return computed(() => ({ [`__scope${baseScope.scopeName}`]: nextScopes }))
}
}

createScope.scopeName = baseScope.scopeName
return createScope
}

export { createProvide, createProvideScope }
export type { CreateScope, Scope }
2 changes: 2 additions & 0 deletions packages/vue/provide/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export { createProvide, createProvideScope } from './createProvide'
export type { CreateScope, Scope } from './createProvide'
43 changes: 43 additions & 0 deletions packages/vue/provide/tests/provide.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { h } from 'vue'
import { describe, expect, test } from 'vitest'
import { mount } from '@vue/test-utils'
import { createProvide } from '../src/index'

describe('Provide', () => {
test('createContext', async () => {
const [AvatarProvider, useAvatarContext] = createProvide('Avatar')
const component = mount(AvatarProvider, {
props: {
test2: 'test2',
},
slots: {
default: h('div', { id: 'test' }, 'testaaa'),
},
})
const deneme = component.html()
expect(deneme).toBe('<div id="test">testaaa</div>')
})

// test('createContextScope', async () => {
// const AVATAR_NAME = 'Avatar'
// const [createAvatarContext, createAvatarScope] = createContextScope(AVATAR_NAME)

// type AvatarContextValue = {
// imageLoadingStatus: ImageLoadingStatus
// onImageLoadingStatusChange(status: ImageLoadingStatus): void
// }

// const [AvatarProvider, useAvatarContext] = createAvatarContext<AvatarContextValue>(AVATAR_NAME)

// // <AvatarProvider
// // scope={__scopeAvatar}
// // imageLoadingStatus={imageLoadingStatus}
// // onImageLoadingStatusChange={setImageLoadingStatus}
// // >
// // <Primitive.span {...avatarProps} ref={forwardedRef} />
// // </AvatarProvider>

// const component = mount(AvatarProvider, {
// props
// })
})
6 changes: 6 additions & 0 deletions packages/vue/provide/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"extends": "./../../../tsconfig.json",
"include": [
"./"
],
}
46 changes: 46 additions & 0 deletions packages/vue/provide/vite.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import path, { resolve } from 'node:path'

import Vue from '@vitejs/plugin-vue'
import { defineConfig } from 'vite'
// https://github.com/qmhc/vite-plugin-dts
import dtsPlugin from 'vite-plugin-dts'

// https://github.com/sxzz/unplugin-vue-macros
import VueMacros from 'unplugin-vue-macros/vite'
import * as pkg from './package.json'

const externals = [
...Object.keys(pkg.peerDependencies || {}),
...Object.keys(pkg.dependencies || {}),
]
export default defineConfig({
plugins: [
dtsPlugin({
include: ['./src/**/*.ts', './src/**/*.tsx', './src/**/*.vue'],
skipDiagnostics: false,
staticImport: true,
outputDir: ['./dist/types'],
cleanVueFileName: false,
}),
VueMacros({
plugins: {
vue: Vue(),
},
}),
],
resolve: {
alias: {
'@': resolve(__dirname, 'src'),
},
},
build: {
target: 'modules',
lib: {
entry: path.resolve(__dirname, './src/index.ts'),
formats: ['es', 'cjs'],
},
rollupOptions: {
external: externals,
},
},
})
10 changes: 10 additions & 0 deletions pnpm-lock.yaml

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

9 changes: 2 additions & 7 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,7 @@
"vue",
"vite/client",
"unplugin-vue-macros/macros-global"
],
"paths": {
"@oku-ui/provide": [
"./packages/vue/provide/index.ts"
]
}
]
},
"vueCompilerOptions": {
"plugins": [
Expand All @@ -39,6 +34,6 @@
]
},
"include": [
"packages/**/*"
"packages/**/*"
]
}