From 0b03c34afc5868e7d1920dc953176b5f1b9d389c Mon Sep 17 00:00:00 2001 From: Robin Ferrari Date: Wed, 28 Aug 2024 15:12:03 +0200 Subject: [PATCH 1/2] chore: trigger detach behaviour on story change (#53) --- src/detachDrupalBehaviors.ts | 25 +++++++++++++++++++++++++ src/preview.ts | 3 ++- 2 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 src/detachDrupalBehaviors.ts diff --git a/src/detachDrupalBehaviors.ts b/src/detachDrupalBehaviors.ts new file mode 100644 index 0000000..138c431 --- /dev/null +++ b/src/detachDrupalBehaviors.ts @@ -0,0 +1,25 @@ +import type { + Renderer, + PartialStoryFn as StoryFunction, + StoryContext, +} from "@storybook/types"; +import { + useEffect, +} from '@storybook/preview-api'; + +declare const Drupal: any; + +export const detachDrupalBehaviors = ( + StoryFn: StoryFunction, + context: StoryContext, +) => { + useEffect(()=>{ + if(typeof Drupal !== 'undefined' && Drupal.behaviors) { + Object.keys(Drupal.behaviors).forEach(key => { + Drupal.behaviors[key].detach(); + }); + } + }, []); + + return StoryFn(); +}; diff --git a/src/preview.ts b/src/preview.ts index ca18623..0c0344b 100644 --- a/src/preview.ts +++ b/src/preview.ts @@ -9,7 +9,8 @@ * https://storybook.js.org/docs/react/writing-stories/decorators#gatsby-focus-wrapper */ import { withDrupalTheme } from './withDrupalTheme'; +import { detachDrupalBehaviors } from './detachDrupalBehaviors'; import fetchStoryHtml from './fetchStoryHtml'; -export const decorators = [withDrupalTheme]; +export const decorators = [withDrupalTheme, detachDrupalBehaviors]; export const parameters = { server: { fetchStoryHtml } }; From 28b790689cdf56d5e164defebc9fa886d4d2e598 Mon Sep 17 00:00:00 2001 From: Robin Ferrari Date: Thu, 29 Aug 2024 16:16:42 +0200 Subject: [PATCH 2/2] chore: handle error when detaching Drupal behaviors --- src/detachDrupalBehaviors.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/detachDrupalBehaviors.ts b/src/detachDrupalBehaviors.ts index 138c431..1fde42a 100644 --- a/src/detachDrupalBehaviors.ts +++ b/src/detachDrupalBehaviors.ts @@ -16,7 +16,11 @@ export const detachDrupalBehaviors = ( useEffect(()=>{ if(typeof Drupal !== 'undefined' && Drupal.behaviors) { Object.keys(Drupal.behaviors).forEach(key => { - Drupal.behaviors[key].detach(); + try{ + Drupal.behaviors[key].detach?.(); + }catch(e){ + console.error(`Error detaching behavior: ${key}`, e); + } }); } }, []);