Refactor DI for simplicity and type safety

This commit improves the dependency injection mechanism by introducing a
custom `injectKey` function.

Key improvements are:

- Enforced type consistency during dependency registration and
  instantiation.
- Simplified injection process, abstracting away the complexity with a
  uniform API, regardless of the dependency's lifetime.
- Eliminated the possibility of `undefined` returns during dependency
  injection, promoting fail-fast behavior.
- Removed the necessity for type casting to `symbol` for injection keys
  in unit tests by using existing types.
- Consalidated imports, combining keys and injection functions in one
  `import` statement.
This commit is contained in:
undergroundwires
2023-11-09 13:17:38 +01:00
parent aab0f7ea46
commit 7770a9b521
51 changed files with 398 additions and 177 deletions

View File

@@ -71,10 +71,11 @@ To add a new dependency:
1. **Define its symbol**: Define an associated symbol for every dependency in [`injectionSymbols.ts`](./../src/presentation/injectionSymbols.ts). Symbols are grouped into: 1. **Define its symbol**: Define an associated symbol for every dependency in [`injectionSymbols.ts`](./../src/presentation/injectionSymbols.ts). Symbols are grouped into:
- **Singletons**: Shared across components, instantiated once. - **Singletons**: Shared across components, instantiated once.
- **Transients**: Factories yielding a new instance on every access. - **Transients**: Factories yielding a new instance on every access.
2. **Provide the dependency**: Modify the [`provideDependencies`](./../src/presentation/bootstrapping/DependencyProvider.ts) function to include the new dependency. [`App.vue`](./../src/presentation/components/App.vue) calls this function within its `setup()` hook to register the dependencies. 2. **Provide the dependency**:
3. **Inject the dependency**: Use Vue's `inject` method alongside the defined symbol to incorporate the dependency into components. Modify the [`provideDependencies`](./../src/presentation/bootstrapping/DependencyProvider.ts) function to include the new dependency.
- For singletons, invoke the factory method: `inject(symbolKey)()`. [`App.vue`](./../src/presentation/components/App.vue) calls this function within its `setup()` hook to register the dependencies.
- For transients, directly inject: `inject(symbolKey)`. 3. **Inject the dependency**: Use `injectKey` to inject a dependency. Pass a selector function to `injectKey` that retrieves the appropriate symbol from the provided dependencies.
- Example usage: `injectKey((keys) => keys.useCollectionState)`;
## Shared UI components ## Shared UI components

View File

