@myparcel-dev/pdk-admin 2.3.0 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/actions/composables/mutations/orders/useExportOrdersMutation.d.ts +1 -1
  3. package/dist/composables/language/useLanguage.d.ts +6 -0
  4. package/dist/pdk/PdkAdmin.d.ts +26 -2
  5. package/dist/pdk/boot.d.ts +5 -0
  6. package/dist/sdk/index.d.ts +1 -0
  7. package/dist/sdk/requestHeaders.d.ts +10 -0
  8. package/dist/services/mutations/getModalMutationOptions.d.ts +7 -1
  9. package/dist/services/mutations/index.d.ts +1 -0
  10. package/dist/services/mutations/modalMutationToken.d.ts +16 -0
  11. package/dist/stores/useModalStore.d.ts +9 -1
  12. package/dist/types/admin.types.d.ts +10 -0
  13. package/dist/types/configuration.types.d.ts +12 -0
  14. package/package.json +2 -2
  15. package/src/actions/composables/mutations/orders/useExportOrdersMutation.spec.ts +75 -0
  16. package/src/actions/composables/mutations/orders/useExportOrdersMutation.ts +17 -6
  17. package/src/components/common/TabNavigation.spec.ts +78 -0
  18. package/src/components/common/TabNavigation.vue +7 -5
  19. package/src/composables/language/resetLanguageCache.spec.ts +24 -0
  20. package/src/composables/language/useLanguage.ts +13 -0
  21. package/src/pdk/PdkAdmin.spec.ts +97 -0
  22. package/src/pdk/PdkAdmin.ts +63 -7
  23. package/src/pdk/boot.ts +13 -3
  24. package/src/pdk/createPdkAdmin.spec.ts +75 -0
  25. package/src/pdk/createPdkAdmin.ts +2 -0
  26. package/src/pdk/instance/plugins/createStorePlugin.spec.ts +44 -0
  27. package/src/pdk/instance/plugins/createStorePlugin.ts +12 -7
  28. package/src/pdk/instance/plugins/createVueQueryPlugin.spec.ts +29 -0
  29. package/src/pdk/instance/plugins/createVueQueryPlugin.ts +7 -7
  30. package/src/pdk/setupAdminApp.ts +3 -0
  31. package/src/sdk/composables/usePdkAdminApi.ts +3 -0
  32. package/src/sdk/index.ts +1 -0
  33. package/src/sdk/requestHeaders.spec.ts +54 -0
  34. package/src/sdk/requestHeaders.ts +36 -0
  35. package/src/services/mutations/getModalMutationOptions.spec.ts +59 -0
  36. package/src/services/mutations/getModalMutationOptions.ts +23 -15
  37. package/src/services/mutations/index.ts +1 -0
  38. package/src/services/mutations/modalMutationToken.ts +27 -0
  39. package/src/stores/useModalStore.spec.ts +33 -0
  40. package/src/stores/useModalStore.ts +13 -1
  41. package/src/types/admin.types.ts +12 -0
  42. package/src/types/configuration.types.ts +14 -0
package/CHANGELOG.md CHANGED
@@ -2,6 +2,18 @@
2
2
 
3
3
  <!-- MONOWEAVE:BELOW -->
4
4
 
