@storybook/web-components 11.0.0-beta.1 → 11.0.0-beta.3

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.
package/dist/preset.js CHANGED
@@ -1,18 +1,19 @@
1
- import CJS_COMPAT_NODE_URL_2mh2kj69z4k from 'node:url';
2
- import CJS_COMPAT_NODE_PATH_2mh2kj69z4k from 'node:path';
3
- import CJS_COMPAT_NODE_MODULE_2mh2kj69z4k from "node:module";
1
+ import CJS_COMPAT_NODE_URL_ixqjvdd3w7j from 'node:url';
2
+ import CJS_COMPAT_NODE_PATH_ixqjvdd3w7j from 'node:path';
3
+ import CJS_COMPAT_NODE_MODULE_ixqjvdd3w7j from "node:module";
4
4
 
5
- var __filename = CJS_COMPAT_NODE_URL_2mh2kj69z4k.fileURLToPath(import.meta.url);
6
- var __dirname = CJS_COMPAT_NODE_PATH_2mh2kj69z4k.dirname(__filename);
7
- var require = CJS_COMPAT_NODE_MODULE_2mh2kj69z4k.createRequire(import.meta.url);
5
+ var __filename = CJS_COMPAT_NODE_URL_ixqjvdd3w7j.fileURLToPath(import.meta.url);
6
+ var __dirname = CJS_COMPAT_NODE_PATH_ixqjvdd3w7j.dirname(__filename);
7
+ var require = CJS_COMPAT_NODE_MODULE_ixqjvdd3w7j.createRequire(import.meta.url);
8
8
 
9
9
  // ------------------------------------------------------------
10
10
  // end of CJS compatibility banner, injected by Storybook's esbuild configuration
11
11
  // ------------------------------------------------------------
12
12
  import {
13
+ parseArgKey,
13
14
  parseStoryFile,
14
15
  resolveStoryComponent
15
- } from "./_node-chunks/chunk-KEYAB73A.js";
16
+ } from "./_node-chunks/chunk-A2FVKW65.js";
16
17
 
17
18
  // src/preset.ts
18
19
  import { fileURLToPath as fileURLToPath3 } from "node:url";
@@ -75,13 +76,16 @@ import {
75
76
  authoredSource,
76
77
  createStoryArgsResolver,
77
78
  createStoryReferenceResolver,
79
+ detachedTextOf as detachedTextOf2,
78
80
  extractStoryJSDocInfo,
79
81
  noSnippetWarning,
80
82
  resolveEffectiveRender,
81
- oneLineTextOf as oneLineTextOf5,
82
- unwrapExpression as unwrapExpression4,
83
+ oneLineTextOf as oneLineTextOf2,
84
+ reindent,
85
+ unwrapExpression as unwrapExpression2,
83
86
  unresolvedWarning
84
87
  } from "storybook/internal/csf-tools";
88
+ import { createHoleMarks as createHoleMarks2, withHoleSpace } from "storybook/internal/docs-tools";
85
89
  import { resolve as resolve2 } from "node:path";
86
90
 
87
91
  // src/docgen/story-docs/arg-values.ts
@@ -209,13 +213,14 @@ var fieldDefault = (fieldName, declaration) => fieldDeclaration(fieldName, decla
209
213
  return (fieldName ? fieldDefault(fieldName, declaration) : void 0) ?? attribute?.default;
210
214
  }, eventForArg = (key, declaration) => {
211
215
  let matches = declaration.events?.filter(
212
- (event) => key === event.name || key === eventActionName(event.name)
216
+ // A hand-written manifest may hold an event without a name.
217
+ (event) => event.name && (key === event.name || key === eventActionName(event.name))
213
218
  ) ?? [];
214
219
  return matches.length === 1 ? matches[0].name : void 0;
215
220
  };
216
221
 
