From a2f17b19ecdbe8606d3b225348232df846cc2f65 Mon Sep 17 00:00:00 2001 From: pengzhanbo Date: Fri, 6 Dec 2024 14:46:03 +0800 Subject: [PATCH] feat(client): add `onContentUpdated` hooks --- packages/client/src/components/Content.ts | 9 ++++++-- .../client/src/composables/contentUpdated.ts | 21 +++++++++++++++++++ packages/client/src/composables/index.ts | 1 + 3 files changed, 29 insertions(+), 2 deletions(-) create mode 100644 packages/client/src/composables/contentUpdated.ts diff --git a/packages/client/src/components/Content.ts b/packages/client/src/components/Content.ts index e58b46214d..41fb0fdc7b 100644 --- a/packages/client/src/components/Content.ts +++ b/packages/client/src/components/Content.ts @@ -1,5 +1,5 @@ import { computed, defineAsyncComponent, defineComponent, h } from 'vue' -import { usePageComponent } from '../composables/index.js' +import { runCallbacks, usePageComponent } from '../composables/index.js' import { resolveRoute } from '../router/index.js' /** @@ -26,6 +26,11 @@ export const Content = defineComponent({ ) }) - return () => h(ContentComponent.value) + return () => + h(ContentComponent.value, { + onVnodeMounted: runCallbacks, + onVnodeUpdated: runCallbacks, + onVnodeBeforeUnmount: runCallbacks, + }) }, }) diff --git a/packages/client/src/composables/contentUpdated.ts b/packages/client/src/composables/contentUpdated.ts new file mode 100644 index 0000000000..1b495719ac --- /dev/null +++ b/packages/client/src/composables/contentUpdated.ts @@ -0,0 +1,21 @@ +import { onUnmounted } from 'vue' + +let contentUpdatedCallbacks: (() => unknown)[] = [] + +/** + * Register callback that is called every time the markdown content is updated + * in the DOM. + */ +export const onContentUpdated = (fn: () => unknown): void => { + contentUpdatedCallbacks.push(fn) + onUnmounted(() => { + contentUpdatedCallbacks = contentUpdatedCallbacks.filter((f) => f !== fn) + }) +} + +/** + * Call all registered callbacks + */ +export const runCallbacks = (): void => { + contentUpdatedCallbacks.forEach((fn) => fn()) +} diff --git a/packages/client/src/composables/index.ts b/packages/client/src/composables/index.ts index c834060742..290b3b41cf 100644 --- a/packages/client/src/composables/index.ts +++ b/packages/client/src/composables/index.ts @@ -1,3 +1,4 @@ export * from './clientData.js' export * from './clientDataUtils.js' export * from './updateHead.js' +export * from './contentUpdated.js'