@storybook/svelte
Version:
Storybook for Svelte: Develop Svelte Component in isolation with Hot Reloading.
108 lines (87 loc) • 2.82 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.decorateStory = decorateStory;
require("core-js/modules/es.object.to-string.js");
require("core-js/modules/es.object.assign.js");
var _store = require("@storybook/store");
var _SlotDecorator = _interopRequireDefault(require("@storybook/svelte/templates/SlotDecorator.svelte"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// eslint-disable-next-line import/no-extraneous-dependencies
/**
* Check if an object is a svelte component.
* @param obj Object
*/
function isSvelteComponent(obj) {
return obj.prototype && obj.prototype.$destroy !== undefined;
}
/**
* Handle component loaded with esm or cjs.
* @param obj object
*/
function unWrap(obj) {
return obj && obj.default ? obj.default : obj;
}
/**
* Transform a story to be compatible with the PreviewRender component.
*
* - `() => MyComponent` is translated to `() => ({ Component: MyComponent })`
* - `() => ({})` is translated to `() => ({ Component: <from context.component> })`
* - A decorator component is wrapped with SlotDecorator. The decorated component is inject through
* a <slot/>
*
* @param context StoryContext
* @param story the current story
* @param originalStory the story decorated by the current story
*/
function prepareStory(context, story, originalStory) {
var result = unWrap(story);
if (isSvelteComponent(result)) {
// wrap the component
result = {
Component: result
};
}
if (originalStory) {
// inject the new story as a wrapper of the original story
result = {
Component: _SlotDecorator.default,
props: {
decorator: unWrap(result.Component),
decoratorProps: result.props,
component: unWrap(originalStory.Component),
props: originalStory.props,
on: originalStory.on
}
};
} else {
var cpn = result.Component;
if (!cpn) {
// if the component is not defined, get it the context
cpn = context.component;
}
result.Component = unWrap(cpn);
}
return result;
}
function decorateStory(storyFn, decorators) {
return decorators.reduce(function (previousStoryFn, decorator) {
return function (context) {
var story;
var decoratedStory = decorator(function (update) {
story = previousStoryFn(Object.assign({}, context, (0, _store.sanitizeStoryContextUpdate)(update)));
return story;
}, context);
if (!story) {
story = previousStoryFn(context);
}
if (!decoratedStory || decoratedStory === story) {
return story;
}
return prepareStory(context, decoratedStory, story);
};
}, function (context) {
return prepareStory(context, storyFn(context));
});
}