217
- // src/docgen/story-docs/html-tree.ts
218
- var INLINE_LIMIT = 80, INDENT = " ", RAW_TEXT_ELEMENTS = /* @__PURE__ */ new Set(["pre", "script", "style", "textarea", "title"]), VOID_ELEMENTS = /* @__PURE__ */ new Set([
222
+ // src/html-parse.ts
223
+ var RAW_TEXT_ELEMENTS = /* @__PURE__ */ new Set(["pre", "script", "style", "textarea", "title"]), VOID_ELEMENTS = /* @__PURE__ */ new Set([
219
224
  "area",
220
225
  "base",
221
226
  "br",
@@ -281,10 +286,6 @@ function parseHtml(source) {
281
286
  }
282
287
  return root.children;
283
288
  }
284
- function printHtml(nodes) {
285
- return printableChildren(nodes).map((node) => printNode(node, 0)).join(`
286
- `);
287
- }
288
289
  var current = (stack) => stack[stack.length - 1], readToken = (source, start) => {
289
290
  if (source[start] !== "<") {
290
291
  let next = source.indexOf("<", start), end2 = next === -1 ? source.length : next;
@@ -352,170 +353,290 @@ var current = (stack) => stack[stack.length - 1], readToken = (source, start) =>
352
353
  attributes.push({ name, value: decodeAttribute(source.slice(valueStart, index)) });
353
354
  }
354
355
  return attributes;
355
- }, printNode = (node, depth) => {
356
+ }, decodeAttribute = (value) => value.replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&lt;/g, "<").replace(/&amp;/g, "&"), hasSelfClosingSlash = (rest) => {
357
+ let index = rest.length - 1;
358
+ for (; index >= 0 && /\s/.test(rest[index]); )
359
+ index -= 1;
360
+ return rest[index] !== "/" ? !1 : index === 0 || /\s/.test(rest[index - 1]);
361
+ }, findTagEnd = (source, start) => {
362
+ let quote, canOpenQuote = !1;
363
+ for (let index = start + 1; index < source.length; index += 1) {
364
+ let char = source[index];
365
+ if (quote) {
366
+ char === quote && (quote = void 0);
367
+ continue;
368
+ }
369
+ if ((char === '"' || char === "'") && canOpenQuote) {
370
+ quote = char;
371
+ continue;
372
+ }
373
+ if (/\s|=/.test(char) && (canOpenQuote = !0), char === ">")
374
+ return index + 1;
375
+ }
376
+ }, findRawTextEnd = (source, start, name) => {
377
+ let lower = source.toLowerCase(), close = `</${name.toLowerCase()}`, index = start;
378
+ for (; index < source.length; ) {
379
+ let found = lower.indexOf(close, index);
380
+ if (found === -1)
381
+ return;
382
+ let boundary = source[found + close.length];
383
+ if (boundary !== void 0 && /[\s>]/.test(boundary)) {
384
+ let end = findTagEnd(source, found);
385
+ return end === void 0 ? void 0 : { end, start: found };
386
+ }
387
+ index = found + close.length;
388
+ }
389
+ };
390
+
391
+ // src/snippet-values.ts
392
+ function escapeAttribute(value, quote = '"') {
393
+ let escaped = value.replace(/&/g, "&amp;").replace(/</g, "&lt;");
394
+ return quote === "'" ? escaped.replace(/'/g, "&#39;") : escaped.replace(/"/g, "&quot;");
395
+ }
396
+ var quotedAttribute = (name, text) => `${name}="${escapeAttribute(text)}"`;
397
+ function attributeText(value, viaField) {
398
+ if (value === !0)
399
+ return !0;
400
+ if (value === "")
401
+ return viaField ? "" : void 0;
402
+ if (!(value === !1 || value === null || value === void 0))
403
+ return typeof value == "object" ? JSON.stringify(value) : String(value);
404
+ }
405
+ var cssDeclarations = (properties) => {
406
+ let declarations = properties.filter(({ value }) => value != null && value !== "").map(({ name, value }) => `${name}: ${String(value)};`);
407
+ return declarations.length === 0 ? void 0 : declarations.join(" ");
408
+ }, styleRule = (selector, declarations) => ` ${selector} { ${declarations} }`, styleElement = (rules) => `<style>
409
+ ${rules.map(({ selector, declarations }) => styleRule(selector, declarations)).join(`
410
+ `)}
411
+ </style>`, slotText = (value) => value == null || value === "" ? "" : String(value), inlineText = (text, first, last) => {
412
+ let collapsed = text.replace(/\s+/g, " ");
413
+ return first && (collapsed = collapsed.trimStart()), last && (collapsed = collapsed.trimEnd()), collapsed;
414
+ };
415
+ function slotPlacement(name, html) {
416
+ if (name === "default" || html === "")
417
+ return "none";
418
+ let nodes = parseHtml(html), [only] = nodes;
419
+ return nodes.length === 1 && only?.kind === "element" && !only.selfClosing && !only.attributes.some((attribute) => attribute.name === "slot") ? "element" : "span";
420
+ }
421
+ function slottedHtml(name, html) {
422
+ switch (slotPlacement(name, html)) {
423
+ case "none":
424
+ return html;
425
+ case "element": {
426
+ let end = findTagEnd(html, 0) - 1;
427
+ return `${html.slice(0, end)} ${quotedAttribute("slot", name)}${html.slice(end)}`;
428
+ }
429
+ case "span":
430
+ return `<span ${quotedAttribute("slot", name)}>${html}</span>`;
431
+ }
432
+ }
433
+
434
+ // src/snippet-holes.ts
435
+ var attrHole = (arg, name, mode) => ({ kind: "attr", arg, ...name !== arg && { name }, mode });
436
+
437
+ // src/docgen/story-docs/html-tree.ts
438
+ var INLINE_LIMIT = 80, INDENT = " ";
439
+ function printHtml(nodes, marks) {
440
+ let tags = /* @__PURE__ */ new Map(), expanded = expandHoles(nodes, tags), marked = marks && { mark: marks.mark, tags }, html = expanded.filter(isPrintable).map((node) => printNode(node, 0, marked)).join(`
441
+ `);
442
+ return html + placeholderHoles(expanded, html ? `
443
+ ` : "", marked);
444
+ }
445
+ var expandHoles = (nodes, tags) => nodes.flatMap((node) => {
446
+ if (node.kind === "element")
447
+ return [{ ...node, children: expandHoles(node.children, tags) }];
448
+ if (node.kind !== "hole")
449
+ return [node];
450
+ let inner = expandHoles(node.nodes, tags), printable = inner.filter(isPrintable);
451
+ return printable.length === 0 ? [...inner, node] : (inner.forEach(
452
+ (child) => tags.set(child, {
453
+ hole: node.hole,
454
+ first: child === printable[0],
455
+ last: child === printable.at(-1)
456
+ })
457
+ ), inner);
458
+ }), isPlaceholder = (node) => node.kind === "hole", isPrintable = (node) => !isPlaceholder(node) && (node.kind !== "text" || collapseText(node.text) !== ""), placeholderHoles = (children, space, marks) => marks ? children.filter(isPlaceholder).map((child) => marks.mark(child.hole, "", space)).join("") : "", wrapInHole = (printed, node, marks) => {
459
+ let tag = marks?.tags.get(node);
460
+ if (!tag || !marks)
461
+ return printed;
462
+ let { hole } = tag, indent = printed.match(/^\s*/)[0], text = printed.slice(indent.length);
463
+ if (tag.first && tag.last)
464
+ return `${indent}${marks.mark(hole, text)}`;
465
+ let [open, close] = marks.mark(hole, `
466
+ `).split(`
467
+ `);
468
+ return `${indent}${tag.first ? open : ""}${text}${tag.last ? close : ""}`;
469
+ }, printNode = (node, depth, marks) => wrapInHole(printNodeText(node, depth, marks), node, marks), printNodeText = (node, depth, marks) => {
356
470
  let indent = INDENT.repeat(depth);
357
471
  switch (node.kind) {
358
472
  case "comment":
359
473
  return `${indent}${node.text}`;
360
474
  case "element":
361
- return printElement(node, depth);
475
+ return printElement(node, depth, marks);
362
476
  case "malformed":
363
477
  return node.text;
364
478
  case "rawText":
365
- return printRawTextElement(node, depth);
479
+ return printRawTextElement(node, depth, marks);
366
480
  case "text":
367
481
  return `${indent}${collapseText(node.text)}`;
482
+ case "hole":
483
+ return "";
368
484
  default:
369
485
  return node;
370
486
  }
371
- }, printElement = (node, depth) => {
372
- let indent = INDENT.repeat(depth), startTag = printStartTag(node, depth);
487
+ }, printElement = (node, depth, marks) => {
488
+ let indent = INDENT.repeat(depth), startTag = printStartTag(node, depth, marks);
373
489
  if (VOID_ELEMENTS.has(node.name.toLowerCase()))
374
490
  return startTag;
375
491
  if (node.selfClosing)
376
492
  return `${startTag}</${node.name}>`;
377
- if (printableChildren(node.children).length === 0)
378
- return node.closed ? `${startTag}</${node.name}>` : startTag;
379
- let inline = inlineElementText(node, !0)?.text;
493
+ if (printableChildren(node.children).length === 0) {
494
+ let content = placeholderHoles(node.children, "", marks);
495
+ return node.closed ? `${startTag}${content}</${node.name}>` : `${startTag}${content}`;
496
+ }
497
+ let inline = inlineElementText(node, !0, void 0)?.text;
380
498
  if (inline && indent.length + inline.length <= INLINE_LIMIT)
381
- return `${indent}${inline}`;
382
- let body = printChildLines(node.children, depth + 1).join(`
383
- `);
499
+ return `${indent}${marks ? inlineElementText(node, !0, marks).text : inline}`;
500
+ let body = printChildLines(node.children, depth + 1, marks).join(`
501
+ `) + placeholderHoles(node.children, `
502
+ ${INDENT.repeat(depth + 1)}`, marks);
384
503
  return node.closed ? `${startTag}
385
504
  ${body}
386
505
  ${indent}</${node.name}>` : `${startTag}
387
506
  ${body}`;
388
- }, printChildLines = (children, depth) => {
507
+ }, printChildLines = (children, depth, marks) => {
389
508
  let lines = [], group = [], flushGroup = () => {
390
509
  if (group.length === 0)
391
510
  return;
392
- let inline = inlineChildrenText(group), indent = INDENT.repeat(depth);
393
- inline && inline.hasText && indent.length + inline.text.length <= INLINE_LIMIT ? lines.push(`${indent}${inline.text}`) : group.forEach((child) => lines.push(printNode(child, depth))), group = [];
511
+ let inline = inlineChildrenText(group, void 0), indent = INDENT.repeat(depth);
512
+ inline && inline.hasText && indent.length + inline.text.length <= INLINE_LIMIT ? lines.push(`${indent}${marks ? inlineChildrenText(group, marks).text : inline.text}`) : group.forEach((child) => lines.push(printNode(child, depth, marks))), group = [];
394
513
  };
395
- for (let child of children) {
396
- if (child.kind === "text" && collapseText(child.text) === "") {
397
- flushGroup();
398
- continue;
399
- }
400
- if (inlineChildText(child)) {
401
- group.push(child);
402
- continue;
514
+ for (let child of children)
515
+ if (!isPlaceholder(child)) {
516
+ if (child.kind === "text" && collapseText(child.text) === "") {
517
+ flushGroup();
518
+ continue;
519
+ }
520
+ if (inlineChildText(child, void 0)) {
521
+ group.push(child);
522
+ continue;
523
+ }
524
+ flushGroup(), lines.push(printNode(child, depth, marks));
403
525
  }
404
- flushGroup(), lines.push(printNode(child, depth));
405
- }
406
526
  return flushGroup(), lines;
407
- }, inlineElementText = (node, requireText = !0) => {
527
+ }, inlineElementText = (node, requireText, marks) => {
408
528
  let lowerName = node.name.toLowerCase();
409
529
  if (VOID_ELEMENTS.has(lowerName))
410
- return { hasText: !1, text: printCompactStartTag(node) };
530
+ return { hasText: !1, text: printCompactStartTag(node, marks) };
411
531
  if (node.selfClosing)
412
- return { hasText: !1, text: `${printCompactStartTag(node)}</${node.name}>` };
532
+ return { hasText: !1, text: `${printCompactStartTag(node, marks)}</${node.name}>` };
533
+ let content = placeholderHoles(node.children, "", marks);
413
534
  if (printableChildren(node.children).length === 0)
414
- return { hasText: !1, text: node.closed ? `${printCompactStartTag(node)}</${node.name}>` : printCompactStartTag(node) };
415
- let childrenText = inlineChildrenText(node.children);
535
+ return { hasText: !1, text: node.closed ? `${printCompactStartTag(node, marks)}${content}</${node.name}>` : `${printCompactStartTag(node, marks)}${content}` };
536
+ let childrenText = inlineChildrenText(node.children, marks);
416
537
  return childrenText === void 0 || requireText && !childrenText.hasText ? void 0 : {
417
538
  hasText: childrenText.hasText,
418
- text: `${printCompactStartTag(node)}${childrenText.text}</${node.name}>`
539
+ text: `${printCompactStartTag(node, marks)}${childrenText.text}${content}</${node.name}>`
419
540
  };
420
- }, inlineChildrenText = (children) => {
421
- let parts = [], hasText = !1;
422
- for (let index = 0; index < children.length; index += 1) {
423
- let child = children[index], part = inlineChildText(child);
541
+ }, inlineChildrenText = (children, marks) => {
542
+ let parts = [], hasText = !1, shown2 = children.filter((child) => !isPlaceholder(child));
543
+ for (let child of shown2) {
544
+ let part = inlineChildText(child, marks);
424
545
  if (part === void 0)
425
546
  return;
426
- part.text !== "" && parts.push(
427
- child.kind === "text" ? inlineText(child.text, index === 0, index === children.length - 1) : part.text
428
- ), hasText ||= part.hasText;
547
+ hasText ||= part.hasText;
548
+ let text = child.kind === "text" ? inlineText(child.text, child === shown2[0], child === shown2.at(-1)) : part.text;
549
+ text !== "" && parts.push(wrapInHole(text, child, marks));
429
550
  }
430
551
  return { hasText, text: parts.join("") };
431
- }, inlineChildText = (node) => {
552
+ }, inlineChildText = (node, marks) => {
432
553
  switch (node.kind) {
433
554
  case "text":
434
555
  return collapseText(node.text) === "" ? void 0 : { hasText: !0, text: node.text };
435
556
  case "element": {
436
557
  if (!isInlineChildElement(node))
437
558
  return;
438
- let inline = inlineElementText(node, !1);
559
+ let inline = inlineElementText(node, !1, marks);
439
560
  return inline ? { hasText: !1, text: inline.text } : void 0;
440
561
  }
441
562
  case "comment":
442
563
  case "malformed":
443
564
  case "rawText":
565
+ case "hole":
444
566
  return;
445
567
  default:
446
568
  return node;
447
569
  }
448
- }, isInlineChildElement = (node) => !VOID_ELEMENTS.has(node.name.toLowerCase()) && printableChildren(node.children).every((child) => child.kind === "text"), printRawTextElement = (node, depth) => {
449
- let startTag = printStartTag({ attributes: node.attributes, name: node.name }, depth);
570
+ }, isInlineChildElement = (node) => !VOID_ELEMENTS.has(node.name.toLowerCase()) && printableChildren(node.children).every((child) => child.kind === "text"), printRawTextElement = (node, depth, marks) => {
571
+ let startTag = printStartTag({ attributes: node.attributes, name: node.name }, depth, marks);
450
572
  return node.closed ? `${startTag}${node.text}</${node.name}>` : `${startTag}${node.text}`;
451
- }, printStartTag = (node, depth) => {
452
- let indent = INDENT.repeat(depth), compact = printCompactStartTag(node);
453
- return indent.length + compact.length <= INLINE_LIMIT ? `${indent}${compact}` : node.attributes.length === 0 ? `${indent}<${node.name}>` : [
573
+ }, printStartTag = (node, depth, marks) => {
574
+ let indent = INDENT.repeat(depth), compact = printCompactStartTag(node, void 0);
575
+ if (indent.length + compact.length <= INLINE_LIMIT || shown(node.attributes).length === 0)
576
+ return `${indent}${marks ? printCompactStartTag(node, marks) : compact}`;
577
+ let lines = shown(node.attributes).map(
578
+ (attribute) => `${indent}${INDENT}${printHtmlAttribute(attribute, marks)}`
579
+ ), omitted = omittedHoles(node.attributes, `
580
+ ${indent}${INDENT}`, marks);
581
+ return [
454
582
  `${indent}<${node.name}`,
455
- ...node.attributes.map((attr) => `${indent}${INDENT}${printHtmlAttribute(attr)}`),
583
+ ...lines.slice(0, -1),
584
+ lines.at(-1) + omitted,
456
585
  `${indent}>`
457
586
  ].join(`
458
587
  `);
459
- }, printCompactStartTag = (node) => {
460
- let attrs = node.attributes.map(printHtmlAttribute).join(" "), suffix = attrs ? ` ${attrs}` : "";
461
- return `<${node.name}${suffix}>`;
462
- }, printHtmlAttribute = ({ name, value }) => value === void 0 ? name : `${name}="${escapeAttribute(value)}"`, decodeAttribute = (value) => value.replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&lt;/g, "<").replace(/&amp;/g, "&"), printableChildren = (children) => children.filter((child) => child.kind !== "text" || collapseText(child.text) !== ""), collapseText = (text) => text.trim().replace(/\s+/g, " "), inlineText = (text, first, last) => {
463
- let collapsed = text.replace(/\s+/g, " ");
464
- return first && (collapsed = collapsed.trimStart()), last && (collapsed = collapsed.trimEnd()), collapsed;
465
- }, hasSelfClosingSlash = (rest) => {
466
- let index = rest.length - 1;
467
- for (; index >= 0 && /\s/.test(rest[index]); )
468
- index -= 1;
469
- return rest[index] !== "/" ? !1 : index === 0 || /\s/.test(rest[index - 1]);
470
- }, findTagEnd = (source, start) => {
471
- let quote, canOpenQuote = !1;
472
- for (let index = start + 1; index < source.length; index += 1) {
473
- let char = source[index];
474
- if (quote) {
475
- char === quote && (quote = void 0);
476
- continue;
477
- }
478
- if ((char === '"' || char === "'") && canOpenQuote) {
479
- quote = char;
480
- continue;
481
- }
482
- if (/\s|=/.test(char) && (canOpenQuote = !0), char === ">")
483
- return index + 1;
484
- }
485
- }, findRawTextEnd = (source, start, name) => {
486
- let lower = source.toLowerCase(), close = `</${name.toLowerCase()}`, index = start;
487
- for (; index < source.length; ) {
488
- let found = lower.indexOf(close, index);
489
- if (found === -1)
490
- return;
491
- let boundary = source[found + close.length];
492
- if (boundary !== void 0 && /[\s>]/.test(boundary)) {
493
- let end = findTagEnd(source, found);
494
- return end === void 0 ? void 0 : { end, start: found };
495
- }
496
- index = found + close.length;
588
+ }, printCompactStartTag = (node, marks) => {
589
+ let attrs = shown(node.attributes).map((attribute) => printHtmlAttribute(attribute, marks)).join(" "), omitted = omittedHoles(node.attributes, " ", marks);
590
+ return `<${node.name}${attrs ? ` ${attrs}` : ""}${omitted}>`;
591
+ }, shown = (attributes) => attributes.filter((attribute) => !attribute.omitted), omittedHoles = (attributes, space, marks) => marks ? attributes.flatMap((attribute) => attribute.omitted && attribute.hole ? [attribute.hole] : []).map((hole) => marks.mark(hole, "", space)).join("") : "", printHtmlAttribute = (attribute, marks) => {
592
+ let { hole, holeValue, name, value } = attribute;
593
+ if (marks && holeValue !== void 0) {
594
+ let marked = holeValue.map((segment) => {
595
+ if (typeof segment == "string")
596
+ return escapeAttribute(segment);
597
+ let { text, space, ...ref } = segment;
598
+ return marks.mark(ref, escapeAttribute(text), space);
599
+ }).join("");
600
+ return `${name}="${marked}"`;
497
601
  }
498
- };
602
+ let printed = value === void 0 ? name : quotedAttribute(name, value);
603
+ return marks && hole ? marks.mark(hole, printed) : printed;
604
+ }, printableChildren = (children) => children.filter(isPrintable), collapseText = (text) => text.trim().replace(/\s+/g, " ");
499
605
 
500
606
  // src/docgen/story-docs/print-element.ts
501
- function escapeAttribute(value, quote = '"') {
502
- let escaped = value.replace(/&/g, "&amp;").replace(/</g, "&lt;");
503
- return quote === "'" ? escaped.replace(/'/g, "&#39;") : escaped.replace(/"/g, "&quot;");
504
- }
505
- function printElementSnippet(snippet) {
506
- let nodes = [
507
- ...styleNodes(snippet.styleRules),
508
- {
509
- attributes: elementAttributes(snippet),
510
- children: slotNodes(snippet.slots),
511
- closed: !0,
512
- kind: "element",
513
- name: snippet.tag,
514
- selfClosing: !1
515
- }
516
- ], element = printHtml(nodes), listenerScript = printListenerScript(snippet.tag, snippet.listeners);
517
- return listenerScript ? `${element}
518
- ${listenerScript}` : element;
607
+ function printElementSnippet(snippet, marks) {
608
+ let rules = snippet.styleRules.filter(
609
+ (rule2) => rule2.declarations !== void 0
610
+ ), element = {
611
+ attributes: elementAttributes(snippet),
612
+ children: slotNodes(snippet.slots),
613
+ closed: !0,
614
+ kind: "element",
615
+ name: snippet.tag,
616
+ selfClosing: !1
617
+ }, listenerScript = printListenerScript(snippet.tag, snippet.listeners), withScript = (html) => listenerScript ? `${html}
618
+ ${listenerScript}` : html;
619
+ if (!marks)
620
+ return withScript(
621
+ [...rules.length > 0 ? [styleElement(rules)] : [], printHtml([element])].join(`
622
+ `)
623
+ );
624
+ let unset = snippet.styleRules.filter(
625
+ (rule2) => rule2.declarations === void 0 && rule2.arg !== void 0
626
+ ), rule = ({ selector, arg }) => ({
627
+ kind: rules.length > 0 ? "rule" : "style",
628
+ selector,
629
+ arg
630
+ }), style = rules.length > 0 ? `<style>
631
+ ${rules.map((written) => {
632
+ let text = styleRule(written.selector, written.declarations);
633
+ return written.arg === void 0 ? text : marks.mark(rule({ ...written, arg: written.arg }), text);
634
+ }).join(`
635
+ `)}${unset.map((arg) => marks.mark(rule(arg), "", `
636
+ `)).join("")}
637
+ </style>
638
+ ` : unset.map((arg) => marks.mark(rule(arg), "")).join("");
639
+ return withScript(`${style}${printHtml([element], marks)}`);
519
640
  }
520
641
  function printListenerScript(tag, listeners) {
521
642
  let uniqueListeners = uniqueListenersByEvent(
@@ -531,614 +652,175 @@ ${uniqueListeners.map(({ event, handler }) => ` host.addEventListener('${esca
531
652
  }
532
653
  </script>`;
533
654
  }
534
- function printRootListenerScript(listeners) {
535
- let uniqueListeners = uniqueListenersByEvent(listeners);
536
- return uniqueListeners.length === 0 ? void 0 : `<script>
537
- {
538
- const host = document.currentScript.previousElementSibling;
539
- ${uniqueListeners.map(
540
- ({ event, handler }) => ` host.addEventListener('${escapeScriptString(event)}', ${sanitizeScriptHandler(handler)});`
541
- ).join(`
542
- `)}
543
- }
544
- </script>`;
545
- }
546
655
  var uniqueListenersByEvent = (listeners) => {
547
656
  let events = /* @__PURE__ */ new Set();
548
657
  return listeners.filter(({ event }) => events.has(event) ? !1 : (events.add(event), !0));
549
- }, styleNodes = (rules) => rules.length === 0 ? [] : [
550
- {
551
- attributes: [],
552
- closed: !0,
553
- kind: "rawText",
554
- name: "style",
555
- text: `
556
- ${rules.map(({ selector, declarations }) => ` ${selector} { ${declarations} }`).join(`
557
- `)}
558
- `
658
+ }, elementAttributes = (snippet) => {
659
+ let attributes = snippet.attributes.flatMap((attribute) => {
660
+ let node = attributeNode(attribute);
661
+ if (attribute.arg === void 0)
662
+ return node ? [node] : [];
663
+ let hole = attrHole(attribute.arg, attribute.name, attribute.viaField ? "field" : "render");
664
+ return [{ ...node ?? { name: attribute.name, value: void 0, omitted: !0 }, hole }];
665
+ }), style = cssDeclarations(snippet.cssProperties), declaration = ({
666
+ name,
667
+ value,
668
+ arg
669
+ }) => {
670
+ let text = cssDeclarations([{ name, value }]) ?? "";
671
+ return arg === void 0 ? text : {
672
+ kind: "css",
673
+ arg,
674
+ ...name !== arg && { property: name },
675
+ text,
676
+ ...text ? {} : { space: " " }
677
+ };
678
+ }, set = snippet.cssProperties.filter((property) => cssDeclarations([property])), unset = snippet.cssProperties.filter(
679
+ (property) => property.arg !== void 0 && !cssDeclarations([property])
680
+ );
681
+ if (style === void 0) {
682
+ let properties = unset.map(({ arg, name }) => ({ arg, property: name }));
683
+ return properties.length === 0 ? attributes : [
684
+ ...attributes,
685
+ {
686
+ name: "style",
687
+ value: void 0,
688
+ omitted: !0,
689
+ hole: { kind: "cssattr", spread: !0, properties }
690
+ }
691
+ ];
559
692
  }
560
- ], elementAttributes = (snippet) => {
561
- let attributes = snippet.attributes.map(attributeNode).filter((attribute) => attribute !== void 0), style = printCssProperties(snippet.cssProperties);
562
- return [...attributes, ...style ? [{ name: "style", value: style }] : []];
563
- };
564
- function printAttribute({
565
- name,
566
- value,
567
- viaField
568
- }) {
569
- if (value === !0)
570
- return name;
571
- if (value === "")
572
- return viaField ? `${name}=""` : void 0;
573
- if (value === !1 || value === null || value === void 0)
574
- return;
575
- let text = typeof value == "object" ? JSON.stringify(value) : String(value);
576
- return `${name}="${escapeAttribute(text)}"`;
577
- }
578
- var printCssProperties = (properties) => {
579
- let declarations = properties.filter(({ value }) => value != null && value !== "").map(({ name, value }) => `${name}: ${String(value)};`);
580
- return declarations.length === 0 ? void 0 : declarations.join(" ");
693
+ let holeValue = [
694
+ ...set.flatMap((property, index) => [...index > 0 ? [" "] : [], declaration(property)]),
695
+ ...unset.map(declaration)
696
+ ];
697
+ return [...attributes, { name: "style", value: style, holeValue }];
581
698
  }, attributeNode = ({
582
699
  name,
583
700
  value,
584
701
  viaField
585
702
  }) => {
586
- if (value === !0)
587
- return { name, value: void 0 };
588
- if (value === "")
589
- return viaField ? { name, value: "" } : void 0;
590
- if (value === !1 || value === null || value === void 0)
591
- return;
592
- let text = typeof value == "object" ? JSON.stringify(value) : String(value);
593
- return { name, value: text };
594
- }, hasSlotContent = ({ html }) => html != null && html !== "", slotNodes = (slots) => slots.filter(hasSlotContent).flatMap(({ name, html }, index) => [
595
- ...index === 0 ? [] : [slotSeparatorNode()],
596
- ...nodesForSlot(name, String(html))
597
- ]), slotSeparatorNode = () => ({ kind: "text", text: `
598
- ` }), nodesForSlot = (name, content) => {
599
- let nodes = parseHtml(content);
600
- if (name === "default")
601
- return nodes;
602
- let [only] = nodes;
603
- return nodes.length === 1 && only?.kind === "element" && !only.selfClosing && !hasSlotAttribute(only) ? (only.attributes.push({ name: "slot", value: name }), nodes) : [
604
- {
605
- attributes: [{ name: "slot", value: name }],
606
- children: nodes,
607
- closed: !0,
608
- kind: "element",
609
- name: "span",
610
- selfClosing: !1
611
- }
612
- ];
613
- }, hasSlotAttribute = (node) => node.attributes.some((attribute) => attribute.name === "slot"), escapeScriptString = (value) => value.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/</g, "\\x3C"), sanitizeScriptHandler = (value) => value.replace(/<!--/g, "<\\!--").replace(/<script/gi, "<\\script").replace(/<\/script/gi, "<\\/script");
703
+ let text = attributeText(value, viaField);
704
+ return text === void 0 ? void 0 : { name, value: text === !0 ? void 0 : text };
705
+ }, slotNodes = (slots) => {
706
+ let content = 0;
707
+ return slots.flatMap((slot) => {
708
+ let html = slotText(slot.html), separator = html !== "" && content++ > 0 ? [slotSeparatorNode()] : [], nodes = html !== "" ? nodesForSlot(slot.name, html) : [];
709
+ return slot.arg === void 0 ? [...separator, ...nodes] : [
710
+ ...separator,
711
+ {
712
+ hole: { kind: "slot", arg: slot.arg, name: slot.name },
713
+ kind: "hole",
714
+ nodes
715
+ }
716
+ ];
717
+ });
718
+ }, slotSeparatorNode = () => ({ kind: "text", text: `
719
+ ` }), nodesForSlot = (name, content) => slotPlacement(name, content) === "span" ? [
720
+ {
721
+ attributes: [{ name: "slot", value: name }],
722
+ children: parseHtml(content),
723
+ closed: !0,
724
+ kind: "element",
725
+ name: "span",
726
+ selfClosing: !1
727
+ }
728
+ ] : parseHtml(slottedHtml(name, content)), escapeScriptString = (value) => value.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/</g, "\\x3C"), sanitizeScriptHandler = (value) => value.replace(/<!--/g, "<\\!--").replace(/<script/gi, "<\\script").replace(/<\/script/gi, "<\\/script");
614
729
 
615
- // src/docgen/story-docs/template-holes.ts
730
+ // src/docgen/story-docs/render-snippet.ts
616
731
  import {
617
732
  detachedTextOf,
618
- oneLineTextOf as oneLineTextOf3,
619
- reindent,
620
- unwrapExpression as unwrapExpression3,
621
- walk
622
- } from "storybook/internal/csf-tools";
623
-
624
- // src/docgen/story-docs/template-scope.ts
625
- import {
626
- collectImportBindings,
627
733
  isStringLiteral,
628
- staticKey as staticKey2,
629
- returnedExpression,
630
- oneLineTextOf as oneLineTextOf2,
631
- unwrapExpression as unwrapExpression2
734
+ isTSWrapper,
735
+ textOf,
736
+ walk
632
737
  } from "storybook/internal/csf-tools";
633
- var TEMPLATE_TAG_SOURCES = ["lit", "lit-html", "lit-element"];
634
- function resolveHtmlTemplate(renderFunction, csf) {
635
- let bindings = collectImportBindings(csf.program), returned = returnedTemplateExpression(renderFunction, bindings);
636
- return returned ? templateFromExpression(unwrapExpression2(returned.node), bindings, returned.scope) : void 0;
637
- }
638
- function templateFromExpression(expression, bindings, scope) {
639
- if (isStringLiteral(expression))
640
- return {
641
- bindings,
642
- expressions: [],
643
- lit: !1,
644
- quasis: [expression.value],
645
- scope,
646
- source: oneLineTextOf2(expression)
647
- };
648
- if (expression.type === "TemplateLiteral")
649
- return templateFromLiteral(expression, bindings, !1, scope, oneLineTextOf2(expression));
650
- if (!(expression.type !== "TaggedTemplateExpression" || expression.tag.type !== "Identifier"))
651
- return isImported(expression.tag.name, "html", TEMPLATE_TAG_SOURCES, bindings) || isImported(expression.tag.name, "default", TEMPLATE_TAG_SOURCES, bindings) ? templateFromLiteral(expression.quasi, bindings, !0, scope, oneLineTextOf2(expression)) : void 0;
652
- }
653
- function aliasValueForIdentifier(expression, scope) {
654
- return scope.aliases.get(expression.name);
655
- }
656
- function argReferenceForExpression(expression, scope) {
657
- let unwrapped = unwrapExpression2(expression);
658
- if (unwrapped.type === "Identifier") {
659
- let alias = aliasValueForIdentifier(unwrapped, scope);
660
- return alias?.kind === "arg" ? { name: alias.name, path: alias.path } : parameterArgReference(unwrapped, scope);
661
- }
662
- if (unwrapped.type !== "MemberExpression")
663
- return;
664
- let property = memberPropertyName(unwrapped);
665
- if (property === void 0)
738
+ import { createHoleMarks, printValue } from "storybook/internal/docs-tools";
739
+ function renderSnippet(render, exportName, args) {
740
+ let body = render.body, reads = argReads(render);
741
+ if (!reads)
666
742
  return;
667
- if (scope.args && unwrapped.object.type === "Identifier" && unwrapped.object.name === scope.args)
668
- return { name: property, path: [] };
669
- let object = argReferenceForExpression(unwrapped.object, scope);
670
- return object ? { name: object.name, path: [...object.path, property] } : void 0;
743
+ let code = textOf(body), indent = /\n([ \t]*)[^\n]*$/.exec(code)?.[1] ?? "", dedent2 = (text) => indent ? text.replaceAll(`
744
+ ${indent}`, `
745
+ `) : text, print = (mark) => {
746
+ let text = "", cursor = 0;
747
+ for (let read of reads) {
748
+ let { before, value, after, hole } = edit(read, args);
749
+ text += dedent2(code.slice(cursor, read.node.start - body.start)), text += before + (mark && hole ? mark(hole, value) : value) + after, cursor = read.node.end - body.start;
750
+ }
751
+ return text += dedent2(code.slice(cursor)), body.type === "BlockStatement" ? `const ${exportName} = ${render.async ? "async " : ""}() => ${text};` : text;
752
+ }, snippet = print();
753
+ if (reads.some((read) => read.arg === void 0))
754
+ return { snippet, template: void 0 };
755
+ let marks = createHoleMarks([snippet]);
756
+ return { snippet, template: marks.toTemplate(print(marks.mark)) };
671
757
  }
672
- var returnedTemplateExpression = (renderFunction, bindings) => {
673
- let baseScope = scopeForRenderFunction(renderFunction), strict = returnedExpression(renderFunction);
674
- if (strict)
675
- return { node: strict, scope: baseScope };
676
- if (renderFunction.body?.type !== "BlockStatement")
677
- return;
678
- let statements = renderFunction.body.body, returned = statements.at(-1);
679
- if (returned?.type !== "ReturnStatement" || !returned.argument)
758
+ function argReads(render) {
759
+ let [param] = render.params, argsName = param?.type === "Identifier" ? param.name : void 0, pattern = param?.type === "ObjectPattern" ? destructuredArgs(param) : { names: /* @__PURE__ */ new Map() };
760
+ if (!pattern || param && !argsName && param.type !== "ObjectPattern")
680
761
  return;
681
- let scope = copyScope(baseScope);
682
- for (let statement of statements.slice(0, -1))
683
- if (statement.type !== "VariableDeclaration" || statement.kind !== "const" && statement.kind !== "let" || !addVariableAliases(statement, scope, bindings))
684
- return;
685
- return { node: returned.argument, scope };
686
- }, scopeForRenderFunction = (renderFunction) => {
687
- let [first] = renderFunction.params, scope = { aliases: /* @__PURE__ */ new Map(), destructured: /* @__PURE__ */ new Map() };
688
- if (first?.type === "Identifier")
689
- return scope.args = first.name, scope;
690
- if (first?.type !== "ObjectPattern")
691
- return scope;
692
- let destructured = destructuredAliases(first, { name: "", path: [] });
693
- if (!destructured)
694
- return scope;
695
- for (let [local, value] of destructured)
696
- scope.aliases.set(local, value), value.kind === "arg" && value.path.length === 0 && scope.destructured.set(local, value.name);
697
- return scope;
698
- }, addVariableAliases = (declaration, scope, bindings) => {
699
- for (let declarator of declaration.declarations) {
700
- if (!declarator.init)
762
+ let { names: destructured, rest } = pattern, names = /* @__PURE__ */ new Set([
763
+ ...destructured.keys(),
764
+ ...argsName ? [argsName] : [],
765
+ ...rest ? [rest] : []
766
+ ]), reads = [], rebound = !1;
767
+ return walk(render.body, (node, parent) => {
768
+ if (node.type.startsWith("TS") && !isTSWrapper(node) || (bindsName(node, names) && (rebound = !0), isName(node, parent)))
701
769
  return !1;
702
- if (declarator.id.type === "Identifier") {
703
- let alias = aliasForExpression(declarator.init, scope, bindings);
704
- if (!alias)
705
- return !1;
706
- scope.aliases.set(declarator.id.name, alias);
707
- continue;
708
- }
709
- if (declarator.id.type === "ObjectPattern") {
710
- let source = destructureSourceForExpression(declarator.init, scope);
711
- if (!source)
712
- return !1;
713
- let aliases = destructuredAliases(declarator.id, source);
714
- if (!aliases)
715
- return !1;
716
- aliases.forEach((alias, name) => scope.aliases.set(name, alias));
770
+ let arg = node.type === "Identifier" ? destructured.get(node.name) ?? (node.name === argsName || node.name === rest ? null : void 0) : node.type === "MemberExpression" && node.object.type === "Identifier" && node.object.name === argsName ? memberKey(node) : void 0;
771
+ if (arg !== void 0)
772
+ return reads.push({
773
+ node,
774
+ ...arg !== null && { arg },
775
+ ...arg === null && node.type === "Identifier" && node.name === rest && {
776
+ rest: [...destructured.values()]
777
+ },
778
+ ...parent?.type === "Property" && parent.shorthand && { shorthand: textOf(parent.key) },
779
+ wrap: needsParentheses(node, parent)
780
+ }), !1;
781
+ }), rebound ? void 0 : reads;
782
+ }
783
+ function destructuredArgs(pattern) {
784
+ let names = /* @__PURE__ */ new Map(), rest;
785
+ for (let property of pattern.properties) {
786
+ if (property.type === "RestElement" && property.argument.type === "Identifier") {
787
+ rest = property.argument.name;
717
788
  continue;
718
789
  }
719
- return !1;
720
- }
721
- return !0;
722
- }, destructureSourceForExpression = (expression, scope) => {
723
- let unwrapped = unwrapExpression2(expression);
724
- return scope.args && unwrapped.type === "Identifier" && unwrapped.name === scope.args ? { name: "", path: [] } : argReferenceForExpression(expression, scope);
725
- }, aliasForExpression = (expression, scope, bindings) => {
726
- let unwrapped = unwrapExpression2(expression), arg = argReferenceForExpression(unwrapped, scope);
727
- if (arg)
728
- return { kind: "arg", source: oneLineTextOf2(expression), ...arg };
729
- if (isStaticLiteral(unwrapped))
730
- return { kind: "value", value: literalValue(unwrapped) };
731
- let template = templateFromExpression(unwrapped, bindings, copyScope(scope));
732
- if (template)
733
- return { kind: "template", source: oneLineTextOf2(expression), template };
734
- }, destructuredAliases = (pattern, source) => {
735
- let aliases = /* @__PURE__ */ new Map();
736
- for (let property of pattern.properties) {
737
- if (property.type !== "Property" || property.computed)
738
- return;
739
- let key = staticKey2(property);
740
- if (!key)
790
+ if (property.type !== "Property" || property.value.type !== "Identifier")
741
791
  return;
742
- let root = source.name === "" ? { name: key, path: [] } : { name: source.name, path: [...source.path, key] };
743
- if (property.value.type === "Identifier")
744
- aliases.set(property.value.name, { kind: "arg", ...root });
745
- else if (property.value.type === "ObjectPattern") {
746
- let nested = destructuredAliases(property.value, root);
747
- if (!nested)
748
- return;
749
- nested.forEach((alias, name) => aliases.set(name, alias));
750
- } else
792
+ let key = property.computed ? void 0 : property.key.type === "Identifier" ? property.key.name : isStringLiteral(property.key) ? property.key.value : void 0;
793
+ if (key === void 0)
751
794
  return;
795
+ names.set(property.value.name, key);
752
796
  }
753
- return aliases;
754
- }, parameterArgReference = (expression, scope) => {
755
- let arg = scope.destructured.get(expression.name);
756
- return arg ? { name: arg, path: [] } : void 0;
757
- }, memberPropertyName = (expression) => !expression.computed && expression.property.type === "Identifier" ? expression.property.name : expression.computed && isStringLiteral(expression.property) ? expression.property.value : void 0, templateFromLiteral = (literal, bindings, lit, scope, source) => ({
758
- bindings,
759
- expressions: literal.expressions,
760
- lit,
761
- quasis: literal.quasis.map((quasi) => quasi.value.raw),
762
- scope,
763
- source
764
- }), copyScope = (scope) => ({
765
- ...scope,
766
- aliases: new Map(scope.aliases),
767
- destructured: new Map(scope.destructured)
768
- }), isImported = (local, importName, sources, bindings) => {
769
- let binding = bindings.get(local);
770
- return !!binding && sources.includes(binding.importId) && binding.importName === importName;
771
- }, isStaticLiteral = (expression) => {
772
- let value = primitiveLiteralValue(expression);
773
- return value !== FAILED && value !== null || expression.type === "TemplateLiteral" && expression.expressions.length === 0;
774
- }, literalValue = (expression) => {
775
- if (expression.type === "TemplateLiteral")
776
- return expression.quasis[0]?.value.cooked ?? expression.quasis[0]?.value.raw ?? "";
777
- let value = primitiveLiteralValue(expression);
778
- return value === FAILED ? void 0 : value;
779
- };
780
-
781
- // src/docgen/story-docs/template-holes.ts
782
- var handlerText = (node) => reindent(detachedTextOf(node), "", " "), TEMPLATE_TAG_SOURCES2 = ["lit", "lit-html", "lit-element"], IF_DEFINED_SOURCES = ["lit/directives/if-defined.js", "lit-html/directives/if-defined.js"], resolveHoleValue = (expression, context) => {
783
- let expressionNode = unwrapExpression3(expression), alias = expressionNode.type === "Identifier" ? aliasValueForIdentifier(expressionNode, context.scope) : void 0;
784
- if (alias)
785
- return resolveAlias(alias, context, oneLineTextOf3(expression));
786
- let arg = argReferenceForExpression(expression, context.scope);
787
- if (arg)
788
- return resolveArgReference(arg, context.storyArgs[arg.name], oneLineTextOf3(expression));
789
- let unwrapped = expressionNode;
790
- if (isNothingExpression(unwrapped, context.bindings))
791
- return { kind: "nothing" };
792
- if (isStaticLiteral2(unwrapped))
793
- return { kind: "value", value: literalValue2(unwrapped) };
794
- if (isFunctionNode(unwrapped))
795
- return {
796
- handler: handlerText(expression),
797
- kind: "function",
798
- source: oneLineTextOf3(expression)
799
- };
800
- let nested = templateFromExpression(unwrapped, context.bindings, context.scope);
801
- if (nested)
802
- return { kind: "template", source: oneLineTextOf3(expression), template: nested };
803
- if (isIfDefinedCall(unwrapped, context.bindings)) {
804
- let value = resolveHoleValue(unwrapped.arguments[0], context);
805
- return value.kind === "value" && value.value !== null && value.value !== void 0 ? value : { kind: "nothing", ...value.arg ? { arg: value.arg } : {} };
806
- }
807
- if (unwrapped.type === "ConditionalExpression") {
808
- let test = resolveConditionalTest(unwrapped.test, context);
809
- if (test.kind === "unresolved")
810
- return test;
811
- let branch = resolveHoleValue(
812
- test.truthy ? unwrapped.consequent : unwrapped.alternate,
813
- context
814
- );
815
- return test.arg && !branch.arg ? { ...branch, arg: test.arg } : branch;
816
- }
817
- return { kind: "unresolved", source: oneLineTextOf3(expression) };
818
- }, collectReferencedArgs = (expression, scope) => {
819
- let referenced = /* @__PURE__ */ new Set();
820
- return walk(expression, (node, parent) => {
821
- if (isStaticName(node, parent))
822
- return !1;
823
- referencedArgsForExpression(node, scope).forEach((arg) => referenced.add(arg));
824
- }), referenced;
825
- }, isTruthyAttributeValue = (value) => value.kind === "value" ? !!value.value : value.kind === "template" || value.kind === "function", attributeValue = (value, context, referenced) => {
826
- if (value.kind === "empty" || value.kind === "function" || value.kind === "nothing")
827
- return { kind: "value", value: void 0 };
828
- if (value.kind === "value")
829
- return { kind: "value", value: value.value };
830
- if (value.template.lit)
831
- return { kind: "unresolved", source: value.source ?? value.template.source };
832
- let resolved = templateAttributeText(value.template, context, referenced);
833
- return resolved.kind === "unresolved" ? resolved : { kind: "value", value: resolved.text };
834
- }, listenerHandler = (value) => value.kind === "function" ? value.handler : "() => {}", escapeText = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;"), resolveArg = (arg, node) => {
835
- if (!node)
836
- return { kind: "value", arg, value: void 0 };
837
- let value = evaluateArgValue(node);
838
- switch (value.kind) {
839
- case "function":
840
- return { handler: handlerText(node), kind: "function", arg, source: oneLineTextOf3(node) };
841
- case "unset":
842
- return { kind: "value", arg, value: void 0 };
843
- case "unresolved":
844
- return { arg, kind: "unresolved", source: value.source };
845
- case "value":
846
- return { kind: "value", arg, value: value.value };
847
- default:
848
- return value;
849
- }
850
- }, resolveAlias = (alias, context, source) => {
851
- switch (alias.kind) {
852
- case "arg":
853
- return resolveArgReference(alias, context.storyArgs[alias.name], source ?? alias.source);
854
- case "template":
855
- return { kind: "template", source: source ?? alias.source, template: alias.template };
856
- case "value":
857
- return { kind: "value", value: alias.value };
858
- default:
859
- return alias;
860
- }
861
- }, resolveArgReference = (reference, node, missingPathSource) => {
862
- let value = resolveArg(reference.name, node);
863
- if (value.kind === "function" && missingPathSource)
864
- return { ...value, source: missingPathSource };
865
- if (value.kind !== "value" || reference.path.length === 0)
866
- return value;
867
- let current2 = value.value;
868
- for (let part of reference.path) {
869
- let object = current2 == null ? void 0 : Object(current2);
870
- if (object === void 0 || !(part in object))
871
- return missingPathSource ? { arg: reference.name, kind: "unresolved", source: missingPathSource } : { arg: reference.name, kind: "empty" };
872
- current2 = object[part];
873
- }
874
- return current2 === void 0 ? missingPathSource ? { arg: reference.name, kind: "unresolved", source: missingPathSource } : { arg: reference.name, kind: "empty" } : { arg: reference.name, kind: "value", value: current2 };
875
- }, referencedArgsForExpression = (expression, scope) => {
876
- let alias = expression.type === "Identifier" ? aliasValueForIdentifier(expression, scope) : void 0;
877
- if (alias)
878
- return referencedArgsForAlias(alias);
879
- let arg = argReferenceForExpression(expression, scope);
880
- return arg ? /* @__PURE__ */ new Set([arg.name]) : /* @__PURE__ */ new Set();
881
- }, referencedArgsForAlias = (alias) => {
882
- switch (alias.kind) {
883
- case "arg":
884
- return /* @__PURE__ */ new Set([alias.name]);
885
- case "template": {
886
- let referenced = /* @__PURE__ */ new Set();
887
- for (let expression of alias.template.expressions)
888
- collectReferencedArgs(expression, alias.template.scope).forEach(
889
- (arg) => referenced.add(arg)
890
- );
891
- return referenced;
892
- }
893
- case "value":
894
- return /* @__PURE__ */ new Set();
895
- default:
896
- return alias;
897
- }
898
- }, isStaticName = (node, parent) => parent?.type === "MemberExpression" && parent.property === node && !parent.computed || parent?.type === "Property" && parent.key === node && parent.value !== node && !parent.computed, isNothingExpression = (expression, bindings) => expression.type === "Identifier" && isImported2(expression.name, "nothing", TEMPLATE_TAG_SOURCES2, bindings), isStaticLiteral2 = (expression) => primitiveLiteralValue(expression) !== FAILED || expression.type === "Identifier" && expression.name === "undefined" || expression.type === "UnaryExpression" && expression.operator === "void" || expression.type === "TemplateLiteral" && expression.expressions.length === 0, literalValue2 = (expression) => {
899
- if (expression.type === "TemplateLiteral")
900
- return expression.quasis[0]?.value.cooked ?? expression.quasis[0]?.value.raw ?? "";
901
- let value = primitiveLiteralValue(expression);
902
- return value === FAILED ? void 0 : value;
903
- }, isIfDefinedCall = (expression, bindings) => expression.type === "CallExpression" && expression.arguments.length === 1 && expression.arguments[0].type !== "SpreadElement" && expression.callee.type === "Identifier" && isImported2(expression.callee.name, "ifDefined", IF_DEFINED_SOURCES, bindings), resolveConditionalTest = (expression, context) => {
904
- let arg = argReferenceForExpression(expression, context.scope);
905
- if (arg) {
906
- let value = resolveArgReference(arg, context.storyArgs[arg.name], oneLineTextOf3(expression));
907
- return value.kind === "value" || value.kind === "empty" ? { arg: arg.name, kind: "value", truthy: value.kind === "value" && !!value.value } : {
908
- kind: "unresolved",
909
- source: value.kind === "unresolved" ? value.source : oneLineTextOf3(expression)
910
- };
911
- }
912
- let unwrapped = unwrapExpression3(expression);
913
- return isNothingExpression(unwrapped, context.bindings) ? { kind: "value", truthy: !1 } : isStaticLiteral2(unwrapped) ? { kind: "value", truthy: !!literalValue2(unwrapped) } : { kind: "unresolved", source: oneLineTextOf3(expression) };
914
- }, templateAttributeText = (template, context, referenced) => {
915
- let scopedContext = { ...context, bindings: template.bindings, scope: template.scope }, text = "";
916
- for (let index = 0; index < template.expressions.length; index += 1) {
917
- text += template.quasis[index] ?? "";
918
- let expression = template.expressions[index], value = resolveHoleValue(expression, scopedContext);
919
- if (value.kind === "unresolved")
920
- return { kind: "unresolved", source: value.source };
921
- value.arg && referenced?.add(value.arg);
922
- let resolved = attributeValue(value, scopedContext, referenced);
923
- if (resolved.kind === "unresolved")
924
- return resolved;
925
- text += resolved.value === void 0 ? "" : String(resolved.value);
926
- }
927
- return text += template.quasis.at(-1) ?? "", { kind: "text", text };
928
- }, isImported2 = (local, importName, sources, bindings) => {
929
- let binding = bindings.get(local);
930
- return !!binding && sources.includes(binding.importId) && binding.importName === importName;
931
- };
932
-
933
- // src/docgen/story-docs/template-print.ts
934
- import { oneLineTextOf as oneLineTextOf4 } from "storybook/internal/csf-tools";
935
- function printHtmlTemplate(template, storyArgs, declaration) {
936
- return printTemplate(template, {
937
- bindings: template.bindings,
938
- declaration,
939
- scope: template.scope,
940
- storyArgs
941
- });
797
+ return { names, rest };
942
798
  }
943
- var printTemplate = (template, context) => printTemplateWithListeners(template, context, !0), printTemplateWithListeners = (template, context, allowRootListeners) => {
944
- let scopedContext = { ...context, bindings: template.bindings, scope: template.scope }, nonce = `${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`, markers = /* @__PURE__ */ new Map(), source = template.quasis.reduce((html, quasi, index) => {
945
- let expression = template.expressions[index];
946
- if (!expression)
947
- return html + quasi;
948
- let marker = `__STORYBOOK_HOLE_${nonce}_${index}__`;
949
- return markers.set(marker, expression), `${html}${quasi}${marker}`;
950
- }, ""), state = {
951
- context: scopedContext,
952
- falseDefaults: /* @__PURE__ */ new Set(),
953
- listeners: [],
954
- listenersNotShown: /* @__PURE__ */ new Set(),
955
- lit: template.lit,
956
- markers,
957
- properties: /* @__PURE__ */ new Set(),
958
- referenced: /* @__PURE__ */ new Set(),
959
- unresolved: /* @__PURE__ */ new Set()
960
- };
961
- for (let expression of template.expressions)
962
- collectReferencedArgs(expression, scopedContext.scope).forEach(
963
- (arg) => state.referenced.add(arg)
964
- );
965
- let nodes = resolveTemplateNodes(parseHtml(source), state, 0), hostRoots = nodes.filter((node) => node.kind === "element" && node.name !== "style"), rootElements = nodes.filter((node) => node.kind === "element" || node.kind === "rawText");
966
- !(allowRootListeners && hostRoots.length === 1 && rootElements.at(-1) === hostRoots[0]) && state.listeners.length > 0 && (state.listeners.forEach((listener) => state.listenersNotShown.add(`@${listener.event}`)), state.listeners = []);
967
- let script = printRootListenerScript(state.listeners), snippet = printHtml(nodes);
799
+ var memberKey = (node) => node.computed ? isStringLiteral(node.property) ? node.property.value : void 0 : node.property.type === "Identifier" ? node.property.name : void 0, isName = (node, parent) => parent?.type === "MemberExpression" && parent.property === node && !parent.computed || parent?.type === "Property" && parent.key === node && !parent.computed && parent.value !== node, bindsName = (node, names) => {
800
+ let targets = node.type === "VariableDeclarator" ? [node.id] : node.type === "AssignmentExpression" ? [node.left] : node.type === "UpdateExpression" ? [node.argument] : node.type === "CatchClause" && node.param ? [node.param] : "params" in node && Array.isArray(node.params) ? node.params : [], binds = !1;
801
+ return targets.forEach(
802
+ (target) => walk(target, (child) => {
803
+ binds ||= child.type === "Identifier" && names.has(child.name);
804
+ })
805
+ ), binds;
806
+ }, needsParentheses = (node, parent) => parent?.type === "MemberExpression" && parent.object === node || parent?.type === "ArrowFunctionExpression" && parent.body === node || parent?.type === "BinaryExpression" && parent.operator === "-" && parent.right === node || (parent?.type === "CallExpression" || parent?.type === "NewExpression") && parent.callee === node || parent?.type === "UnaryExpression" || parent?.type === "UpdateExpression" || parent?.type === "BinaryExpression" && parent.operator === "**";
807
+ function edit(read, args) {
808
+ let before = `${read.shorthand ? `${read.shorthand}: ` : ""}${read.wrap ? "(" : ""}`, after = read.wrap ? ")" : "";
809
+ if (read.arg === void 0) {
810
+ let entries = Object.entries(args).filter(([name]) => !read.rest?.includes(name)).map(([name, node]) => `${printKey(name)}: ${valueCode(name, node)}`);
811
+ return { before, value: `{ ${entries.join(", ")} }`, after };
812
+ }
968
813
  return {
969
- ...state.falseDefaults.size === 0 ? {} : { falseDefaults: [...state.falseDefaults] },
970
- listeners: state.listeners,
971
- ...state.listenersNotShown.size === 0 ? {} : { listenersNotShown: [...state.listenersNotShown] },
972
- properties: [...state.properties],
973
- referenced: [...state.referenced],
974
- snippet: script ? `${snippet}
975
- ${script}` : snippet,
976
- unresolved: [...state.unresolved]
814
+ before,
815
+ value: valueCode(read.arg, args[read.arg]),
816
+ after,
817
+ hole: { kind: "code", arg: read.arg }
977
818
  };
978
- }, resolveTemplateNodes = (nodes, state, depth) => nodes.flatMap((node) => resolveTemplateNode(node, state, depth)), resolveTemplateNode = (node, state, depth) => {
979
- switch (node.kind) {
980
- case "element":
981
- return [
982
- {
983
- ...node,
984
- attributes: resolveAttributes(node.name, node.attributes, state, depth),
985
- children: resolveTemplateNodes(node.children, state, depth + 1)
986
- }
987
- ];
988
- case "text":
989
- return resolveTextNode(node.text, state);
990
- case "comment":
991
- return [{ ...node, text: removeUnsupportedMarkers(node.text, state) }];
992
- case "rawText":
993
- return [{ ...node, text: removeUnsupportedMarkers(node.text, state) }];
994
- case "malformed":
995
- return [{ ...node, text: removeUnsupportedMarkers(node.text, state) }];
996
- default:
997
- return node;
998
- }
999
- }, resolveAttributes = (tag, attributes, state, depth) => {
1000
- let resolved = [];
1001
- for (let attribute of attributes) {
1002
- let next = resolveAttribute(tag, attribute, state, depth);
1003
- next && upsertAttribute(resolved, next);
1004
- }
1005
- return resolved;
1006
- }, resolveAttribute = (tag, attribute, state, depth) => {
1007
- if (containsMarker(attribute.name, state)) {
1008
- unresolvedMarkers(attribute.name, state);
1009
- return;
1010
- }
1011
- if (attribute.value === void 0 || !containsMarker(attribute.value, state))
1012
- return attribute;
1013
- let prefix = state.lit ? attribute.name[0] : void 0;
1014
- if (prefix === "?") {
1015
- let value = resolveFirstMarker(attribute.value, state);
1016
- return value && isTruthyAttributeValue(value) ? { name: attribute.name.slice(1), value: void 0 } : void 0;
1017
- }
1018
- if (prefix === "@") {
1019
- let value = resolveFirstMarker(attribute.value, state), event = attribute.name.slice(1);
1020
- depth === 0 ? state.listeners.push({
1021
- event,
1022
- handler: value ? listenerHandler(value) : "() => {}"
1023
- }) : state.listenersNotShown.add(`@${event}`);
1024
- return;
1025
- }
1026
- if (prefix === ".") {
1027
- let property = attribute.name.slice(1), paired = pairedAttribute(property, state.context.declaration);
1028
- if (!paired) {
1029
- state.properties.add(property);
1030
- return;
1031
- }
1032
- let markers2 = markersIn(attribute.value, state), value = markers2.length === 1 && attribute.value === markers2[0] ? resolveFirstMarker(attribute.value, state) : void 0;
1033
- if (!value || value.kind === "unresolved") {
1034
- state.unresolved.add(
1035
- value?.kind === "unresolved" ? value.source : markerSources(markers2, state)
1036
- );
1037
- return;
1038
- }
1039
- let resolved = attributeValue(value, state.context, state.referenced);
1040
- if (resolved.kind === "unresolved") {
1041
- state.unresolved.add(resolved.source);
1042
- return;
1043
- }
1044
- return resolved.value === !1 && fieldDefault(property, state.context.declaration) === "true" && state.falseDefaults.add(property), attributeFromPrinted(
1045
- printAttribute({ name: paired, value: resolved.value, viaField: !0 })
1046
- );
1047
- }
1048
- let markers = markersIn(attribute.value, state), singleDynamicValue = markers.length === 1 && attribute.value === markers[0], text = attribute.value;
1049
- for (let marker of markers) {
1050
- let expression = state.markers.get(marker);
1051
- if (!expression)
1052
- continue;
1053
- let value = resolveMarkerValue(expression, state);
1054
- if (value.kind === "function") {
1055
- state.unresolved.add(oneLineTextOf4(expression));
1056
- return;
1057
- }
1058
- if (value.kind === "nothing")
1059
- return;
1060
- if (value.kind === "unresolved") {
1061
- state.unresolved.add(value.source);
1062
- return;
1063
- }
1064
- let resolved = attributeValue(value, state.context, state.referenced);
1065
- if (resolved.kind === "unresolved") {
1066
- state.unresolved.add(resolved.source);
1067
- return;
1068
- }
1069
- if (!attribute.quoted && !singleDynamicValue && resolved.value === void 0 && text.startsWith(marker))
1070
- return;
1071
- let valueText = resolved.value === null || resolved.value === void 0 ? "" : String(resolved.value);
1072
- text = text.replace(marker, valueText);
1073
- }
1074
- return { name: attribute.name, value: text };
1075
- }, resolveTextNode = (text, state) => {
1076
- let markers = markersIn(text, state);
1077
- if (markers.length === 0)
1078
- return [{ kind: "text", text }];
1079
- let nodes = [], rest = text;
1080
- for (let marker of markers) {
1081
- let [before, after] = rest.split(marker);
1082
- before && nodes.push({ kind: "text", text: before });
1083
- let expression = state.markers.get(marker);
1084
- expression && nodes.push(...nodesForChildValue(resolveMarkerValue(expression, state), state)), rest = after ?? "";
1085
- }
1086
- return rest && nodes.push({ kind: "text", text: rest }), nodes;
1087
- }, nodesForChildValue = (value, state) => {
1088
- switch (value.kind) {
1089
- case "empty":
1090
- case "nothing":
1091
- return [];
1092
- case "function":
1093
- return state.unresolved.add(value.source ?? value.handler), [];
1094
- case "template": {
1095
- let nested = printTemplateWithListeners(value.template, state.context, !1);
1096
- return nested.properties.forEach((property) => state.properties.add(property)), nested.referenced.forEach((arg) => state.referenced.add(arg)), nested.unresolved.forEach((source) => state.unresolved.add(source)), nested.listenersNotShown?.forEach((listener) => state.listenersNotShown.add(listener)), parseHtml(nested.snippet.replace(/<script>[\s\S]*<\/script>$/, ""));
1097
- }
1098
- case "unresolved":
1099
- return state.unresolved.add(value.source), [];
1100
- case "value":
1101
- if (value.value === null || value.value === void 0 || value.value === "")
1102
- return [];
1103
- if (Array.isArray(value.value)) {
1104
- let text = value.value.map((item) => item ?? "").join("");
1105
- return state.lit ? [{ kind: "text", text: escapeText(text) }] : parseHtml(text);
1106
- }
1107
- return state.lit ? [{ kind: "text", text: escapeText(String(value.value)) }] : parseHtml(String(value.value));
1108
- default:
1109
- return value;
1110
- }
1111
- }, resolveMarkerValue = (expression, state) => {
1112
- let value = resolveHoleValue(expression, state.context);
1113
- return value.arg && state.referenced.add(value.arg), value;
1114
- }, resolveFirstMarker = (text, state) => {
1115
- let marker = markersIn(text, state)[0], expression = marker ? state.markers.get(marker) : void 0;
1116
- return expression ? resolveMarkerValue(expression, state) : void 0;
1117
- }, removeUnsupportedMarkers = (text, state) => {
1118
- let next = text;
1119
- for (let marker of markersIn(text, state)) {
1120
- let expression = state.markers.get(marker);
1121
- expression && state.unresolved.add(oneLineTextOf4(expression)), next = next.replace(marker, "");
1122
- }
1123
- return next;
1124
- }, unresolvedMarkers = (text, state) => {
1125
- for (let marker of markersIn(text, state)) {
1126
- let expression = state.markers.get(marker);
1127
- expression && state.unresolved.add(oneLineTextOf4(expression));
1128
- }
1129
- }, containsMarker = (text, state) => markersIn(text, state).length > 0, markersIn = (text, state) => [...state.markers.keys()].filter((marker) => text.includes(marker)), markerSources = (markers, state) => markers.map((marker) => state.markers.get(marker)).filter((expression) => expression !== void 0).map(oneLineTextOf4).join(", "), attributeFromPrinted = (attribute) => {
1130
- if (!attribute)
1131
- return;
1132
- let [node] = parseHtml(`<x ${attribute}></x>`);
1133
- return node?.kind === "element" ? node.attributes[0] : void 0;
1134
- }, upsertAttribute = (attributes, next) => {
1135
- let index = attributes.findIndex((attribute) => attribute.name === next.name);
1136
- if (index === -1) {
1137
- attributes.push(next);
1138
- return;
1139
- }
1140
- attributes[index] = next;
1141
- };
819
+ }
820
+ var valueCode = (name, node) => {
821
+ let value = node ? evaluateArgValue(node) : { kind: "unset" };
822
+ return value.kind === "value" ? printValue(value.value, name, { quote: "'" }) : value.kind === "unset" || !node ? "undefined" : detachedTextOf(node);
823
+ }, printKey = (name) => /^[A-Za-z_$][\w$]*$/.test(name) ? name : printValue(name, name, { quote: "'" });
1142
824
 
1143
825
  // src/docgen/story-docs/build-story-docs.ts
1144
826
  var NO_COMPONENT_WARNING = "No static snippet: `meta.component` is not set.", openStoryReferences = createStoryReferenceResolver();
@@ -1202,6 +884,10 @@ var buildPayload = (input, storyImportPath, csf, snippetFor, name) => {
1202
884
  id: story.id,
1203
885
  name: story.name ?? storyNameFromExport(exportName),
1204
886
  ...result.snippet === void 0 ? {} : { snippet: result.snippet },
887
+ ...result.snippet === void 0 || result.template === void 0 ? {} : {
888
+ // A value a control clears leaves no gap or empty line.
889
+ template: withHoleSpace(result.template, (hole) => hole.kind !== "code")
890
+ },
1205
891
  ...result.warning === void 0 ? {} : { warning: result.warning },
1206
892
  ...description ? { description } : {},
1207
893
  ...summary === void 0 ? {} : { summary }
@@ -1236,38 +922,27 @@ var buildPayload = (input, storyImportPath, csf, snippetFor, name) => {
1236
922
  }, renderedArgsSnippet = (exportName, resolved, deps) => {
1237
923
  let warnings = [], render = resolveEffectiveRender(deps.csf, exportName, deps.resolveStoryArgs.ctx);
1238
924
  if (render.kind === "resolved") {
1239
- let template = resolveHtmlTemplate(render.node, deps.csf);
1240
- if (template) {
1241
- let printed = printHtmlTemplate(template, resolved.args, deps.declaration), unresolved = [...resolved.unresolved, ...printed.unresolved];
1242
- warnings.push(unresolvedWarning(unresolved)), warnings.push(incompleteList(printed.properties, "properties without an attribute")), warnings.push(
1243
- incompleteList(printed.falseDefaults ?? [], "false values that HTML cannot express")
1244
- ), warnings.push(incompleteList(printed.listenersNotShown ?? [], "listeners not shown")), warnings.push(unboundTemplateArgs(resolved.args, printed.referenced));
1245
- let hasFailedHole = unresolved.length > 0 || printed.properties.length > 0, hasSnippet = printed.snippet !== "" || !hasFailedHole;
1246
- return {
1247
- ...hasSnippet ? { snippet: printed.snippet } : {},
1248
- ...joinWarnings(hasSnippet ? warnings : [...warnings, noSnippetWarning(unresolved)])
1249
- };
1250
- }
1251
- warnings.push(unresolvedWarning([oneLineTextOf5(render.node)]));
925
+ let code = render.node.body && renderSnippet(render.node, exportName, resolved.args);
926
+ if (code)
927
+ return code;
928
+ warnings.push(unresolvedWarning([oneLineTextOf2(render.node)]));
1252
929
  } else render.kind === "unresolved" && warnings.push(unresolvedWarning(unresolvedRenderSource(render, resolved)));
1253
930
  let args = argsSnippet(
1254
931
  resolved.args,
1255
932
  deps.declaration,
1256
933
  deps.docgenPayload.argTypes ?? {},
1257
934
  deps.tag,
1258
- resolved.unresolved
935
+ resolved.unresolved,
936
+ render.kind !== "missing"
1259
937
  );
1260
938
  return warnings.push(args.warning), {
1261
- ...args.snippet ? { snippet: args.snippet } : {},
939
+ ...args.snippet ? { snippet: args.snippet, template: args.template } : {},
1262
940
  ...joinWarnings(warnings)
1263
941
  };
1264
- }, unboundTemplateArgs = (args, referenced) => {
1265
- let bound = new Set(referenced), unbound = Object.entries(args).filter(([name, node]) => !bound.has(name) && evaluateArgValue(node).kind !== "unset").map(([name]) => name);
1266
- return incompleteList(unbound, "args not bound by the render template");
1267
942
  }, unresolvedRenderSource = (render, resolved) => {
1268
943
  let node = resolved.storyMembers.properties.render ?? resolved.metaMembers.properties.render ?? render.shadowedRender;
1269
- return node ? [oneLineTextOf5(node)] : [];
1270
- }, argsSnippet = (args, declaration, argTypes, tag, unresolvedArgs) => {
944
+ return node ? [oneLineTextOf2(node)] : [];
945
+ }, argsSnippet = (args, declaration, argTypes, tag, unresolvedArgs, customRender) => {
1271
946
  let snippet = {
1272
947
  tag,
1273
948
  attributes: [],
@@ -1283,7 +958,7 @@ var buildPayload = (input, storyImportPath, csf, snippetFor, name) => {
1283
958
  let binding = classifyArg(key, value.kind === "function", argTypes ?? {}, declaration);
1284
959
  switch (binding.kind) {
1285
960
  case "listener":
1286
- binding.event ? snippet.listeners.push({ event: binding.event, handler: listenerHandler2(node), tag }) : listeners.push(key);
961
+ binding.event ? snippet.listeners.push({ event: binding.event, handler: listenerHandler(node), tag }) : listeners.push(key);
1287
962
  break;
1288
963
  case "property":
1289
964
  properties.push(key);
@@ -1310,39 +985,78 @@ var buildPayload = (input, storyImportPath, csf, snippetFor, name) => {
1310
985
  incompleteList(unknown, `args not declared by \`${tag}\``),
1311
986
  incompleteList(falseDefaultAttributes(snippet), "false values that HTML cannot express")
1312
987
  ], allUnresolved = [...unresolvedArgs, ...unresolved], printed = hasSnippetContent(snippet) || allUnresolved.length === 0;
1313
- return warnings.push(printed ? unresolvedWarning(allUnresolved) : noSnippetWarning(allUnresolved)), {
1314
- ...printed ? { snippet: printElementSnippet(snippet) } : {},
988
+ if (warnings.push(printed ? unresolvedWarning(allUnresolved) : noSnippetWarning(allUnresolved)), !printed)
989
+ return joinWarnings(warnings);
990
+ let html = printElementSnippet(snippet);
991
+ return {
992
+ snippet: html,
993
+ template: elementTemplate(html, snippet, args, argTypes, declaration, customRender),
1315
994
  ...joinWarnings(warnings)
1316
995
  };
1317
- }, addBoundValue = (snippet, binding, source, value, tag) => {
996
+ }, elementTemplate = (html, snippet, args, argTypes, declaration, customRender) => {
997
+ let kinds = new Map(
998
+ Object.entries(args).map(([key, node]) => [key, evaluateArgValue(node).kind])
999
+ ), template = {
1000
+ ...snippet,
1001
+ attributes: [...snippet.attributes],
1002
+ cssProperties: [...snippet.cssProperties],
1003
+ slots: [...snippet.slots],
1004
+ styleRules: [...snippet.styleRules]
1005
+ }, properties = [], guarded = [];
1006
+ for (let key of /* @__PURE__ */ new Set([...Object.keys(args), ...Object.keys(argTypes ?? {})])) {
1007
+ let binding = classifyArg(key, kinds.get(key) === "function", argTypes ?? {}, declaration);
1008
+ switch (binding.kind) {
1009
+ case "attribute":
1010
+ case "cssProperty":
1011
+ case "slot":
1012
+ case "cssPart":
1013
+ case "cssState":
1014
+ kinds.get(key) !== "value" && addBoundValue(template, binding, key, void 0, snippet.tag, !0);
1015
+ break;
1016
+ case "property":
1017
+ case "unknown":
1018
+ customRender || binding.kind === "unknown" && parseArgKey(key) ? guarded.push(key) : properties.push({
1019
+ arg: key,
1020
+ name: binding.kind === "property" ? binding.name : key,
1021
+ tag: snippet.tag
1022
+ });
1023
+ break;
1024
+ default:
1025
+ break;
1026
+ }
1027
+ }
1028
+ let marks = createHoleMarks2([html]), guards = guarded.map((arg) => marks.mark({ kind: "guard", arg }, "")).join(""), props = properties.length === 0 ? "" : marks.mark({ kind: "props", spread: !0, properties }, "", `
1029
+ `);
1030
+ return marks.toTemplate(guards + printElementSnippet(template, marks) + props);
1031
+ }, addBoundValue = (snippet, binding, source, value, tag, unset = !1) => {
1032
+ let upsert = unset ? addIfAbsent : upsertByName;
1318
1033
  switch (binding.kind) {
1319
1034
  case "attribute":
1320
- upsertByName(snippet.attributes, {
1035
+ upsert(snippet.attributes, {
1321
1036
  name: binding.name,
1322
1037
  value,
1323
1038
  viaField: binding.viaField,
1324
1039
  defaultValue: binding.defaultValue,
1325
- source
1040
+ source,
1041
+ arg: source
1326
1042
  });
1327
1043
  break;
1328
1044
  case "cssProperty":
1329
- upsertByName(snippet.cssProperties, { name: binding.name, value });
1045
+ upsert(snippet.cssProperties, { name: binding.name, value, arg: source });
1330
1046
  break;
1331
1047
  case "slot":
1332
- upsertByName(snippet.slots, { name: binding.name, html: value });
1048
+ upsert(snippet.slots, { name: binding.name, html: value, arg: source });
1333
1049
  break;
1334
1050
  case "cssPart":
1335
- upsertBySelector(snippet.styleRules, {
1336
- selector: `${tag}::part(${binding.name})`,
1337
- declarations: String(value)
1338
- });
1339
- break;
1340
- case "cssState":
1341
- upsertBySelector(snippet.styleRules, {
1342
- selector: `${tag}:state(${binding.name})`,
1343
- declarations: String(value)
1344
- });
1051
+ case "cssState": {
1052
+ let selector = binding.kind === "cssPart" ? `${tag}::part(${binding.name})` : `${tag}:state(${binding.name})`, rule = {
1053
+ selector,
1054
+ declarations: unset ? void 0 : String(value),
1055
+ arg: source
1056
+ };
1057
+ unset ? snippet.styleRules.some((existing) => existing.selector === selector) || snippet.styleRules.push(rule) : upsertBySelector(snippet.styleRules, rule);
1345
1058
  break;
1059
+ }
1346
1060
  default:
1347
1061
  return binding;
1348
1062
  }
@@ -1353,6 +1067,8 @@ var buildPayload = (input, storyImportPath, csf, snippetFor, name) => {
1353
1067
  return;
1354
1068
  }
1355
1069
  items[index] = next;
1070
+ }, addIfAbsent = (items, next) => {
1071
+ items.some((item) => item.name === next.name) || items.push(next);
1356
1072
  }, upsertBySelector = (items, next) => {
1357
1073
  let index = items.findIndex((item) => item.selector === next.selector);
1358
1074
  if (index === -1) {
@@ -1360,7 +1076,7 @@ var buildPayload = (input, storyImportPath, csf, snippetFor, name) => {
1360
1076
  return;
1361
1077
  }
1362
1078
  items[index] = next;
1363
- }, falseDefaultAttributes = (snippet) => snippet.attributes.filter(({ value, defaultValue }) => value === !1 && defaultValue === "true").map(({ source, name }) => source ?? name), hasSnippetContent = (snippet) => snippet.attributes.length > 0 || snippet.cssProperties.length > 0 || snippet.listeners.length > 0 || snippet.slots.length > 0 || snippet.styleRules.length > 0, listenerHandler2 = (node) => isFunctionNode(unwrapExpression4(node)) ? handlerText(node) : "() => {}", incompleteList = (names, suffix) => names.length === 0 ? void 0 : `Incomplete snippet: ${suffix}: ${names.map((name) => `\`${name}\``).join(", ")}.`, joinWarnings = (parts) => {
1079
+ }, falseDefaultAttributes = (snippet) => snippet.attributes.filter(({ value, defaultValue }) => value === !1 && defaultValue === "true").map(({ source, name }) => source ?? name), hasSnippetContent = (snippet) => snippet.attributes.length > 0 || snippet.cssProperties.length > 0 || snippet.listeners.length > 0 || snippet.slots.length > 0 || snippet.styleRules.length > 0, handlerText = (node) => reindent(detachedTextOf2(node), "", " "), listenerHandler = (node) => isFunctionNode(unwrapExpression2(node)) ? handlerText(node) : "() => {}", incompleteList = (names, suffix) => names.length === 0 ? void 0 : `Incomplete snippet: ${suffix}: ${names.map((name) => `\`${name}\``).join(", ")}.`, joinWarnings = (parts) => {
1364
1080
  let warning = [...new Set(parts.filter((part) => part !== void 0))].join(`
1365
1081
  `);
1366
1082
  return warning === "" ? {} : { warning };