b978f8a5cdc59f885928e68eccda261b765ee89647c6ce7e6c66df19806da70fb8e865d6e6e703d55c1bda0706ba1d54366103e1713b294094283d375485dc 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { defineComponent, inject, withDirectives, cloneVNode, Comment, Fragment, createVNode, Text } from 'vue';
  2. import { FORWARD_REF_INJECTION_KEY, useForwardRefDirective } from '../../../hooks/use-forward-ref/index.mjs';
  3. import { NOOP, isObject } from '@vue/shared';
  4. import { useNamespace } from '../../../hooks/use-namespace/index.mjs';
  5. const NAME = "ElOnlyChild";
  6. const OnlyChild = defineComponent({
  7. name: NAME,
  8. setup(_, {
  9. slots,
  10. attrs
  11. }) {
  12. var _a;
  13. const forwardRefInjection = inject(FORWARD_REF_INJECTION_KEY);
  14. const forwardRefDirective = useForwardRefDirective((_a = forwardRefInjection == null ? void 0 : forwardRefInjection.setForwardRef) != null ? _a : NOOP);
  15. return () => {
  16. var _a2;
  17. const defaultSlot = (_a2 = slots.default) == null ? void 0 : _a2.call(slots, attrs);
  18. if (!defaultSlot)
  19. return null;
  20. const [firstLegitNode, length] = findFirstLegitChild(defaultSlot);
  21. if (!firstLegitNode) {
  22. return null;
  23. }
  24. return withDirectives(cloneVNode(firstLegitNode, attrs), [[forwardRefDirective]]);
  25. };
  26. }
  27. });
  28. function findFirstLegitChild(node) {
  29. if (!node)
  30. return [null, 0];
  31. const children = node;
  32. const len = children.filter((c) => c.type !== Comment).length;
  33. for (const child of children) {
  34. if (isObject(child)) {
  35. switch (child.type) {
  36. case Comment:
  37. continue;
  38. case Text:
  39. case "svg":
  40. return [wrapTextContent(child), len];
  41. case Fragment:
  42. return findFirstLegitChild(child.children);
  43. default:
  44. return [child, len];
  45. }
  46. }
  47. return [wrapTextContent(child), len];
  48. }
  49. return [null, 0];
  50. }
  51. function wrapTextContent(s) {
  52. const ns = useNamespace("only-child");
  53. return createVNode("span", {
  54. "class": ns.e("content")
  55. }, [s]);
  56. }
  57. export { OnlyChild };
  58. //# sourceMappingURL=only-child.mjs.map