Skip to content

Commit

Permalink
Improve source decorator.
Browse files Browse the repository at this point in the history
  • Loading branch information
edoardocavazza committed Apr 29, 2024
1 parent 5b97fa2 commit 3fad3de
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
5 changes: 5 additions & 0 deletions .changeset/polite-hats-vanish.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@chialab/storybook-dna": patch
---

Improve source decorator.
28 changes: 24 additions & 4 deletions packages/storybook-dna/src/docs/sourceDecorator.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Template, VObject } from '@chialab/dna';
import { getProperties, isComponentConstructor, type Template, type VObject } from '@chialab/dna';
import { STORY_PREPARED } from '@storybook/core-events';
import { SNIPPET_RENDERED } from '@storybook/docs-tools';
import { addons, useEffect } from '@storybook/preview-api';
Expand Down Expand Up @@ -152,13 +152,33 @@ function vnodeToString(vnode: Template): string {
'#unknown';

const properties = { ...hyperObject.properties };
const constructor = customElements.get(properties.is || tag);
const definedProperties =
constructor && isComponentConstructor(constructor) ? getProperties(constructor.prototype) : null;

const attrs = Object.keys(properties)
.map((prop) => {
if (prop === 'ref' || prop === 'children') {
if (prop === 'ref' || prop === 'children' || prop === 'class' || prop === 'style') {
return false;
}

if (prop === 'is') {
return `is="${properties[prop as keyof typeof properties]}"`;
}

let value = properties[prop as keyof typeof properties];
if (value == null) {
return false;
}

const definedProperty = definedProperties?.[prop as keyof typeof definedProperties];
if (definedProperty?.defaultValue === value) {
return false;
}

value = (definedProperty?.toAttribute as any)?.(value) ?? value;

Check warning on line 179 in packages/storybook-dna/src/docs/sourceDecorator.ts

View workflow job for this annotation

GitHub Actions / Lint

Unexpected any. Specify a different type
prop = definedProperty?.attribute ?? prop;

if (value == null || value === false) {
return false;
}
Expand All @@ -172,9 +192,9 @@ function vnodeToString(vnode: Template): string {
value = '{...}';
}
if (isFunction(value)) {
value = value.name || 'function() { ... }';
return `${prop}="..."`;
}
if (value === true) {
if (value === true || value === '') {
return prop;
}
return `${prop}="${escapeHtml(`${value}`)}"`;
Expand Down

0 comments on commit 3fad3de

Please sign in to comment.