import{j as e}from"./assertThisInitialized-ClXgY4BW.js";import{G as I,t as P}from"./api-D469Uxm1.js";import{d as G,u as N}from"./dataProvider-BSMCbdJg.js";import{r as J,a as W}from"./ideExtension-Duoj5XVI.js";import{r as l}from"./index-BP8_t0zE.js";import{A as _}from"./utils-CkyKHvS2.js";import{R as S}from"./ReferenceManyField-Do-6y4r4.js";import{S as A}from"./SimpleList-DYXh3sa6.js";import{T as C}from"./Typography-E7d16C50.js";import{A as k}from"./AdminContext-jMMnnv4u.js";import{d as U}from"./defaultI18nProvider-C_r1y4tu.js";import{R as q}from"./ResourceContextProvider-_t2ysSg2.js";import{R as z}from"./useRecordContext-CmNI-aHo.js";import{S as B}from"./Show-CQpDTbX7.js";import{S as H,L as h}from"./SimpleShowLayout-Bj8OsoZA.js";import{T as R}from"./TextField-n0Myx-gm.js";import{a as T,L as F}from"./ListNoResults-BHi6V5m8.js";import{u as K}from"./useDataProvider-BTi1EEZL.js";import"./useResourceDefinitionContext-mEDLreK0.js";import"./debounce-0x2xWYwC.js";import"./useGetList-Dit6Yzrj.js";import"./useQuery-DJhJ3Hj4.js";import"./useLogout-DAYYFX4P.js";import"./Button-C3j8Wgdd.js";import"./hooks-kyAPvxe4.js";import"./usePaginationState-CSxOqUBu.js";import"./useRemoveFromStore-DvPdj666.js";import"./useResourceContext-BI9mATY-.js";import"./index-qEiLzbkV.js";import"./index-BCKAMao3.js";import"./TextField-z9WrHgJg.js";import"./useFormControl-D0zEVldg.js";import"./createSvgIcon-C1LdFc73.js";import"./Modal-CloRq8hE.js";import"./Avatar-CDOhctCa.js";import"./ListItemText-Cc_vo_cp.js";import"./listItemTextClasses-C7xWMLDP.js";import"./useGetRecordRepresentation-DwGaoA_n.js";import"./useAuthenticated-CxLvTTH7.js";import"./_isIterateeCall-D0xvKagp.js";import"./identity-B2iMGpmP.js";import"./useAuthState-Chcbfem2.js";import"./colorManipulator-DXmmM2jC.js";import"./PreferencesEditorContext-oPOmBo-a.js";import"./useRedirect-BE8GZC2N.js";import"./useRefresh-BVYjI9Ho.js";import"./useGetOne-Ddk2GsYy.js";import"./TopToolbar-BqW7kXvQ.js";import"./Toolbar-C8uTbHq-.js";import"./EditButton-DudJBc_J.js";import"./createSvgIcon-BeVLBbd8.js";import"./Card-Cv9uZOGS.js";import"./Title-Db_cbkJo.js";import"./warning-3oRADCZr.js";import"./Stack-BmeOikgJ.js";import"./getFieldLabelTranslationArgs-DwcCC9dO.js";import"./OptionalRecordContextProvider-ChL7EZ8k.js";import"./pick-BQz50zYv.js";import"./hasIn-BUTlUeuZ.js";import"./CardContent-C5u1opi3.js";const rt={title:"Relations/Reference/ListContextAdapter",component:_,decorators:[i=>Q(i)]},d={render:()=>{const i=P(({children:n})=>{const t=T(),[r,m]=l.useState();l.useEffect(()=>{t.data&&m(t.data)},[t.data]);let s;return t.isLoading||t.isPending||t.isFetching||t.error||!r?s={...t}:s={...t,data:r},e.jsx(F,{value:s,children:n})});return e.jsx(S,{reference:"userCompetences",target:"userId",children:e.jsx(I.InsertOnly,{children:e.jsx(i,{children:e.jsx(A,{primaryText:n=>`${n.grade} ${n.name}`,secondaryText:n=>n.description})})})})}},c={render:({reference:i,source:n})=>{const t=P(({children:r,reference:m,source:s})=>{const o=T(),[u,b]=l.useState(),x=K();l.useEffect(()=>{const M=async f=>{const{data:$}=await x.getMany(m,{ids:f.map(a=>a[s])}),w=f.map(a=>{const E=$.find(O=>O.id===a[s]);return{...a,...E}});b(w)};o.data&&M(o.data)},[o.data,x]);let p;return o.isLoading||o.isPending||o.isFetching||o.error||!u?p={...o}:p={...o,data:u},e.jsx(F,{value:p,children:r})});return e.jsx(S,{reference:"userCompetences",target:"userId",children:e.jsx(I.InsertOnly,{children:e.jsx(t,{reference:i,source:n,children:e.jsx(A,{primaryText:r=>`${r.grade} ${r.name}`,secondaryText:r=>r.description})})})})},args:{reference:J("competences",{title:"Child Resource",resourceId:"subresource",allowContext:!1}),source:W("competenceId",{resourceId:"parentResource",attributeSelectTitle:"Reference Attribute from JoinResource Resource to Child Resource"})}},Q=i=>e.jsx(k,{dataProvider:G,i18nProvider:U,children:e.jsx(q,{value:"people",children:e.jsx(z,{value:N[1],children:e.jsx(B,{resource:"people",id:1,children:e.jsxs(H,{children:[e.jsx(C,{variant:"body1",children:"Custom component for modifying list context"}),e.jsx(C,{variant:"h5",children:"User"}),e.jsx(h,{children:e.jsx(R,{source:"id"})}),e.jsx(h,{children:e.jsx(R,{source:"name"})}),e.jsx(i,{})]})})})})});var v,g,L;d.parameters={...d.parameters,docs:{...(v=d.parameters)==null?void 0:v.docs,source:{originalSource:`{
  render: () => {
    const ListContextAdapter = topLevel(({
      children
    }: {
      children: React.ReactNode;
    }) => {
      const listContext = useListContext();
      const [modifiedData, setModifiedData] = useState<unknown[]>();
      useEffect(() => {
        if (listContext.data) {
          // Write necessary data processing here 
          setModifiedData(listContext.data);
        }
      }, [listContext.data]);
      let value: ListControllerResult;
      if (listContext.isLoading || listContext.isPending || listContext.isFetching || listContext.error || !modifiedData) {
        value = {
          ...listContext
        };
      } else {
        value = {
          ...listContext,
          data: modifiedData
        };
      }
      return <ListContextProvider value={value}>
                {children}
            </ListContextProvider>;
    });
    return <ReferenceManyField reference={"userCompetences"} target={"userId"}>
            <GenerationInstructions.InsertOnly>
                <ListContextAdapter>
                    <SimpleList primaryText={record => \`\${record.grade} \${record.name}\`} secondaryText={record => record.description} />
                </ListContextAdapter>
            </GenerationInstructions.InsertOnly>
        </ReferenceManyField>;
  }
}`,...(L=(g=d.parameters)==null?void 0:g.docs)==null?void 0:L.source}}};var y,j,D;c.parameters={...c.parameters,docs:{...(y=c.parameters)==null?void 0:y.docs,source:{originalSource:`{
  render: ({
    reference,
    source
  }) => {
    const ListContextAdapter = topLevel(({
      children,
      reference: resource,
      source
    }: {
      children: React.ReactNode;
      source: string;
      reference: string;
    }) => {
      const listContext = useListContext();
      const [joinedData, setJoinedData] = useState<any[]>();
      const dataProvider = useDataProvider();
      useEffect(() => {
        const updateChildrenState = async (data: any[]) => {
          const {
            data: children
          } = await dataProvider.getMany(resource, {
            ids: data.map(parentRecord => parentRecord[source])
          });
          const joinedData = data.map(parentRecord => {
            const childRecord = children.find(child => child.id === parentRecord[source])!;
            return {
              ...parentRecord,
              ...childRecord
            };
          });
          setJoinedData(joinedData);
        };
        if (listContext.data) {
          updateChildrenState(listContext.data);
        }
      }, [listContext.data, dataProvider]);
      let value: ListControllerResult;
      if (listContext.isLoading || listContext.isPending || listContext.isFetching || listContext.error || !joinedData) {
        value = {
          ...listContext
        };
      } else {
        value = {
          ...listContext,
          data: joinedData
        };
      }
      return <ListContextProvider value={value}>
                {children}
            </ListContextProvider>;
    });
    return <ReferenceManyField reference={"userCompetences"} target={"userId"}>
            <GenerationInstructions.InsertOnly>
                <ListContextAdapter reference={reference} source={source}>
                    <SimpleList primaryText={record => \`\${record.grade} \${record.name}\`} secondaryText={record => record.description} />
                </ListContextAdapter>
            </GenerationInstructions.InsertOnly>
        </ReferenceManyField>;
  },
  args: {
    reference: resourceName("competences", {
      title: 'Child Resource',
      resourceId: 'subresource',
      allowContext: false
    }),
    source: attributeName("competenceId", {
      resourceId: 'parentResource',
      attributeSelectTitle: 'Reference Attribute from JoinResource Resource to Child Resource'
    })
  }
}`,...(D=(j=c.parameters)==null?void 0:j.docs)==null?void 0:D.source}}};const ot=["Deafult","WithDataFetching"];export{d as Deafult,c as WithDataFetching,ot as __namedExportsOrder,rt as default};