5
+ ## [2.4.0](https://github.com/myparcelnl/js-pdk/compare/@myparcel-dev/pdk-admin@2.3.0...@myparcel-dev/pdk-admin@2.4.0) "@myparcel-dev/pdk-admin" (2026-10-22)
6
+
7
+
8
+ ### Features
9
+
10
+ * **admin:** allow dynamic request headers ([#499](https://github.com/myparcelnl/js-pdk/issues/499)) ([35c3b02](https://github.com/myparcelnl/js-pdk/commit/35c3b02f7307043e5c6a7a3fa8cae545703b067c))
11
+ * **admin:** allow turning off the tab hash ([#502](https://github.com/myparcelnl/js-pdk/issues/502)) ([f1bb842](https://github.com/myparcelnl/js-pdk/commit/f1bb8424b155958cf2d7cc1541758142b94eb8a0))
12
+ * **admin:** support remounting the admin in a single-page app ([#501](https://github.com/myparcelnl/js-pdk/issues/501)) ([9912af5](https://github.com/myparcelnl/js-pdk/commit/9912af591f2e72ef128d5bd5f7a5cc4389ab13d8))
13
+
14
+
15
+
16
+
5
17
  ## [2.3.0](https://github.com/myparcelnl/js-pdk/compare/@myparcel-dev/pdk-admin@2.2.7...@myparcel-dev/pdk-admin@2.3.0) "@myparcel-dev/pdk-admin" (2026-10-15)
6
18
 
7
19
 
@@ -1,5 +1,5 @@
1
- import { BackendEndpoint } from '@myparcel-dev/pdk-common';
2
1
  import { type OneOrMore } from '@myparcel-dev/ts-utils';
2
+ import { BackendEndpoint } from '@myparcel-dev/pdk-common';
3
3
  import { type ResolvedQuery } from '../../../../stores';
4
4
  import { MutationMode } from '../../../../services';
5
5
  export declare const useExportOrdersMutation: (orderIds?: OneOrMore<string>, mode?: MutationMode) => ResolvedQuery<BackendEndpoint.ExportOrders>;
@@ -19,5 +19,11 @@ type UseLanguage = {
19
19
  */
20
20
  translate(key?: Translation, replacers?: Replacers): string;
21
21
  };
22
+ /**
23
+ * Clears the cached translations. createPdkAdmin() calls it, so a new admin
24
+ * instance, for example after a language change in a single-page app, uses its
25
+ * own translations.
26
+ */
27
+ export declare const resetLanguageCache: () => void;
22
28
  export declare const useLanguage: () => UseLanguage;
23
29
  export {};
@@ -5,11 +5,35 @@ export declare class PdkAdmin {
5
5
  readonly config: AdminConfiguration;
6
6
  readonly context: AdminContextObject;
7
7
  readonly renderedComponents: string[];
8
+ /**
9
+ * One store and one query client per instance, shared by its apps. A page that
10
+ * creates a new instance after unmounting the apps of the previous one (for
11
+ * example a single-page admin) then starts without stale queries.
12
+ */
13
+ protected readonly store: import("pinia").Pinia;
14
+ protected readonly queryClient: import("@tanstack/vue-query").QueryClient;
15
+ private readonly disposers;
8
16
  constructor(config: AdminConfiguration, context: AdminContextObject);
9
17
  /**
10
- * Render a views in given selector.
18
+ * Register cleanup work for dispose().
19
+ */
20
+ onDispose(disposer: () => void): void;
21
+ /**
22
+ * Stop this instance, for example when a single-page app leaves the page.
23
+ * Unmount the apps that render() returned first. Safe to call twice.
24
+ *
25
+ * createPdkAdmin() reads the context from the boot element once. To create
26
+ * the next instance, render a new boot element.
27
+ *
28
+ * The cached queries go at once. A request that is still running reports to
29
+ * the admin on screen when it finishes.
30
+ */
31
+ dispose(): void;
32
+ /**
33
+ * Render a view in the given selector. Returns the app, so the caller can
34
+ * unmount it, or undefined when mounting failed.
11
35
  */
12
- render(view: AdminView, selector: string): Promise<void>;
36
+ render(view: AdminView, selector: string): Promise<App | undefined>;
13
37
  protected createApp(view: AdminView, appConfig: AdminAppConfig): Promise<App>;
14
38
  /**
15
39
  * Create a unique app name for components that are rendered multiple times.
@@ -1,3 +1,8 @@
1
1
  import { type AdminContextObject } from '../types';
2
2
  import { type PdkAdmin } from './PdkAdmin';
3
+ /**
4
+ * Sends the boot event now and again on every ping, until the instance is
5
+ * disposed. The listener and its cleanup exist before the first event, so a
6
+ * handler of that event can already dispose the instance.
7
+ */
3
8
  export declare const boot: (pdkAdmin: PdkAdmin, context: AdminContextObject) => void;
@@ -1,3 +1,4 @@
1
1
  export * from './PdkFetchClient';
2
2
  export * from './composables';
3
3
  export * from './endpoints';
4
+ export * from './requestHeaders';
@@ -0,0 +1,10 @@
1
+ export type RequestHeaders = Record<string, string>;
2
+ export type RequestHeadersProvider = () => RequestHeaders | Promise<RequestHeaders>;
3
+ export declare const setRequestHeadersProvider: (newProvider: RequestHeadersProvider | undefined) => void;
4
+ /**
5
+ * Request interceptor. Calls the provider for every request, so a short-lived
6
+ * token is always current.
7
+ */
8
+ export declare const addRequestHeaders: <T extends {
9
+ headers?: RequestHeaders;
10
+ }>(options: T) => Promise<T>;
@@ -1,2 +1,8 @@
1
1
  import { type MutationOptions } from '@tanstack/vue-query';
2
- export declare const getModalMutationOptions: <TData = unknown, TError = unknown, TVariables = void, TContext = unknown>() => MutationOptions<TData, TError, TVariables, TContext>;
2
+ import { type ModalMutationContext } from './modalMutationToken';
3
+ /**
4
+ * Options for a mutation that a modal starts. The callbacks only change the
5
+ * modal when it is still the modal that started the mutation. Pass the default
6
+ * mutation options, so their onMutate still runs.
7
+ */
8
+ export declare const getModalMutationOptions: <TData = unknown, TError = unknown, TVariables = void>(defaultOptions?: MutationOptions<TData, TError, TVariables>) => MutationOptions<TData, TError, TVariables, ModalMutationContext>;
@@ -1,3 +1,4 @@
1
1
  export * from './getCallbackForMutationMode';
2
2
  export * from './getModalMutationOptions';
3
+ export * from './modalMutationToken';
3
4
  export * from './mutationMode';
@@ -0,0 +1,16 @@
1
+ import { type ModalToken } from '../../stores';
2
+ export type ModalMutationContext = {
3
+ modalToken: ModalToken | null;
4
+ };
5
+ /**
6
+ * Creates an onMutate that keeps the token of the modal that is open when the
7
+ * mutation starts. Pass the onMutate it replaces, for example the default one
8
+ * of the query client, so that one still runs.
9
+ */
10
+ export declare const keepModalToken: <TVariables>(onMutate?: (variables: TVariables) => unknown) => (variables: TVariables) => ModalMutationContext;
11
+ /**
12
+ * Tells if the modal that was open when the mutation started is still open.
13
+ * Use it in late mutation callbacks, so they do not change a modal that the
14
+ * user opened in the meantime.
15
+ */
16
+ export declare const isSameModal: (context: ModalMutationContext | undefined) => boolean;
@@ -3,14 +3,22 @@ import { type AdminModalContext } from '../types';
3
3
  import { type AdminModalKey } from '../data';
4
4
  type ModalOpenFn = <K extends AdminModalKey>(modal: K, context?: AdminModalContext<K>) => void;
5
5
  type ModalCloseFn = <K extends AdminModalKey>(modal: K) => void;
6
+ /**
7
+ * Identifies one opened modal. Every open() creates a new object, so a token
8
+ * never matches another modal, also not a modal in another admin instance.
9
+ */
10
+ export type ModalToken = Readonly<{
11
+ modal: AdminModalKey;
12
+ }>;
6
13
  type ModalStore = {
7
14
  loading: Ref<boolean>;
8
15
  opened: Ref<AdminModalKey | null>;
9
16
  context: Ref<UnwrapNestedRefs<AdminModalContext>>;
17
+ token: Ref<ModalToken | null>;
10
18
  onOpen(callback: ModalOpenFn): void;
11
19
  onClose(callback: ModalCloseFn): void;
12
20
  open<K extends AdminModalKey>(modal: K, newContext?: AdminModalContext<K>): void;
13
21
  close(): void;
14
22
  };
15
- export declare const useModalStore: import("pinia").StoreDefinition<"modal", import("pinia")._UnwrapAll<Pick<ModalStore, "context" | "loading" | "opened">>, Pick<ModalStore, never>, Pick<ModalStore, "open" | "close" | "onOpen" | "onClose">>;
23
+ export declare const useModalStore: import("pinia").StoreDefinition<"modal", import("pinia")._UnwrapAll<Pick<ModalStore, "context" | "loading" | "opened" | "token">>, Pick<ModalStore, never>, Pick<ModalStore, "open" | "close" | "onOpen" | "onClose">>;
16
24
  export {};
@@ -1,4 +1,6 @@
1
1
  import { type Component } from 'vue';
2
+ import { type Pinia } from 'pinia';
3
+ import { type QueryClient } from '@tanstack/vue-query';
2
4
  import { type PdkLogger } from '../services';
3
5
  import { type ADMIN_COMPONENT_PREFIX, type AdminComponent, type AdminView, type optionalAdminActionContainerComponentNames, type optionalAdminComponentNames, type optionalAdminPlainWrapperComponentNames, type requiredAdminComponentNames } from '../data';
4
6
  import { type AdminContextObject, type AdminInstanceContext } from './context.types';
@@ -20,6 +22,14 @@ export interface AdminAppConfig {
20
22
  context: AdminContextObject;
21
23
  logger: PdkLogger;
22
24
  view?: AdminView;
25
+ /**
26
+ * Store of the PdkAdmin instance, shared by its apps. Without it, all apps share one store.
27
+ */
28
+ store?: Pinia;
29
+ /**
30
+ * Query client of the PdkAdmin instance, shared by its apps. Without it, all apps share one client.
31
+ */
32
+ queryClient?: QueryClient;
23
33
  }
24
34
  export interface AdminInstance extends Omit<AdminAppConfig, 'context'> {
25
35
  context: Partial<AdminInstanceContext>;
@@ -2,6 +2,7 @@ import { type PiniaPluginContext } from 'pinia';
2
2
  import { type FormConfiguration, type InteractiveElementInstance } from '@myparcel-dev/vue-form-builder';
3
3
  import { type MakeOptional } from '@myparcel-dev/ts-utils';
4
4
  import { type LogLevel } from '../services';
5
+ import { type RequestHeadersProvider } from '../sdk/requestHeaders';
5
6
  import { type FORM_KEYS } from '../forms';
6
7
  import { type FormatterObject } from '../composables';
7
8
  import { type AdminContextObject } from './context.types';
@@ -90,6 +91,17 @@ export type AdminConfiguration = {
90
91
  * Callback to generate a field id.
91
92
  */
92
93
  generateFieldId(element: InteractiveElementInstance): string;
94
+ /**
95
+ * Gives extra headers for every request to the PDK backend endpoint, for
96
+ * example a short-lived bearer token. Called once per request.
97
+ */
98
+ getRequestHeaders?: RequestHeadersProvider;
99
+ /**
100
+ * Read and write the active tab in window.location.hash. Turn it off when the
101
+ * host app routes with the hash, such as the Shopware administration.
102
+ * Defaults to true.
103
+ */
104
+ useLocationHash?: boolean;
93
105
  };
94
106
  export type AdminConfigurationPreset = Omit<Partial<AdminConfiguration>, 'components'>;
95
107
  export type InputAdminConfiguration = MakeOptional<AdminConfiguration, 'generateFieldId'>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@myparcel-dev/pdk-admin",
3
- "version": "2.3.0",
3
+ "version": "2.4.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/myparcelnl/js-pdk.git",
@@ -37,7 +37,7 @@
37
37
  },
38
38
  "dependencies": {
39
39
  "@myparcel-dev/constants": "^2.9.0",
40
- "@myparcel-dev/pdk-common": "^2.3.0",
40
+ "@myparcel-dev/pdk-common": "^2.3.1",
41
41
  "@myparcel-dev/sdk": "^5.1.0",
42
42
  "@myparcel-dev/vue-form-builder": "1.0.0-beta.42.6",
43
43
  "@tanstack/vue-query": "~4.43.0",
@@ -0,0 +1,75 @@
1
+ // @vitest-environment happy-dom
2
+
3
+ import {createApp, defineComponent} from 'vue';
4
+ import {afterEach, describe, expect, it, vi} from 'vitest';
5
+ import {createPinia} from 'pinia';
6
+ import {QueryClient, VueQueryPlugin} from '@tanstack/vue-query';
7
+ import {useModalStore} from '../../../../stores';
8
+ import {AdminModalKey} from '../../../../data';
9
+ import {useExportOrdersMutation} from './useExportOrdersMutation';
10
+
11
+ const exportOrders = vi.fn();
12
+
13
+ vi.mock('../../../../sdk', () => ({usePdkAdminApi: () => ({exportOrders})}));
14
+
15
+ const mountMutation = () => {
16
+ let mutation: ReturnType<typeof useExportOrdersMutation> | undefined;
17
+ const app = createApp(
18
+ defineComponent({
19
+ setup() {
20
+ mutation = useExportOrdersMutation('1');
21
+
22
+ return () => null;
23
+ },
24
+ }),
25
+ );
26
+
27
+ app.use(createPinia());
28
+ app.use(VueQueryPlugin, {queryClient: new QueryClient()});
29
+ app.mount(document.createElement('div'));
30
+
31
+ return {
32
+ app,
33
+ mutation: mutation as ReturnType<typeof useExportOrdersMutation>,
34
+ };
35
+ };
36
+
37
+ describe('useExportOrdersMutation', () => {
38
+ afterEach(() => {
39
+ exportOrders.mockReset();
40
+ });
41
+
42
+ it('closes the modal that started the export', async () => {
43
+ exportOrders.mockResolvedValue([]);
44
+ const {app, mutation} = mountMutation();
45
+ const modalStore = app.runWithContext(() => useModalStore());
46
+
47
+ modalStore.open(AdminModalKey.ShipmentOptions);
48
+ await mutation.mutateAsync({} as never);
49
+
50
+ expect(modalStore.opened).toBeNull();
51
+ });
52
+
53
+ it('leaves a modal open that the user opened while the export ran', async () => {
54
+ let finish: (value: unknown[]) => void = () => undefined;
55
+ exportOrders.mockReturnValue(
56
+ new Promise((resolve) => {
57
+ finish = resolve;
58
+ }),
59
+ );
60
+ const {app, mutation} = mountMutation();
61
+ const modalStore = app.runWithContext(() => useModalStore());
62
+
63
+ modalStore.open(AdminModalKey.ShipmentOptions);
64
+ const done = mutation.mutateAsync({} as never);
65
+ await vi.waitFor(() => expect(exportOrders).toHaveBeenCalled());
66
+
67
+ // The user closes the modal with Escape and opens the modal of another order.
68
+ modalStore.close();
69
+ modalStore.open(AdminModalKey.ShipmentOptions);
70
+ finish([]);
71
+ await done;
72
+
73
+ expect(modalStore.opened).toBe(AdminModalKey.ShipmentOptions);
74
+ });
75
+ });
@@ -1,11 +1,17 @@
1
1
  import {useQueryClient} from '@tanstack/vue-query';
2
- import {BackendEndpoint} from '@myparcel-dev/pdk-common';
3
2
  import {type OneOrMore, toArray} from '@myparcel-dev/ts-utils';
3
+ import {BackendEndpoint} from '@myparcel-dev/pdk-common';
4
4
  import {usePdkMutation} from '../usePdkMutation';
5
5
  import {encodeArrayParameter, formToBody} from '../../../../utils';
6
6
  import {type BackendEndpointOptions} from '../../../../types';
7
7
  import {type ResolvedQuery, useModalStore} from '../../../../stores';
8
- import {getCallbackForMutationMode, getModalMutationOptions, MutationMode} from '../../../../services';
8
+ import {
9
+ getCallbackForMutationMode,
10
+ getModalMutationOptions,
11
+ isSameModal,
12
+ keepModalToken,
13
+ MutationMode,
14
+ } from '../../../../services';
9
15
  import {usePdkAdminApi} from '../../../../sdk';
10
16
  import {fillShipmentsQueryData} from '../../../../pdk';
11
17
 
@@ -14,6 +20,7 @@ export const useExportOrdersMutation = (
14
20
  mode: MutationMode = MutationMode.Default,
15
21
  ): ResolvedQuery<BackendEndpoint.ExportOrders> => {
16
22
  const queryClient = useQueryClient();
23
+ const defaultMutationOptions = queryClient.defaultMutationOptions();
17
24
 
18
25
  return usePdkMutation(
19
26
  BackendEndpoint.ExportOrders,
@@ -32,11 +39,15 @@ export const useExportOrdersMutation = (
32
39
  return pdk.exportOrders(options);
33
40
  },
34
41
  {
35
- ...queryClient.defaultMutationOptions(),
36
- ...(mode === MutationMode.Modal ? getModalMutationOptions() : {}),
42
+ ...defaultMutationOptions,
43
+ ...(mode === MutationMode.Modal ? getModalMutationOptions(defaultMutationOptions) : {}),
44
+ // Also in the default mode: onSuccess closes the modal that started the export.
45
+ onMutate: keepModalToken(defaultMutationOptions.onMutate),
37
46
 
38
- async onSuccess(data, input) {
39
- useModalStore().close();
47
+ async onSuccess(data, input, context) {
48
+ if (isSameModal(context)) {
49
+ useModalStore().close();
50
+ }
40
51
 
41
52
  toArray(data).forEach((order) => {
42
53
  fillShipmentsQueryData(queryClient, order.shipments?.slice(-1) ?? [], order);
@@ -0,0 +1,78 @@
1
+ // @vitest-environment happy-dom
2
+
3
+ import {defineComponent, h} from 'vue';
4
+ import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
5
+ import {mount} from '@vue/test-utils';
6
+ import {useAdminConfig} from '../../composables';
7
+ import TabNavigation from './TabNavigation.vue';
8
+
9
+ vi.mock('../../composables', () => ({
10
+ useAdminConfig: vi.fn(),
11
+ useLanguage: vi.fn(() => ({translate: (key: string) => key})),
12
+ }));
13
+
14
+ const createTab = (name: string) => ({
15
+ name,
16
+ label: name,
17
+ component: defineComponent({name: `Tab-${name}`, render: () => h('p', name)}),
18
+ });
19
+
20
+ // eslint-disable-next-line @typescript-eslint/naming-convention
21
+ const PdkTabNavContentWrapper = defineComponent({
22
+ render() {
23
+ return h('div', this.$slots.default?.());
24
+ },
25
+ });
26
+
27
+ const mountTabs = () =>
28
+ mount(TabNavigation, {
29
+ props: {tabs: [createTab('general'), createTab('label')], button: 'button', buttonWrapper: 'div'},
30
+ global: {stubs: {PdkTabNavContentWrapper}},
31
+ });
32
+
33
+ const clickTab = async (wrapper: ReturnType<typeof mountTabs>, name: string) => {
34
+ await wrapper
35
+ .findAll('button')
36
+ .find((button) => button.text() === name)
37
+ ?.trigger('click');
38
+ };
39
+
40
+ describe('TabNavigation', () => {
41
+ beforeEach(() => {
42
+ window.location.hash = '';
43
+ });
44
+
45
+ afterEach(() => {
46
+ window.location.hash = '';
47
+ });
48
+
49
+ it('writes the active tab to the location hash by default', async () => {
50
+ vi.mocked(useAdminConfig).mockReturnValue({} as never);
51
+ const wrapper = mountTabs();
52
+
53
+ await clickTab(wrapper, 'label');
54
+
55
+ expect(window.location.hash).toBe('#label');
56
+ expect(wrapper.text()).toContain('label');
57
+ });
58
+
59
+ it('opens the tab from the location hash by default', () => {
60
+ vi.mocked(useAdminConfig).mockReturnValue({} as never);
61
+ window.location.hash = '#label';
62
+
63
+ expect(mountTabs().find('p').text()).toBe('label');
64
+ });
65
+
66
+ it('leaves the location hash alone when the host app routes with it', async () => {
67
+ vi.mocked(useAdminConfig).mockReturnValue({useLocationHash: false} as never);
68
+ window.location.hash = '#/myparcel/settings/index';
69
+ const wrapper = mountTabs();
70
+
71
+ expect(wrapper.find('p').text()).toBe('general');
72
+
73
+ await clickTab(wrapper, 'label');
74
+
75
+ expect(window.location.hash).toBe('#/myparcel/settings/index');
76
+ expect(wrapper.find('p').text()).toBe('label');
77
+ });
78
+ });
@@ -79,8 +79,13 @@ const props = defineProps({
79
79
 
80
80
  const activeTab = ref<string | null>(null);
81
81
 
82
+ const config = useAdminConfig();
83
+ const {translate} = useLanguage();
84
+
85
+ const useLocationHash = config.useLocationHash !== false;
86
+
82
87
  const handleClick = (tab: TabDefinition) => {
83
- if (props.initialTab !== false) {
88
+ if (useLocationHash && props.initialTab !== false) {
84
89
  window.location.hash = props.hashPrefix + tab.name;
85
90
  }
86
91
 
@@ -96,9 +101,6 @@ const activeTabContents = computed(() => {
96
101
  return (props.tabs as unknown as TabDefinition[])?.find((tab) => tab.name === activeTab.value);
97
102
  });
98
103
 
99
- const config = useAdminConfig();
100
- const {translate} = useLanguage();
101
-
102
104
  watch(
103
105
  () => [props.tabs, props.initialTab],
104
106
  () => {
@@ -113,7 +115,7 @@ watch(
113
115
 
114
116
  let initialTab = props.initialTab === true ? null : props.initialTab;
115
117
 
116
- if (!props.initialTab) {
118
+ if (!props.initialTab && useLocationHash) {
117
119
  const hash = window.location.hash.replace('#', '').replace(props.hashPrefix ?? '', '');
118
120
  const tabName = hash.split(HASH_SEPARATOR)[0];
119
121
 
@@ -0,0 +1,24 @@
1
+ // @vitest-environment happy-dom
2
+
3
+ import {describe, expect, it, vi} from 'vitest';
4
+ import {useGlobalContext} from '../context';
5
+ import {resetLanguageCache, useLanguage} from './useLanguage';
6
+
7
+ vi.mock('../context', () => ({useGlobalContext: vi.fn()}));
8
+
9
+ const useTranslations = (translations: Record<string, string>) => {
10
+ vi.mocked(useGlobalContext).mockReturnValue({translations} as never);
11
+ };
12
+
13
+ describe('resetLanguageCache', () => {
14
+ it('translates with the translations of the next admin instance after a reset', () => {
15
+ useTranslations({settings_title: 'Settings'});
16
+ expect(useLanguage().translate('settings_title')).toBe('Settings');
17
+
18
+ useTranslations({settings_title: 'Einstellungen'});
19
+ resetLanguageCache();
20
+
21
+ expect(useLanguage().translate('settings_title')).toBe('Einstellungen');
22
+ expect(useLanguage().has('settings_title')).toBe(true);
23
+ });
24
+ });
@@ -104,6 +104,19 @@ const memoizedAll = useMemoize(all);
104
104
  const memoizedHas = useMemoize(has);
105
105
  const memoizedTranslate = useMemoize(translate);
106
106
 
107
+ /**
108
+ * Clears the cached translations. createPdkAdmin() calls it, so a new admin
109
+ * instance, for example after a language change in a single-page app, uses its
110
+ * own translations.
111
+ */
112
+ export const resetLanguageCache = (): void => {
113
+ memoizedAll.clear();
114
+ memoizedHas.clear();
115
+ memoizedTranslate.clear();
116
+ useCache().clear();
117
+ useMissingKeys().value = [];
118
+ };
119
+
107
120
  export const useLanguage = (): UseLanguage => {
108
121
  const missingKeys = useMissingKeys();
109
122
 
@@ -0,0 +1,97 @@
1
+ import {defineComponent, h} from 'vue';
2
+ import {afterEach, describe, expect, it, vi} from 'vitest';
3
+ import {AdminView} from '../data';
4
+ import {setupAdminApp} from './setupAdminApp';
5
+ import {createAdminConfig} from './createAdminConfig';
6
+ import {PdkAdmin} from './PdkAdmin';
7
+
8
+ vi.mock('./renderMap', () => ({
9
+ renderViewComponent: vi.fn(() => Promise.resolve(defineComponent({render: () => h('p', 'rendered')}))),
10
+ }));
11
+
12
+ vi.mock('./setupAdminApp', () => ({setupAdminApp: vi.fn()}));
13
+
14
+ const createPdkAdmin = (): PdkAdmin => new PdkAdmin(createAdminConfig({components: {}} as never), {} as never);
15
+
16
+ describe('PdkAdmin.render', () => {
17
+ afterEach(() => {
18
+ document.body.innerHTML = '';
19
+ });
20
+
21
+ it('returns the mounted app, so the caller can unmount it', async () => {
22
+ document.body.innerHTML = '<div id="target"></div>';
23
+
24
+ const app = await createPdkAdmin().render(AdminView.PluginSettings, '#target');
25
+
26
+ expect(document.querySelector('#target')?.textContent).toBe('rendered');
27
+
28
+ app?.unmount();
29
+
30
+ expect(document.querySelector('#target')?.textContent).toBe('');
31
+ });
32
+
33
+ it('returns undefined when the element does not exist', async () => {
34
+ const app = await createPdkAdmin().render(AdminView.PluginSettings, '#missing');
35
+
36
+ expect(app).toBeUndefined();
37
+ });
38
+
39
+ it('shares one store and query client between the apps of one instance', async () => {
40
+ document.body.innerHTML = '<div id="one"></div><div id="two"></div>';
41
+ vi.mocked(setupAdminApp).mockClear();
42
+ const pdkAdmin = createPdkAdmin();
43
+
44
+ await pdkAdmin.render(AdminView.PluginSettings, '#one');
45
+ await pdkAdmin.render(AdminView.PluginSettings, '#two');
46
+
47
+ const [first, second] = vi.mocked(setupAdminApp).mock.calls.map(([, appConfig]) => appConfig);
48
+
49
+ expect(first.store).toBeDefined();
50
+ expect(first.queryClient).toBeDefined();
51
+ expect(second.store).toBe(first.store);
52
+ expect(second.queryClient).toBe(first.queryClient);
53
+ });
54
+
55
+ it('gives a new instance its own store and query client, so a second visit starts clean', async () => {
56
+ document.body.innerHTML = '<div id="one"></div><div id="two"></div>';
57
+ vi.mocked(setupAdminApp).mockClear();
58
+
59
+ await createPdkAdmin().render(AdminView.PluginSettings, '#one');
60
+ await createPdkAdmin().render(AdminView.PluginSettings, '#two');
61
+
62
+ const [first, second] = vi.mocked(setupAdminApp).mock.calls.map(([, appConfig]) => appConfig);
63
+
64
+ expect(second.store).not.toBe(first.store);
65
+ expect(second.queryClient).not.toBe(first.queryClient);
66
+ });
67
+
68
+ it('removes the cached queries on dispose', async () => {
69
+ document.body.innerHTML = '<div id="target"></div>';
70
+ vi.mocked(setupAdminApp).mockClear();
71
+ const pdkAdmin = createPdkAdmin();
72
+
73
+ await pdkAdmin.render(AdminView.PluginSettings, '#target');
74
+
75
+ const [[, {queryClient}]] = vi.mocked(setupAdminApp).mock.calls;
76
+
77
+ queryClient.setQueryData(['orders'], ['order']);
78
+ pdkAdmin.dispose();
79
+
80
+ expect(queryClient.getQueryCache().getAll()).toHaveLength(0);
81
+ });
82
+
83
+ it('returns the mounted app when the onRendered hook fails, so the caller can still unmount it', async () => {
84
+ document.body.innerHTML = '<div id="target"></div>';
85
+ const config = createAdminConfig({
86
+ components: {},
87
+ onRendered: () => {
88
+ throw new Error('hook failed');
89
+ },
90
+ } as never);
91
+
92
+ const app = await new PdkAdmin(config, {} as never).render(AdminView.PluginSettings, '#target');
93
+
94
+ expect(app).toBeDefined();
95
+ expect(document.querySelector('#target')?.textContent).toBe('rendered');
96
+ });
97
+ });