@@ -2,38 +2,89 @@ import { InjectionKey, provide, inject } from 'vue';
import { useCollectionState } from '@/presentation/components/Shared/Hooks/UseCollectionState'; import { useCollectionState } from '@/presentation/components/Shared/Hooks/UseCollectionState';
import { useApplication } from '@/presentation/components/Shared/Hooks/UseApplication'; import { useApplication } from '@/presentation/components/Shared/Hooks/UseApplication';
import { useAutoUnsubscribedEvents } from '@/presentation/components/Shared/Hooks/UseAutoUnsubscribedEvents'; import { useAutoUnsubscribedEvents } from '@/presentation/components/Shared/Hooks/UseAutoUnsubscribedEvents';
import { useClipboard } from '@/presentation/components/Shared/Hooks/Clipboard/UseClipboard';
import { useCurrentCode } from '@/presentation/components/Shared/Hooks/UseCurrentCode';
import { IApplicationContext } from '@/application/Context/IApplicationContext'; import { IApplicationContext } from '@/application/Context/IApplicationContext';
import { RuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironment'; import { RuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironment';
import { InjectionKeys } from '@/presentation/injectionSymbols'; import {
import { useClipboard } from '../components/Shared/Hooks/Clipboard/UseClipboard'; AnyLifetimeInjectionKey, InjectionKeySelector, InjectionKeys, SingletonKey,
import { useCurrentCode } from '../components/Shared/Hooks/UseCurrentCode'; TransientKey, injectKey,
} from '@/presentation/injectionSymbols';
import { PropertyKeys } from '@/TypeHelpers';
export function provideDependencies( export function provideDependencies(
context: IApplicationContext, context: IApplicationContext,
api: VueDependencyInjectionApi = { provide, inject }, api: VueDependencyInjectionApi = { provide, inject },
) { ) {
const registerSingleton = <T>(key: InjectionKey<T>, value: T) => api.provide(key, value); const resolvers: Record<PropertyKeys<typeof InjectionKeys>, (di: DependencyRegistrar) => void> = {
const registerTransient = <T>( useCollectionState: (di) => di.provide(
key: InjectionKey<() => T>, InjectionKeys.useCollectionState,
factory: () => T, () => {
) => api.provide(key, factory); const { events } = di.injectKey((keys) => keys.useAutoUnsubscribedEvents);
return useCollectionState(context, events);
},
),
useApplication: (di) => di.provide(
InjectionKeys.useApplication,
useApplication(context.app),
),
useRuntimeEnvironment: (di) => di.provide(
InjectionKeys.useRuntimeEnvironment,
RuntimeEnvironment.CurrentEnvironment,
),
useAutoUnsubscribedEvents: (di) => di.provide(
InjectionKeys.useAutoUnsubscribedEvents,
useAutoUnsubscribedEvents,
),
useClipboard: (di) => di.provide(
InjectionKeys.useClipboard,
useClipboard,
),
useCurrentCode: (di) => di.provide(
InjectionKeys.useCurrentCode,
() => {
const { events } = di.injectKey((keys) => keys.useAutoUnsubscribedEvents);
const state = di.injectKey((keys) => keys.useCollectionState);
return useCurrentCode(state, events);
},
),
};
registerAll(Object.values(resolvers), api);
}
registerSingleton(InjectionKeys.useApplication, useApplication(context.app)); function registerAll(
registerSingleton(InjectionKeys.useRuntimeEnvironment, RuntimeEnvironment.CurrentEnvironment); registrations: ReadonlyArray<(di: DependencyRegistrar) => void>,
registerTransient(InjectionKeys.useAutoUnsubscribedEvents, () => useAutoUnsubscribedEvents()); api: VueDependencyInjectionApi,
registerTransient(InjectionKeys.useCollectionState, () => { ) {
const { events } = api.inject(InjectionKeys.useAutoUnsubscribedEvents)(); const registrar = new DependencyRegistrar(api);
return useCollectionState(context, events); Object.values(registrations).forEach((register) => register(registrar));
});
registerTransient(InjectionKeys.useClipboard, () => useClipboard());
registerTransient(InjectionKeys.useCurrentCode, () => {
const { events } = api.inject(InjectionKeys.useAutoUnsubscribedEvents)();
const state = api.inject(InjectionKeys.useCollectionState)();
return useCurrentCode(state, events);
});
} }
export interface VueDependencyInjectionApi { export interface VueDependencyInjectionApi {
provide<T>(key: InjectionKey<T>, value: T): void; provide<T>(key: InjectionKey<T>, value: T): void;
inject<T>(key: InjectionKey<T>): T; inject<T>(key: InjectionKey<T>): T;
} }
class DependencyRegistrar {
constructor(private api: VueDependencyInjectionApi) {}
public provide<T>(
key: TransientKey<T>,
resolver: () => T,
): void;
public provide<T>(
key: SingletonKey<T>,
resolver: T,
): void;
public provide<T>(
key: AnyLifetimeInjectionKey<T>,
resolver: T | (() => T),
): void {
this.api.provide(key.key, resolver);
}
public injectKey<T>(key: InjectionKeySelector<T>): T {
const injector = this.api.inject.bind(this.api);
return injectKey(key, injector);
}
}

View File

@@ -7,10 +7,8 @@
</template> </template>
<script lang="ts"> <script lang="ts">
import { import { defineComponent } from 'vue';
defineComponent, inject, import { injectKey } from '@/presentation/injectionSymbols';
} from 'vue';
import { InjectionKeys } from '@/presentation/injectionSymbols';
import IconButton from './IconButton.vue'; import IconButton from './IconButton.vue';
export default defineComponent({ export default defineComponent({
@@ -18,8 +16,8 @@ export default defineComponent({
IconButton, IconButton,
}, },
setup() { setup() {
const { copyText } = inject(InjectionKeys.useClipboard)(); const { copyText } = injectKey((keys) => keys.useClipboard);
const { currentCode } = inject(InjectionKeys.useCurrentCode)(); const { currentCode } = injectKey((keys) => keys.useCurrentCode);
async function copyCode() { async function copyCode() {
await copyText(currentCode.value); await copyText(currentCode.value);

View File

@@ -8,10 +8,8 @@
</template> </template>
<script lang="ts"> <script lang="ts">
import { import { defineComponent, computed } from 'vue';
defineComponent, computed, inject, import { injectKey } from '@/presentation/injectionSymbols';
} from 'vue';
import { InjectionKeys } from '@/presentation/injectionSymbols';
import { OperatingSystem } from '@/domain/OperatingSystem'; import { OperatingSystem } from '@/domain/OperatingSystem';
import { CodeRunner } from '@/infrastructure/CodeRunner'; import { CodeRunner } from '@/infrastructure/CodeRunner';
import { IReadOnlyApplicationContext } from '@/application/Context/IApplicationContext'; import { IReadOnlyApplicationContext } from '@/application/Context/IApplicationContext';
@@ -22,8 +20,8 @@ export default defineComponent({
IconButton, IconButton,
}, },
setup() { setup() {
const { currentState, currentContext } = inject(InjectionKeys.useCollectionState)(); const { currentState, currentContext } = injectKey((keys) => keys.useCollectionState);
const { os, isDesktop } = inject(InjectionKeys.useRuntimeEnvironment); const { os, isDesktop } = injectKey((keys) => keys.useRuntimeEnvironment);
const canRun = computed<boolean>(() => getCanRunState(currentState.value.os, isDesktop, os)); const canRun = computed<boolean>(() => getCanRunState(currentState.value.os, isDesktop, os));

View File

@@ -13,9 +13,9 @@
<script lang="ts"> <script lang="ts">
import { import {
defineComponent, ref, computed, inject, defineComponent, ref, computed,
} from 'vue'; } from 'vue';
import { InjectionKeys } from '@/presentation/injectionSymbols'; import { injectKey } from '@/presentation/injectionSymbols';
import { SaveFileDialog, FileType } from '@/infrastructure/SaveFileDialog'; import { SaveFileDialog, FileType } from '@/infrastructure/SaveFileDialog';
import ModalDialog from '@/presentation/components/Shared/Modal/ModalDialog.vue'; import ModalDialog from '@/presentation/components/Shared/Modal/ModalDialog.vue';
import { IReadOnlyCategoryCollectionState } from '@/application/Context/State/ICategoryCollectionState'; import { IReadOnlyCategoryCollectionState } from '@/application/Context/State/ICategoryCollectionState';
@@ -34,8 +34,8 @@ export default defineComponent({
ModalDialog, ModalDialog,
}, },
setup() { setup() {
const { currentState } = inject(InjectionKeys.useCollectionState)(); const { currentState } = injectKey((keys) => keys.useCollectionState);
const { isDesktop } = inject(InjectionKeys.useRuntimeEnvironment); const { isDesktop } = injectKey((keys) => keys.useRuntimeEnvironment);
const areInstructionsVisible = ref(false); const areInstructionsVisible = ref(false);
const fileName = computed<string>(() => buildFileName(currentState.value.collection.scripting)); const fileName = computed<string>(() => buildFileName(currentState.value.collection.scripting));

View File

@@ -16,10 +16,10 @@
</template> </template>
<script lang="ts"> <script lang="ts">
import { defineComponent, shallowRef, inject } from 'vue'; import { defineComponent, shallowRef } from 'vue';
import TooltipWrapper from '@/presentation/components/Shared/TooltipWrapper.vue'; import TooltipWrapper from '@/presentation/components/Shared/TooltipWrapper.vue';
import AppIcon from '@/presentation/components/Shared/Icon/AppIcon.vue'; import AppIcon from '@/presentation/components/Shared/Icon/AppIcon.vue';
import { InjectionKeys } from '@/presentation/injectionSymbols'; import { injectKey } from '@/presentation/injectionSymbols';
export default defineComponent({ export default defineComponent({
components: { components: {
@@ -27,7 +27,7 @@ export default defineComponent({
AppIcon, AppIcon,
}, },
setup() { setup() {
const { copyText } = inject(InjectionKeys.useClipboard)(); const { copyText } = injectKey((keys) => keys.useClipboard);
const codeElement = shallowRef<HTMLElement | undefined>(); const codeElement = shallowRef<HTMLElement | undefined>();

View File

@@ -57,9 +57,8 @@
<script lang="ts"> <script lang="ts">
import { import {
defineComponent, PropType, computed, defineComponent, PropType, computed,
inject,
} from 'vue'; } from 'vue';
import { InjectionKeys } from '@/presentation/injectionSymbols'; import { injectKey } from '@/presentation/injectionSymbols';
import { OperatingSystem } from '@/domain/OperatingSystem'; import { OperatingSystem } from '@/domain/OperatingSystem';
import TooltipWrapper from '@/presentation/components/Shared/TooltipWrapper.vue'; import TooltipWrapper from '@/presentation/components/Shared/TooltipWrapper.vue';
import AppIcon from '@/presentation/components/Shared/Icon/AppIcon.vue'; import AppIcon from '@/presentation/components/Shared/Icon/AppIcon.vue';
@@ -79,7 +78,7 @@ export default defineComponent({
}, },
}, },
setup(props) { setup(props) {
const { info } = inject(InjectionKeys.useApplication); const { info } = injectKey((keys) => keys.useApplication);
const appName = computed<string>(() => info.name); const appName = computed<string>(() => info.name);

View File

@@ -8,9 +8,9 @@
<script lang="ts"> <script lang="ts">
import { import {
defineComponent, computed, inject, defineComponent, computed,
} from 'vue'; } from 'vue';
import { InjectionKeys } from '@/presentation/injectionSymbols'; import { injectKey } from '@/presentation/injectionSymbols';
import CodeRunButton from './CodeRunButton.vue'; import CodeRunButton from './CodeRunButton.vue';
import CodeCopyButton from './CodeCopyButton.vue'; import CodeCopyButton from './CodeCopyButton.vue';
import CodeSaveButton from './Save/CodeSaveButton.vue'; import CodeSaveButton from './Save/CodeSaveButton.vue';
@@ -22,7 +22,7 @@ export default defineComponent({
CodeSaveButton, CodeSaveButton,
}, },
setup() { setup() {
const { currentCode } = inject(InjectionKeys.useCurrentCode)(); const { currentCode } = injectKey((keys) => keys.useCurrentCode);
const hasCode = computed<boolean>(() => currentCode.value.length > 0); const hasCode = computed<boolean>(() => currentCode.value.length > 0);

View File

@@ -11,9 +11,9 @@
<script lang="ts"> <script lang="ts">
import { import {
defineComponent, onUnmounted, onMounted, inject, defineComponent, onUnmounted, onMounted,
} from 'vue'; } from 'vue';
import { InjectionKeys } from '@/presentation/injectionSymbols'; import { injectKey } from '@/presentation/injectionSymbols';
import { ICodeChangedEvent } from '@/application/Context/State/Code/Event/ICodeChangedEvent'; import { ICodeChangedEvent } from '@/application/Context/State/Code/Event/ICodeChangedEvent';
import { IScript } from '@/domain/IScript'; import { IScript } from '@/domain/IScript';
import { ScriptingLanguage } from '@/domain/ScriptingLanguage'; import { ScriptingLanguage } from '@/domain/ScriptingLanguage';
@@ -37,8 +37,8 @@ export default defineComponent({
NonCollapsing, NonCollapsing,
}, },
setup(props) { setup(props) {
const { onStateChange, currentState } = inject(InjectionKeys.useCollectionState)(); const { onStateChange, currentState } = injectKey((keys) => keys.useCollectionState);
const { events } = inject(InjectionKeys.useAutoUnsubscribedEvents)(); const { events } = injectKey((keys) => keys.useAutoUnsubscribedEvents);
const editorId = 'codeEditor'; const editorId = 'codeEditor';
let editor: ace.Ace.Editor | undefined; let editor: ace.Ace.Editor | undefined;

View File

@@ -65,8 +65,8 @@
</template> </template>
<script lang="ts"> <script lang="ts">
import { defineComponent, ref, inject } from 'vue'; import { defineComponent, ref } from 'vue';
import { InjectionKeys } from '@/presentation/injectionSymbols'; import { injectKey } from '@/presentation/injectionSymbols';
import TooltipWrapper from '@/presentation/components/Shared/TooltipWrapper.vue'; import TooltipWrapper from '@/presentation/components/Shared/TooltipWrapper.vue';
import { ICategoryCollectionState } from '@/application/Context/State/ICategoryCollectionState'; import { ICategoryCollectionState } from '@/application/Context/State/ICategoryCollectionState';
import { IEventSubscription } from '@/infrastructure/Events/IEventSource'; import { IEventSubscription } from '@/infrastructure/Events/IEventSource';
@@ -81,8 +81,8 @@ export default defineComponent({
TooltipWrapper, TooltipWrapper,
}, },
setup() { setup() {
const { modifyCurrentState, onStateChange } = inject(InjectionKeys.useCollectionState)(); const { modifyCurrentState, onStateChange } = injectKey((keys) => keys.useCollectionState);
const { events } = inject(InjectionKeys.useAutoUnsubscribedEvents)(); const { events } = injectKey((keys) => keys.useAutoUnsubscribedEvents);
const currentSelection = ref(SelectionType.None); const currentSelection = ref(SelectionType.None);

View File

@@ -11,10 +11,8 @@
</template> </template>
<script lang="ts"> <script lang="ts">
import { import { defineComponent, computed } from 'vue';
defineComponent, computed, inject, import { injectKey } from '@/presentation/injectionSymbols';
} from 'vue';
import { InjectionKeys } from '@/presentation/injectionSymbols';
import { OperatingSystem } from '@/domain/OperatingSystem'; import { OperatingSystem } from '@/domain/OperatingSystem';
import MenuOptionList from './MenuOptionList.vue'; import MenuOptionList from './MenuOptionList.vue';
import MenuOptionListItem from './MenuOptionListItem.vue'; import MenuOptionListItem from './MenuOptionListItem.vue';
@@ -30,8 +28,8 @@ export default defineComponent({
MenuOptionListItem, MenuOptionListItem,
}, },
setup() { setup() {
const { modifyCurrentContext, currentState } = inject(InjectionKeys.useCollectionState)(); const { modifyCurrentContext, currentState } = injectKey((keys) => keys.useCollectionState);
const { application } = inject(InjectionKeys.useApplication); const { application } = injectKey((keys) => keys.useApplication);
const allOses = computed<ReadonlyArray<IOsViewModel>>(() => ( const allOses = computed<ReadonlyArray<IOsViewModel>>(() => (
application.getSupportedOsList() ?? []) application.getSupportedOsList() ?? [])

View File

@@ -10,10 +10,8 @@
</template> </template>
<script lang="ts"> <script lang="ts">
import { import { defineComponent, ref } from 'vue';
defineComponent, ref, inject, import { injectKey } from '@/presentation/injectionSymbols';
} from 'vue';
import { InjectionKeys } from '@/presentation/injectionSymbols';
import { IReadOnlyUserFilter } from '@/application/Context/State/Filter/IUserFilter'; import { IReadOnlyUserFilter } from '@/application/Context/State/Filter/IUserFilter';
import { IEventSubscription } from '@/infrastructure/Events/IEventSource'; import { IEventSubscription } from '@/infrastructure/Events/IEventSource';
import TheOsChanger from './TheOsChanger.vue'; import TheOsChanger from './TheOsChanger.vue';
@@ -27,8 +25,8 @@ export default defineComponent({
TheViewChanger, TheViewChanger,
}, },
setup() { setup() {
const { onStateChange } = inject(InjectionKeys.useCollectionState)(); const { onStateChange } = injectKey((keys) => keys.useCollectionState);
const { events } = inject(InjectionKeys.useAutoUnsubscribedEvents)(); const { events } = injectKey((keys) => keys.useAutoUnsubscribedEvents);
const isSearching = ref(false); const isSearching = ref(false);

View File

@@ -35,9 +35,8 @@
<script lang="ts"> <script lang="ts">
import { import {
defineComponent, ref, onMounted, onUnmounted, computed, defineComponent, ref, onMounted, onUnmounted, computed,
inject,
} from 'vue'; } from 'vue';
import { InjectionKeys } from '@/presentation/injectionSymbols'; import { injectKey } from '@/presentation/injectionSymbols';
import SizeObserver from '@/presentation/components/Shared/SizeObserver.vue'; import SizeObserver from '@/presentation/components/Shared/SizeObserver.vue';
import { hasDirective } from './NonCollapsingDirective'; import { hasDirective } from './NonCollapsingDirective';
import CardListItem from './CardListItem.vue'; import CardListItem from './CardListItem.vue';
@@ -48,7 +47,7 @@ export default defineComponent({
SizeObserver, SizeObserver,
}, },
setup() { setup() {
const { currentState, onStateChange } = inject(InjectionKeys.useCollectionState)(); const { currentState, onStateChange } = injectKey((keys) => keys.useCollectionState);
const width = ref<number>(0); const width = ref<number>(0);
const categoryIds = computed<ReadonlyArray<number>>(() => currentState const categoryIds = computed<ReadonlyArray<number>>(() => currentState

View File

@@ -49,11 +49,10 @@
<script lang="ts"> <script lang="ts">
import { import {
defineComponent, ref, watch, computed, defineComponent, ref, watch, computed, shallowRef,
inject, shallowRef,
} from 'vue'; } from 'vue';
import AppIcon from '@/presentation/components/Shared/Icon/AppIcon.vue'; import AppIcon from '@/presentation/components/Shared/Icon/AppIcon.vue';
import { InjectionKeys } from '@/presentation/injectionSymbols'; import { injectKey } from '@/presentation/injectionSymbols';
import ScriptsTree from '@/presentation/components/Scripts/View/Tree/ScriptsTree.vue'; import ScriptsTree from '@/presentation/components/Scripts/View/Tree/ScriptsTree.vue';
import { sleep } from '@/infrastructure/Threading/AsyncSleep'; import { sleep } from '@/infrastructure/Threading/AsyncSleep';
@@ -78,8 +77,8 @@ export default defineComponent({
/* eslint-enable @typescript-eslint/no-unused-vars */ /* eslint-enable @typescript-eslint/no-unused-vars */
}, },
setup(props, { emit }) { setup(props, { emit }) {
const { onStateChange, currentState } = inject(InjectionKeys.useCollectionState)(); const { onStateChange, currentState } = injectKey((keys) => keys.useCollectionState);
const { events } = inject(InjectionKeys.useAutoUnsubscribedEvents)(); const { events } = injectKey((keys) => keys.useAutoUnsubscribedEvents);
const isExpanded = computed({ const isExpanded = computed({
get: () => { get: () => {

View File

@@ -39,10 +39,9 @@
<script lang="ts"> <script lang="ts">
import { import {
defineComponent, PropType, ref, computed, defineComponent, PropType, ref, computed,
inject,
} from 'vue'; } from 'vue';
import AppIcon from '@/presentation/components/Shared/Icon/AppIcon.vue'; import AppIcon from '@/presentation/components/Shared/Icon/AppIcon.vue';
import { InjectionKeys } from '@/presentation/injectionSymbols'; import { injectKey } from '@/presentation/injectionSymbols';
import ScriptsTree from '@/presentation/components/Scripts/View/Tree/ScriptsTree.vue'; import ScriptsTree from '@/presentation/components/Scripts/View/Tree/ScriptsTree.vue';
import CardList from '@/presentation/components/Scripts/View/Cards/CardList.vue'; import CardList from '@/presentation/components/Scripts/View/Cards/CardList.vue';
import { ViewType } from '@/presentation/components/Scripts/Menu/View/ViewType'; import { ViewType } from '@/presentation/components/Scripts/Menu/View/ViewType';
@@ -62,9 +61,9 @@ export default defineComponent({
}, },
}, },
setup() { setup() {
const { modifyCurrentState, onStateChange } = inject(InjectionKeys.useCollectionState)(); const { modifyCurrentState, onStateChange } = injectKey((keys) => keys.useCollectionState);
const { events } = inject(InjectionKeys.useAutoUnsubscribedEvents)(); const { events } = injectKey((keys) => keys.useAutoUnsubscribedEvents);
const { info } = inject(InjectionKeys.useApplication); const { info } = injectKey((keys) => keys.useApplication);
const repositoryUrl = computed<string>(() => info.repositoryWebUrl); const repositoryUrl = computed<string>(() => info.repositoryWebUrl);
const searchQuery = ref<string | undefined>(); const searchQuery = ref<string | undefined>();

View File

@@ -8,11 +8,10 @@
<script lang="ts"> <script lang="ts">
import { import {
PropType, defineComponent, ref, watch, PropType, defineComponent, ref, watch, computed,
computed, inject,
} from 'vue'; } from 'vue';
import { SelectedScript } from '@/application/Context/State/Selection/SelectedScript'; import { SelectedScript } from '@/application/Context/State/Selection/SelectedScript';
import { InjectionKeys } from '@/presentation/injectionSymbols'; import { injectKey } from '@/presentation/injectionSymbols';
import { NodeMetadata } from '@/presentation/components/Scripts/View/Tree/NodeContent/NodeMetadata'; import { NodeMetadata } from '@/presentation/components/Scripts/View/Tree/NodeContent/NodeMetadata';
import { IReverter } from './Reverter/IReverter'; import { IReverter } from './Reverter/IReverter';
import { getReverter } from './Reverter/ReverterFactory'; import { getReverter } from './Reverter/ReverterFactory';
@@ -31,8 +30,8 @@ export default defineComponent({
setup(props) { setup(props) {
const { const {
currentState, modifyCurrentState, onStateChange, currentState, modifyCurrentState, onStateChange,
} = inject(InjectionKeys.useCollectionState)(); } = injectKey((keys) => keys.useCollectionState);
const { events } = inject(InjectionKeys.useAutoUnsubscribedEvents)(); const { events } = injectKey((keys) => keys.useAutoUnsubscribedEvents);
const isReverted = ref(false); const isReverted = ref(false);

View File

@@ -1,14 +1,14 @@
import { import {
WatchSource, inject, shallowRef, watch, WatchSource, shallowRef, watch,
} from 'vue'; } from 'vue';
import { InjectionKeys } from '@/presentation/injectionSymbols'; import { injectKey } from '@/presentation/injectionSymbols';
import { ReadOnlyTreeNode } from './TreeNode'; import { ReadOnlyTreeNode } from './TreeNode';
import { TreeNodeStateDescriptor } from './State/StateDescriptor'; import { TreeNodeStateDescriptor } from './State/StateDescriptor';
export function useNodeState( export function useNodeState(
nodeWatcher: WatchSource<ReadOnlyTreeNode | undefined>, nodeWatcher: WatchSource<ReadOnlyTreeNode | undefined>,
) { ) {
const { events } = inject(InjectionKeys.useAutoUnsubscribedEvents)(); const { events } = injectKey((keys) => keys.useAutoUnsubscribedEvents);
const state = shallowRef<TreeNodeStateDescriptor>(); const state = shallowRef<TreeNodeStateDescriptor>();

View File

@@ -1,12 +1,12 @@
import { import {
WatchSource, watch, inject, shallowReadonly, shallowRef, WatchSource, watch, shallowReadonly, shallowRef,
} from 'vue'; } from 'vue';
import { InjectionKeys } from '@/presentation/injectionSymbols'; import { injectKey } from '@/presentation/injectionSymbols';
import { TreeRoot } from './TreeRoot/TreeRoot'; import { TreeRoot } from './TreeRoot/TreeRoot';
import { QueryableNodes } from './TreeRoot/NodeCollection/Query/QueryableNodes'; import { QueryableNodes } from './TreeRoot/NodeCollection/Query/QueryableNodes';
export function useCurrentTreeNodes(treeWatcher: WatchSource<TreeRoot>) { export function useCurrentTreeNodes(treeWatcher: WatchSource<TreeRoot>) {
const { events } = inject(InjectionKeys.useAutoUnsubscribedEvents)(); const { events } = injectKey((keys) => keys.useAutoUnsubscribedEvents);
const tree = shallowRef<TreeRoot | undefined>(); const tree = shallowRef<TreeRoot | undefined>();
const nodes = shallowRef<QueryableNodes | undefined>(); const nodes = shallowRef<QueryableNodes | undefined>();

View File

@@ -1,7 +1,7 @@
import { import {
WatchSource, inject, watch, shallowRef, WatchSource, watch, shallowRef,
} from 'vue'; } from 'vue';
import { InjectionKeys } from '@/presentation/injectionSymbols'; import { injectKey } from '@/presentation/injectionSymbols';
import { IEventSubscription } from '@/infrastructure/Events/IEventSource'; import { IEventSubscription } from '@/infrastructure/Events/IEventSource';
import { TreeRoot } from './TreeRoot/TreeRoot'; import { TreeRoot } from './TreeRoot/TreeRoot';
import { TreeNode } from './Node/TreeNode'; import { TreeNode } from './Node/TreeNode';
@@ -15,7 +15,7 @@ export function useNodeStateChangeAggregator(
useTreeNodes = useCurrentTreeNodes, useTreeNodes = useCurrentTreeNodes,
) { ) {
const { nodes } = useTreeNodes(treeWatcher); const { nodes } = useTreeNodes(treeWatcher);
const { events } = inject(InjectionKeys.useAutoUnsubscribedEvents)(); const { events } = injectKey((keys) => keys.useAutoUnsubscribedEvents);
const onNodeChangeCallback = shallowRef<NodeStateChangeEventCallback>(); const onNodeChangeCallback = shallowRef<NodeStateChangeEventCallback>();

View File

@@ -1,10 +1,9 @@
import { inject } from 'vue'; import { injectKey } from '@/presentation/injectionSymbols';
import { InjectionKeys } from '@/presentation/injectionSymbols';
import { TreeNodeCheckState } from '../TreeView/Node/State/CheckState'; import { TreeNodeCheckState } from '../TreeView/Node/State/CheckState';
import { TreeNodeStateChangedEmittedEvent } from '../TreeView/Bindings/TreeNodeStateChangedEmittedEvent'; import { TreeNodeStateChangedEmittedEvent } from '../TreeView/Bindings/TreeNodeStateChangedEmittedEvent';
export function useCollectionSelectionStateUpdater() { export function useCollectionSelectionStateUpdater() {
const { modifyCurrentState, currentState } = inject(InjectionKeys.useCollectionState)(); const { modifyCurrentState, currentState } = injectKey((keys) => keys.useCollectionState);
function updateNodeSelection(change: TreeNodeStateChangedEmittedEvent) { function updateNodeSelection(change: TreeNodeStateChangedEmittedEvent) {
const { node } = change; const { node } = change;

View File

@@ -1,7 +1,7 @@
import { import {
computed, inject, shallowReadonly, shallowRef, triggerRef, computed, shallowReadonly, shallowRef, triggerRef,
} from 'vue'; } from 'vue';
import { InjectionKeys } from '@/presentation/injectionSymbols'; import { injectKey } from '@/presentation/injectionSymbols';
import { SelectedScript } from '@/application/Context/State/Selection/SelectedScript'; import { SelectedScript } from '@/application/Context/State/Selection/SelectedScript';
import { getScriptNodeId } from './CategoryNodeMetadataConverter'; import { getScriptNodeId } from './CategoryNodeMetadataConverter';
@@ -20,8 +20,8 @@ export function useSelectedScriptNodeIds(scriptNodeIdParser = getScriptNodeId) {
} }
function useSelectedScripts() { function useSelectedScripts() {
const { events } = inject(InjectionKeys.useAutoUnsubscribedEvents)(); const { events } = injectKey((keys) => keys.useAutoUnsubscribedEvents);
const { onStateChange } = inject(InjectionKeys.useCollectionState)(); const { onStateChange } = injectKey((keys) => keys.useCollectionState);
const selectedScripts = shallowRef<readonly SelectedScript[]>([]); const selectedScripts = shallowRef<readonly SelectedScript[]>([]);

View File

@@ -1,9 +1,9 @@
import { import {
Ref, inject, shallowReadonly, shallowRef, Ref, shallowReadonly, shallowRef,
} from 'vue'; } from 'vue';
import { IScript } from '@/domain/IScript'; import { IScript } from '@/domain/IScript';
import { ICategory } from '@/domain/ICategory'; import { ICategory } from '@/domain/ICategory';
import { InjectionKeys } from '@/presentation/injectionSymbols'; import { injectKey } from '@/presentation/injectionSymbols';
import { IReadOnlyUserFilter } from '@/application/Context/State/Filter/IUserFilter'; import { IReadOnlyUserFilter } from '@/application/Context/State/Filter/IUserFilter';
import { IFilterResult } from '@/application/Context/State/Filter/IFilterResult'; import { IFilterResult } from '@/application/Context/State/Filter/IFilterResult';
import { TreeViewFilterEvent, createFilterRemovedEvent, createFilterTriggeredEvent } from '../TreeView/Bindings/TreeInputFilterEvent'; import { TreeViewFilterEvent, createFilterRemovedEvent, createFilterTriggeredEvent } from '../TreeView/Bindings/TreeInputFilterEvent';
@@ -18,8 +18,8 @@ type TreeNodeFilterResultPredicate = (
) => boolean; ) => boolean;
export function useTreeViewFilterEvent() { export function useTreeViewFilterEvent() {
const { onStateChange } = inject(InjectionKeys.useCollectionState)(); const { onStateChange } = injectKey((keys) => keys.useCollectionState);
const { events } = inject(InjectionKeys.useAutoUnsubscribedEvents)(); const { events } = injectKey((keys) => keys.useAutoUnsubscribedEvents);
const latestFilterEvent = shallowRef<TreeViewFilterEvent | undefined>(undefined); const latestFilterEvent = shallowRef<TreeViewFilterEvent | undefined>(undefined);

View File

@@ -1,9 +1,9 @@
import { import {
WatchSource, computed, inject, WatchSource, computed,
ref, watch, ref, watch,
} from 'vue'; } from 'vue';
import { ICategoryCollection } from '@/domain/ICategoryCollection'; import { ICategoryCollection } from '@/domain/ICategoryCollection';
import { InjectionKeys } from '@/presentation/injectionSymbols'; import { injectKey } from '@/presentation/injectionSymbols';
import { TreeInputNodeData } from '../TreeView/Bindings/TreeInputNodeData'; import { TreeInputNodeData } from '../TreeView/Bindings/TreeInputNodeData';
import { NodeMetadata } from '../NodeContent/NodeMetadata'; import { NodeMetadata } from '../NodeContent/NodeMetadata';
import { convertToNodeInput } from './TreeNodeMetadataConverter'; import { convertToNodeInput } from './TreeNodeMetadataConverter';
@@ -17,7 +17,7 @@ export function useTreeViewNodeInput(
}, },
nodeConverter = convertToNodeInput, nodeConverter = convertToNodeInput,
) { ) {
const { currentState } = inject(InjectionKeys.useCollectionState)(); const { currentState } = injectKey((keys) => keys.useCollectionState);
const categoryId = ref<number | undefined>(); const categoryId = ref<number | undefined>();

View File

@@ -18,9 +18,9 @@
</template> </template>
<script lang="ts"> <script lang="ts">
import { defineComponent, inject } from 'vue'; import { defineComponent } from 'vue';
import { OperatingSystem } from '@/domain/OperatingSystem'; import { OperatingSystem } from '@/domain/OperatingSystem';
import { InjectionKeys } from '@/presentation/injectionSymbols'; import { injectKey } from '@/presentation/injectionSymbols';
import AppIcon from '@/presentation/components/Shared/Icon/AppIcon.vue'; import AppIcon from '@/presentation/components/Shared/Icon/AppIcon.vue';
import DownloadUrlListItem from './DownloadUrlListItem.vue'; import DownloadUrlListItem from './DownloadUrlListItem.vue';
@@ -36,7 +36,7 @@ export default defineComponent({
AppIcon, AppIcon,
}, },
setup() { setup() {
const { os: currentOs } = inject(InjectionKeys.useRuntimeEnvironment); const { os: currentOs } = injectKey((keys) => keys.useRuntimeEnvironment);
const supportedDesktops = [ const supportedDesktops = [
...supportedOperativeSystems, ...supportedOperativeSystems,
].sort((os) => (os === currentOs ? 0 : 1)); ].sort((os) => (os === currentOs ? 0 : 1));

View File

@@ -12,9 +12,8 @@
<script lang="ts"> <script lang="ts">
import { import {
defineComponent, PropType, computed, defineComponent, PropType, computed,
inject,
} from 'vue'; } from 'vue';
import { InjectionKeys } from '@/presentation/injectionSymbols'; import { injectKey } from '@/presentation/injectionSymbols';
import { OperatingSystem } from '@/domain/OperatingSystem'; import { OperatingSystem } from '@/domain/OperatingSystem';
export default defineComponent({ export default defineComponent({
@@ -25,8 +24,8 @@ export default defineComponent({
}, },
}, },
setup(props) { setup(props) {
const { info } = inject(InjectionKeys.useApplication); const { info } = injectKey((keys) => keys.useApplication);
const { os: currentOs } = inject(InjectionKeys.useRuntimeEnvironment); const { os: currentOs } = injectKey((keys) => keys.useRuntimeEnvironment);
const isCurrentOs = computed<boolean>(() => { const isCurrentOs = computed<boolean>(() => {
return currentOs === props.operatingSystem; return currentOs === props.operatingSystem;

View File

@@ -41,13 +41,13 @@
</template> </template>
<script lang="ts"> <script lang="ts">
import { defineComponent, computed, inject } from 'vue'; import { defineComponent, computed } from 'vue';
import { InjectionKeys } from '@/presentation/injectionSymbols'; import { injectKey } from '@/presentation/injectionSymbols';
export default defineComponent({ export default defineComponent({
setup() { setup() {
const { info } = inject(InjectionKeys.useApplication); const { info } = injectKey((keys) => keys.useApplication);
const { isDesktop } = inject(InjectionKeys.useRuntimeEnvironment); const { isDesktop } = injectKey((keys) => keys.useRuntimeEnvironment);
const repositoryUrl = computed<string>(() => info.repositoryUrl); const repositoryUrl = computed<string>(() => info.repositoryUrl);
const feedbackUrl = computed<string>(() => info.feedbackUrl); const feedbackUrl = computed<string>(() => info.feedbackUrl);

View File

@@ -45,11 +45,11 @@
<script lang="ts"> <script lang="ts">
import { import {
defineComponent, ref, computed, inject, defineComponent, ref, computed,
} from 'vue'; } from 'vue';
import ModalDialog from '@/presentation/components/Shared/Modal/ModalDialog.vue'; import ModalDialog from '@/presentation/components/Shared/Modal/ModalDialog.vue';
import AppIcon from '@/presentation/components/Shared/Icon/AppIcon.vue'; import AppIcon from '@/presentation/components/Shared/Icon/AppIcon.vue';
import { InjectionKeys } from '@/presentation/injectionSymbols'; import { injectKey } from '@/presentation/injectionSymbols';
import DownloadUrlList from './DownloadUrlList.vue'; import DownloadUrlList from './DownloadUrlList.vue';
import PrivacyPolicy from './PrivacyPolicy.vue'; import PrivacyPolicy from './PrivacyPolicy.vue';
@@ -61,8 +61,8 @@ export default defineComponent({
AppIcon, AppIcon,
}, },
setup() { setup() {
const { info } = inject(InjectionKeys.useApplication); const { info } = injectKey((keys) => keys.useApplication);
const { isDesktop } = inject(InjectionKeys.useRuntimeEnvironment); const { isDesktop } = injectKey((keys) => keys.useRuntimeEnvironment);
const isPrivacyDialogVisible = ref(false); const isPrivacyDialogVisible = ref(false);

View File

@@ -6,12 +6,12 @@
</template> </template>
<script lang="ts"> <script lang="ts">
import { defineComponent, computed, inject } from 'vue'; import { defineComponent, computed } from 'vue';
import { InjectionKeys } from '@/presentation/injectionSymbols'; import { injectKey } from '@/presentation/injectionSymbols';
export default defineComponent({ export default defineComponent({
setup() { setup() {
const { info } = inject(InjectionKeys.useApplication); const { info } = injectKey((keys) => keys.useApplication);
const title = computed(() => info.name); const title = computed(() => info.name);
const subtitle = computed(() => info.slogan); const subtitle = computed(() => info.slogan);

View File

@@ -15,9 +15,8 @@
<script lang="ts"> <script lang="ts">
import { import {
defineComponent, ref, watch, computed, defineComponent, ref, watch, computed,
inject,
} from 'vue'; } from 'vue';
import { InjectionKeys } from '@/presentation/injectionSymbols'; import { injectKey } from '@/presentation/injectionSymbols';
import { NonCollapsing } from '@/presentation/components/Scripts/View/Cards/NonCollapsingDirective'; import { NonCollapsing } from '@/presentation/components/Scripts/View/Cards/NonCollapsingDirective';
import AppIcon from '@/presentation/components/Shared/Icon/AppIcon.vue'; import AppIcon from '@/presentation/components/Shared/Icon/AppIcon.vue';
import { IReadOnlyUserFilter } from '@/application/Context/State/Filter/IUserFilter'; import { IReadOnlyUserFilter } from '@/application/Context/State/Filter/IUserFilter';
@@ -32,8 +31,8 @@ export default defineComponent({
setup() { setup() {
const { const {
modifyCurrentState, onStateChange, currentState, modifyCurrentState, onStateChange, currentState,
} = inject(InjectionKeys.useCollectionState)(); } = injectKey((keys) => keys.useCollectionState);
const { events } = inject(InjectionKeys.useAutoUnsubscribedEvents)(); const { events } = injectKey((keys) => keys.useAutoUnsubscribedEvents);
const searchPlaceholder = computed<string>(() => { const searchPlaceholder = computed<string>(() => {
const { totalScripts } = currentState.value.collection; const { totalScripts } = currentState.value.collection;

View File

@@ -1,10 +1,10 @@
import { inject, type InjectionKey } from 'vue';
import type { useCollectionState } from '@/presentation/components/Shared/Hooks/UseCollectionState'; import type { useCollectionState } from '@/presentation/components/Shared/Hooks/UseCollectionState';
import type { useApplication } from '@/presentation/components/Shared/Hooks/UseApplication'; import type { useApplication } from '@/presentation/components/Shared/Hooks/UseApplication';
import type { useRuntimeEnvironment } from '@/presentation/components/Shared/Hooks/UseRuntimeEnvironment'; import type { useRuntimeEnvironment } from '@/presentation/components/Shared/Hooks/UseRuntimeEnvironment';
import type { useClipboard } from '@/presentation/components/Shared/Hooks/Clipboard/UseClipboard'; import type { useClipboard } from '@/presentation/components/Shared/Hooks/Clipboard/UseClipboard';
import type { useCurrentCode } from '@/presentation/components/Shared/Hooks/UseCurrentCode'; import type { useCurrentCode } from '@/presentation/components/Shared/Hooks/UseCurrentCode';
import type { useAutoUnsubscribedEvents } from '@/presentation/components/Shared/Hooks/UseAutoUnsubscribedEvents'; import type { useAutoUnsubscribedEvents } from '@/presentation/components/Shared/Hooks/UseAutoUnsubscribedEvents';
import type { InjectionKey } from 'vue';
export const InjectionKeys = { export const InjectionKeys = {
useCollectionState: defineTransientKey<ReturnType<typeof useCollectionState>>('useCollectionState'), useCollectionState: defineTransientKey<ReturnType<typeof useCollectionState>>('useCollectionState'),
@@ -15,10 +15,68 @@ export const InjectionKeys = {
useCurrentCode: defineTransientKey<ReturnType<typeof useCurrentCode>>('useCurrentCode'), useCurrentCode: defineTransientKey<ReturnType<typeof useCurrentCode>>('useCurrentCode'),
}; };
function defineSingletonKey<T>(key: string): InjectionKey<T> { export interface InjectionKeyWithLifetime<T> {
return Symbol(key) as InjectionKey<T>; readonly lifetime: InjectionKeyLifetime;
readonly key: InjectionKey<T> & symbol;
} }
function defineTransientKey<T>(key: string): InjectionKey<() => T> { export interface SingletonKey<T> extends InjectionKeyWithLifetime<T> {
return Symbol(key) as InjectionKey<() => T>; readonly lifetime: InjectionKeyLifetime.Singleton;
readonly key: InjectionKey<T> & symbol;
}
export interface TransientKey<T> extends InjectionKeyWithLifetime<() => T> {
readonly lifetime: InjectionKeyLifetime.Transient;
readonly key: InjectionKey<() => T> & symbol;
}
export type AnyLifetimeInjectionKey<T> = InjectionKeyWithLifetime<T> | TransientKey<T>;
export type InjectionKeySelector<T> = (keys: typeof InjectionKeys) => AnyLifetimeInjectionKey<T>;
export function injectKey<T>(
keySelector: InjectionKeySelector<T>,
vueInjector = inject,
): T {
const key = keySelector(InjectionKeys);
const injectedValue = injectRequired(key.key, vueInjector);
if (key.lifetime === InjectionKeyLifetime.Transient) {
const factory = injectedValue as () => T;
const value = factory();
return value;
}
return injectedValue as T;
}
export enum InjectionKeyLifetime {
Singleton,
Transient,
}
function defineSingletonKey<T>(key: string): SingletonKey<T> {
return {
lifetime: InjectionKeyLifetime.Singleton,
key: Symbol(key),
};
}
function defineTransientKey<T>(key: string): TransientKey<T> {
return {
lifetime: InjectionKeyLifetime.Transient,
key: Symbol(key),
};
}
function injectRequired<T>(
key: InjectionKey<T>,
vueInjector = inject,
): T {
const injectedValue = vueInjector(key);
if (injectedValue === undefined) {
throw new Error(`Failed to inject value for key: ${key.description}`);
}
return injectedValue;
} }

View File

@@ -0,0 +1,53 @@
import { it, describe, expect } from 'vitest';
import { shallowMount } from '@vue/test-utils';
import { defineComponent, inject } from 'vue';
import { InjectionKeySelector, InjectionKeys, injectKey } from '@/presentation/injectionSymbols';
import { provideDependencies } from '@/presentation/bootstrapping/DependencyProvider';
import { buildContext } from '@/application/Context/ApplicationContextFactory';
import { IApplicationContext } from '@/application/Context/IApplicationContext';
describe('DependencyResolution', () => {
describe('all dependencies can be injected', async () => {
// arrange
const context = await buildContext();
const dependencies = collectProvidedKeys(context);
Object.values(InjectionKeys).forEach((key) => {
it(`"${key.key.description}"`, () => {
// act
const resolvedDependency = resolve(() => key, dependencies);
// assert
expect(resolvedDependency).to.toBeDefined();
});
});
});
});
type ProvidedKeys = Record<symbol, unknown>;
function collectProvidedKeys(context: IApplicationContext): ProvidedKeys {
const providedKeys: ProvidedKeys = {};
provideDependencies(context, {
inject,
provide: (key, value) => {
providedKeys[key as symbol] = value;
},
});
return providedKeys;
}
function resolve<T>(
selector: InjectionKeySelector<T>,
providedKeys: ProvidedKeys,
): T | undefined {
let injectedDependency: T | undefined;
shallowMount(defineComponent({
setup() {
injectedDependency = injectKey(selector);
},
}), {
global: {
provide: providedKeys,
},
});
return injectedDependency;
}

View File

@@ -0,0 +1,3 @@
# Composite Tests
The `composite` directory contains integration tests that validate the cooperative functionality of multiple components within the application, going beyond unit tests to ensure interconnected parts perform as expected.

View File

@@ -0,0 +1,16 @@
import { describe } from 'vitest';
import { createApp } from 'vue';
import { ApplicationBootstrapper } from '@/presentation/bootstrapping/ApplicationBootstrapper';
import { expectDoesNotThrowAsync } from '@tests/shared/Assertions/ExpectThrowsAsync';
describe('ApplicationBootstrapper', () => {
it('can bootstrap without errors', async () => {
// arrange
const sut = new ApplicationBootstrapper();
const vueApp = createApp({});
// act
const act = () => sut.bootstrap(vueApp);
// assert
await expectDoesNotThrowAsync(act);
});
});

View File

@@ -7,7 +7,7 @@ import { IApplication } from '@/domain/IApplication';
import { RuntimeEnvironmentStub } from '@tests/unit/shared/Stubs/RuntimeEnvironmentStub'; import { RuntimeEnvironmentStub } from '@tests/unit/shared/Stubs/RuntimeEnvironmentStub';
import { ApplicationStub } from '@tests/unit/shared/Stubs/ApplicationStub'; import { ApplicationStub } from '@tests/unit/shared/Stubs/ApplicationStub';
import { CategoryCollectionStub } from '@tests/unit/shared/Stubs/CategoryCollectionStub'; import { CategoryCollectionStub } from '@tests/unit/shared/Stubs/CategoryCollectionStub';
import { expectThrowsAsync } from '@tests/unit/shared/Assertions/ExpectThrowsAsync'; import { expectThrowsAsync } from '@tests/shared/Assertions/ExpectThrowsAsync';
describe('ApplicationContextFactory', () => { describe('ApplicationContextFactory', () => {
describe('buildContext', () => { describe('buildContext', () => {

View File

@@ -2,7 +2,7 @@ import { describe, it, expect } from 'vitest';
import { RuntimeEnvironmentStub } from '@tests/unit/shared/Stubs/RuntimeEnvironmentStub'; import { RuntimeEnvironmentStub } from '@tests/unit/shared/Stubs/RuntimeEnvironmentStub';
import { OperatingSystem } from '@/domain/OperatingSystem'; import { OperatingSystem } from '@/domain/OperatingSystem';
import { CodeRunner } from '@/infrastructure/CodeRunner'; import { CodeRunner } from '@/infrastructure/CodeRunner';
import { expectThrowsAsync } from '@tests/unit/shared/Assertions/ExpectThrowsAsync'; import { expectThrowsAsync } from '@tests/shared/Assertions/ExpectThrowsAsync';
import { SystemOperationsStub } from '@tests/unit/shared/Stubs/SystemOperationsStub'; import { SystemOperationsStub } from '@tests/unit/shared/Stubs/SystemOperationsStub';
import { OperatingSystemOpsStub } from '@tests/unit/shared/Stubs/OperatingSystemOpsStub'; import { OperatingSystemOpsStub } from '@tests/unit/shared/Stubs/OperatingSystemOpsStub';
import { LocationOpsStub } from '@tests/unit/shared/Stubs/LocationOpsStub'; import { LocationOpsStub } from '@tests/unit/shared/Stubs/LocationOpsStub';

View File

@@ -1,7 +1,7 @@
import { describe, it, expect } from 'vitest'; import { describe, it, expect } from 'vitest';
import { BootstrapperStub } from '@tests/unit/shared/Stubs/BootstrapperStub'; import { BootstrapperStub } from '@tests/unit/shared/Stubs/BootstrapperStub';
import { ApplicationBootstrapper } from '@/presentation/bootstrapping/ApplicationBootstrapper'; import { ApplicationBootstrapper } from '@/presentation/bootstrapping/ApplicationBootstrapper';
import { expectThrowsAsync } from '@tests/unit/shared/Assertions/ExpectThrowsAsync'; import { expectThrowsAsync } from '@tests/shared/Assertions/ExpectThrowsAsync';
import type { App } from 'vue'; import type { App } from 'vue';
describe('ApplicationBootstrapper', () => { describe('ApplicationBootstrapper', () => {

View File

@@ -18,8 +18,9 @@ describe('DependencyProvider', () => {
useCurrentCode: createTransientTests(), useCurrentCode: createTransientTests(),
}; };
Object.entries(testCases).forEach(([key, runTests]) => { Object.entries(testCases).forEach(([key, runTests]) => {
describe(`Key: "${key}"`, () => { const registeredKey = InjectionKeys[key].key;
runTests(InjectionKeys[key]); describe(`Key: "${registeredKey.toString()}"`, () => {
runTests(registeredKey);
}); });
}); });
}); });

View File

@@ -1,7 +1,7 @@
import { describe, it, expect } from 'vitest'; import { describe, it, expect } from 'vitest';
import { ISanityCheckOptions } from '@/infrastructure/RuntimeSanity/Common/ISanityCheckOptions'; import { ISanityCheckOptions } from '@/infrastructure/RuntimeSanity/Common/ISanityCheckOptions';
import { RuntimeSanityValidator } from '@/presentation/bootstrapping/Modules/RuntimeSanityValidator'; import { RuntimeSanityValidator } from '@/presentation/bootstrapping/Modules/RuntimeSanityValidator';
import { expectDoesNotThrowAsync, expectThrowsAsync } from '@tests/unit/shared/Assertions/ExpectThrowsAsync'; import { expectDoesNotThrowAsync, expectThrowsAsync } from '@tests/shared/Assertions/ExpectThrowsAsync';
describe('RuntimeSanityValidator', () => { describe('RuntimeSanityValidator', () => {
it('calls validator with correct options upon bootstrap', async () => { it('calls validator with correct options upon bootstrap', async () => {

View File

@@ -39,12 +39,12 @@ function mountComponent(options?: {
return shallowMount(CodeCopyButton, { return shallowMount(CodeCopyButton, {
global: { global: {
provide: { provide: {
[InjectionKeys.useClipboard as symbol]: () => ( [InjectionKeys.useClipboard.key]: () => (
options?.clipboard options?.clipboard
? new UseClipboardStub(options.clipboard) ? new UseClipboardStub(options.clipboard)
: new UseClipboardStub() : new UseClipboardStub()
).get(), ).get(),
[InjectionKeys.useCurrentCode as symbol]: () => ( [InjectionKeys.useCurrentCode.key]: () => (
options.currentCode === undefined options.currentCode === undefined
? new UseCurrentCodeStub() ? new UseCurrentCodeStub()
: new UseCurrentCodeStub().withCurrentCode(options.currentCode) : new UseCurrentCodeStub().withCurrentCode(options.currentCode)

View File

@@ -1,7 +1,7 @@
import { describe, it, expect } from 'vitest'; import { describe, it, expect } from 'vitest';
import { shallowMount } from '@vue/test-utils'; import { shallowMount } from '@vue/test-utils';
import CodeInstruction from '@/presentation/components/Code/CodeButtons/Save/Instructions/CodeInstruction.vue'; import CodeInstruction from '@/presentation/components/Code/CodeButtons/Save/Instructions/CodeInstruction.vue';
import { expectThrowsAsync } from '@tests/unit/shared/Assertions/ExpectThrowsAsync'; import { expectThrowsAsync } from '@tests/shared/Assertions/ExpectThrowsAsync';
import { InjectionKeys } from '@/presentation/injectionSymbols'; import { InjectionKeys } from '@/presentation/injectionSymbols';
import { Clipboard } from '@/presentation/components/Shared/Hooks/Clipboard/Clipboard'; import { Clipboard } from '@/presentation/components/Shared/Hooks/Clipboard/Clipboard';
import { UseClipboardStub } from '@tests/unit/shared/Stubs/UseClipboardStub'; import { UseClipboardStub } from '@tests/unit/shared/Stubs/UseClipboardStub';
@@ -74,7 +74,7 @@ function mountComponent(options?: {
return shallowMount(CodeInstruction, { return shallowMount(CodeInstruction, {
global: { global: {
provide: { provide: {
[InjectionKeys.useClipboard as symbol]: [InjectionKeys.useClipboard.key]:
() => { () => {
if (options?.clipboard) { if (options?.clipboard) {
return new UseClipboardStub(options.clipboard).get(); return new UseClipboardStub(options.clipboard).get();

View File

@@ -406,11 +406,11 @@ function mountComponent(options?: {
return shallowMount(TheScriptsView, { return shallowMount(TheScriptsView, {
global: { global: {
provide: { provide: {
[InjectionKeys.useCollectionState as symbol]: [InjectionKeys.useCollectionState.key]:
() => options?.useCollectionState ?? new UseCollectionStateStub().get(), () => options?.useCollectionState ?? new UseCollectionStateStub().get(),
[InjectionKeys.useApplication as symbol]: [InjectionKeys.useApplication.key]:
new UseApplicationStub().get(), new UseApplicationStub().get(),
[InjectionKeys.useAutoUnsubscribedEvents as symbol]: [InjectionKeys.useAutoUnsubscribedEvents.key]:
() => new UseAutoUnsubscribedEventsStub().get(), () => new UseAutoUnsubscribedEventsStub().get(),
}, },
}, },

View File

@@ -79,7 +79,7 @@ function mountWrapperComponent(nodeWatcher: WatchSource<ReadOnlyTreeNode | undef
{ {
global: { global: {
provide: { provide: {
[InjectionKeys.useAutoUnsubscribedEvents as symbol]: [InjectionKeys.useAutoUnsubscribedEvents.key]:
() => new UseAutoUnsubscribedEventsStub().get(), () => new UseAutoUnsubscribedEventsStub().get(),
}, },
}, },

View File

@@ -70,7 +70,7 @@ function mountWrapperComponent(treeWatcher: WatchSource<TreeRoot | undefined>) {
{ {
global: { global: {
provide: { provide: {
[InjectionKeys.useAutoUnsubscribedEvents as symbol]: [InjectionKeys.useAutoUnsubscribedEvents.key]:
() => new UseAutoUnsubscribedEventsStub().get(), () => new UseAutoUnsubscribedEventsStub().get(),
}, },
}, },

View File

@@ -336,7 +336,7 @@ class UseNodeStateChangeAggregatorBuilder {
{ {
global: { global: {
provide: { provide: {
[InjectionKeys.useAutoUnsubscribedEvents as symbol]: [InjectionKeys.useAutoUnsubscribedEvents.key]:
() => this.events.get(), () => this.events.get(),
}, },
}, },

View File

@@ -172,7 +172,7 @@ function mountWrapperComponent() {
}, { }, {
global: { global: {
provide: { provide: {
[InjectionKeys.useCollectionState as symbol]: () => useStateStub.get(), [InjectionKeys.useCollectionState.key]: () => useStateStub.get(),
}, },
}, },
}); });

View File

@@ -239,9 +239,9 @@ function mountWrapperComponent(scenario?: {
}, { }, {
global: { global: {
provide: { provide: {
[InjectionKeys.useCollectionState as symbol]: [InjectionKeys.useCollectionState.key]:
() => useStateStub.get(), () => useStateStub.get(),
[InjectionKeys.useAutoUnsubscribedEvents as symbol]: [InjectionKeys.useAutoUnsubscribedEvents.key]:
() => (scenario?.useAutoUnsubscribedEvents ?? new UseAutoUnsubscribedEventsStub()).get(), () => (scenario?.useAutoUnsubscribedEvents ?? new UseAutoUnsubscribedEventsStub()).get(),
}, },
}, },

View File

@@ -148,9 +148,9 @@ function mountWrapperComponent(options?: {
}, { }, {
global: { global: {
provide: { provide: {
[InjectionKeys.useCollectionState as symbol]: [InjectionKeys.useCollectionState.key]:
() => useStateStub.get(), () => useStateStub.get(),
[InjectionKeys.useAutoUnsubscribedEvents as symbol]: [InjectionKeys.useAutoUnsubscribedEvents.key]:
() => new UseAutoUnsubscribedEventsStub().get(), () => new UseAutoUnsubscribedEventsStub().get(),
}, },
}, },

View File

@@ -106,7 +106,7 @@ function mountWrapperComponent(categoryIdWatcher: WatchSource<number | undefined
}, { }, {
global: { global: {
provide: { provide: {
[InjectionKeys.useCollectionState as symbol]: () => useStateStub.get(), [InjectionKeys.useCollectionState.key]: () => useStateStub.get(),
}, },
}, },
}); });

View File

@@ -1,7 +1,7 @@
import { describe, it, expect } from 'vitest'; import { describe, it, expect } from 'vitest';
import { BrowserClipboard, NavigatorClipboard } from '@/presentation/components/Shared/Hooks/Clipboard/BrowserClipboard'; import { BrowserClipboard, NavigatorClipboard } from '@/presentation/components/Shared/Hooks/Clipboard/BrowserClipboard';
import { StubWithObservableMethodCalls } from '@tests/unit/shared/Stubs/StubWithObservableMethodCalls'; import { StubWithObservableMethodCalls } from '@tests/unit/shared/Stubs/StubWithObservableMethodCalls';
import { expectThrowsAsync } from '@tests/unit/shared/Assertions/ExpectThrowsAsync'; import { expectThrowsAsync } from '@tests/shared/Assertions/ExpectThrowsAsync';
describe('BrowserClipboard', () => { describe('BrowserClipboard', () => {
describe('writeText', () => { describe('writeText', () => {

View File

@@ -1,23 +1,77 @@
import { describe, it, expect } from 'vitest'; import { describe, it, expect } from 'vitest';
import { InjectionKeys } from '@/presentation/injectionSymbols'; import { InjectionKeySelector, InjectionKeys, injectKey } from '@/presentation/injectionSymbols';
import { getAbsentObjectTestCases } from '../shared/TestCases/AbsentTests';
describe('injectionSymbols', () => { describe('injectionSymbols', () => {
Object.entries(InjectionKeys).forEach(([key, symbol]) => { describe('InjectionKeys', () => {
describe(`symbol for ${key}`, () => { Object.entries(InjectionKeys).forEach(([key, injectionKey]) => {
it('should be a symbol type', () => { describe(`symbol for ${injectionKey.key.toString()}`, () => {
// arrange it('should be a symbol type', () => {
const expectedType = Symbol; // arrange
// act const actualKey = injectionKey.key;
// assert const expectedType = Symbol;
expect(symbol).to.be.instanceOf(expectedType); // act
// assert
expect(actualKey).to.be.instanceOf(expectedType);
});
it(`should have a description matching the key "${injectionKey.key.toString()}"`, () => {
// arrange
const actualKey = injectionKey.key;
const expected = key;
// act
const actual = actualKey.description;
// assert
expect(expected).to.equal(actual);
});
}); });
it(`should have a description matching the key "${key}"`, () => { });
// arrange });
const expected = key; describe('injectKey', () => {
// act it('returns the correct value for singleton keys', () => {
const actual = symbol.description; // arrange
// assert const mockValue = { someProperty: 'someValue' };
expect(expected).to.equal(actual); // act
const mockInject = () => mockValue;
const result = injectKey((keys) => keys.useApplication, mockInject);
// assert
expect(result).to.equal(mockValue);
});
it('invokes and returns result from factory function for transient keys', () => {
// arrange
const mockValue = { anotherProperty: 'anotherValue' };
const mockFactory = () => mockValue;
const mockInject = () => mockFactory;
// act
const result = injectKey((keys) => keys.useCollectionState, mockInject);
// assert
expect(result).to.equal(mockValue);
});
describe('throws error when no value is provided for a key', () => {
// arrange
const testScenarios: ReadonlyArray<{
readonly name: string,
readonly act: (selector: InjectionKeySelector<unknown>) => void,
}> = getAbsentObjectTestCases().flatMap((absentTest) => [
{
name: `singleton factory: ${absentTest.absentValue}`,
act: (selector) => injectKey(selector, () => (() => absentTest.absentValue)),
},
{
name: `transient: ${absentTest.absentValue}`,
act: (selector) => injectKey(selector, () => absentTest.absentValue),
},
]);
testScenarios.forEach((testCase) => {
it(testCase.name, () => {
// arrange
const key = InjectionKeys.useRuntimeEnvironment;
const expectedError = `Failed to inject value for key: ${key.key.description}`;
const selector: InjectionKeySelector<typeof key> = () => key;
// act
const act = () => testCase.act(selector);
// assert
expect(act).to.throw(expectedError);
});
}); });
}); });
}); });