react-semaphor 0.1.424 → 0.1.426
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/analytics-protocol/index.cjs +1 -1
- package/dist/analytics-protocol/index.js +246 -91
- package/dist/appearance/index.cjs +1 -1
- package/dist/appearance/index.js +1 -1
- package/dist/brand-studio/index.cjs +2 -2
- package/dist/brand-studio/index.js +8 -8
- package/dist/chunks/{analyze-result-contract-D7pjjYPy.js → analyze-result-contract-DnfF8kBb.js} +434 -427
- package/dist/chunks/analyze-result-contract-ege_u6Nl.js +1 -0
- package/dist/chunks/{braces-8TRlDwDw.js → braces-BdbUk_r9.js} +1 -1
- package/dist/chunks/{braces-D2tStQjF.js → braces-CbO-aIwH.js} +1 -1
- package/dist/chunks/calendar-preferences-dialog-C-gN-vlq.js +1 -0
- package/dist/chunks/{calendar-preferences-dialog-D5mABNDT.js → calendar-preferences-dialog-tBSngRN-.js} +4 -4
- package/dist/chunks/{catalog-field-grounding-CJKAqtiC.js → catalog-field-grounding-AOGwWu0K.js} +11 -11
- package/dist/chunks/{switch-2bh3Hka1.js → code-editor-Pod1s6SK.js} +9927 -9098
- package/dist/chunks/code-editor-tfzm8LWW.js +138 -0
- package/dist/chunks/{common-types-4bjoIgvm.js → common-types-ClkOI-3O.js} +4 -4
- package/dist/chunks/comparison-document-migration-BJH1idOd.js +414 -0
- package/dist/chunks/comparison-document-migration-b6c3xiWh.js +1 -0
- package/dist/chunks/dashboard-JNK2ly_e.js +1402 -0
- package/dist/chunks/{index-Dzz6jXSY.js → dashboard-ZoKNg47G.js} +67158 -65267
- package/dist/chunks/{dashboard-briefing-launcher-DuWgwtxX.js → dashboard-briefing-launcher-0kR-QThz.js} +11 -6
- package/dist/chunks/{dashboard-briefing-launcher-BNDzMjjt.js → dashboard-briefing-launcher-BE-sNAzW.js} +226 -209
- package/dist/chunks/dashboard-controls-BUYTVauu.js +36 -0
- package/dist/chunks/dashboard-controls-Ce_Bps8f.js +2196 -0
- package/dist/chunks/dashboard-date-comparison-definition-BaYxjLi5.js +167 -0
- package/dist/chunks/dashboard-date-comparison-definition-DGZr3m-b.js +1 -0
- package/dist/chunks/dashboard-input-contract-BFpERluO.js +18 -0
- package/dist/chunks/dashboard-input-contract-DV3cshjz.js +1 -0
- package/dist/chunks/{dashboard-json-CkTEDNtH.js → dashboard-json-4quaFoSw.js} +16 -15
- package/dist/chunks/dashboard-json-81uc8aVR.js +1 -0
- package/dist/chunks/date-formatter-BTTYdAik.js +1 -0
- package/dist/chunks/date-formatter-D-89jTjG.js +514 -0
- package/dist/chunks/{edit-dashboard-visual-CRjVRZLk.js → edit-dashboard-visual-DqQsH7rN.js} +8470 -8520
- package/dist/chunks/edit-dashboard-visual-nVRXv1Lq.js +182 -0
- package/dist/chunks/{index-CjzRe2su.js → index-CnujJ3fa.js} +3 -3
- package/dist/chunks/{index-DRlMUglg.js → index-Dpm_VET4.js} +2 -2
- package/dist/chunks/{index-CJdxSyQq.js → index-If0wlXGi.js} +308 -308
- package/dist/chunks/index-jSrCwPQz.js +31 -0
- package/dist/chunks/{x-CXDkqdur.js → index-xHCrHprY.js} +59 -59
- package/dist/chunks/{layout-grid-C0OI-MRn.js → layout-grid-B08pP7v6.js} +1 -1
- package/dist/chunks/{layout-grid-CiubineE.js → layout-grid-D5tYJg1-.js} +1 -1
- package/dist/chunks/metric-comparison-BKgkMy9r.js +1 -0
- package/dist/chunks/metric-comparison-CWweq9RG.js +387 -0
- package/dist/chunks/{palette-C4KTXOug.js → palette-C0yjT5Tv.js} +1 -1
- package/dist/chunks/{palette-Cp1hqZtm.js → palette-jqaAcwiQ.js} +1 -1
- package/dist/chunks/{save-DgMfP0j8.js → save-HCJjjzdX.js} +1 -1
- package/dist/chunks/{save-C__QggEE.js → save-Xdc4pnys.js} +1 -1
- package/dist/chunks/{search-BHsQIWBV.js → search-DHZCro8B.js} +1 -1
- package/dist/chunks/{search-DNCejM7Z.js → search-Dcud9ajy.js} +1 -1
- package/dist/chunks/{update-policy-C1pmhLz9.js → update-policy-BgONreNd.js} +1 -1
- package/dist/chunks/{update-policy-BCJc0oI5.js → update-policy-CY2k-pJP.js} +9 -9
- package/dist/chunks/{use-create-flow-overlay-state-B-bYbtix.js → use-create-flow-overlay-state-CoANTEXS.js} +2 -2
- package/dist/chunks/{use-create-flow-overlay-state-B9vArrvr.js → use-create-flow-overlay-state-DUVIsF0y.js} +62 -62
- package/dist/chunks/validators-B4VMLX3_.js +1 -0
- package/dist/chunks/{validators-PXkij33j.js → validators-Cz-XuORM.js} +123 -119
- package/dist/dashboard/index.cjs +1 -1
- package/dist/dashboard/index.js +2 -2
- package/dist/dashboard-authoring/index.cjs +2 -2
- package/dist/dashboard-authoring/index.js +6 -4
- package/dist/data-app-builder/index.cjs +6 -6
- package/dist/data-app-builder/index.js +5 -5
- package/dist/data-app-codegen/index.cjs +1 -1
- package/dist/data-app-codegen/index.js +2 -2
- package/dist/data-app-codegen-node/index.cjs +1 -1
- package/dist/data-app-codegen-node/index.js +3 -3
- package/dist/data-app-sdk/index.cjs +1 -1
- package/dist/data-app-sdk/index.js +6 -6
- package/dist/data-app-sdk-adapters/index.cjs +1 -1
- package/dist/data-app-sdk-adapters/index.js +1 -1
- package/dist/data-app-sdk-validation/index.cjs +1 -1
- package/dist/data-app-sdk-validation/index.js +65 -68
- package/dist/format-utils/index.cjs +2 -2
- package/dist/format-utils/index.js +59 -58
- package/dist/index.cjs +1 -1
- package/dist/index.js +19 -19
- package/dist/style.css +1 -1
- package/dist/surfboard/index.cjs +1 -1
- package/dist/surfboard/index.js +3 -3
- package/dist/types/analytics-protocol.d.ts +337 -3
- package/dist/types/brand-studio.d.ts +2 -2
- package/dist/types/briefings.d.ts +65 -41
- package/dist/types/dashboard-assistant.d.ts +28 -7
- package/dist/types/dashboard-authoring.d.ts +123 -43
- package/dist/types/dashboard.d.ts +122 -48
- package/dist/types/data-app-builder.d.ts +2 -2
- package/dist/types/data-app-sdk.d.ts +1 -1
- package/dist/types/format-utils.d.ts +98 -10
- package/dist/types/index.js +1 -1
- package/dist/types/main.d.ts +264 -100
- package/dist/types/shared.d.ts +84 -43
- package/dist/types/surfboard.d.ts +124 -49
- package/dist/types/types.d.ts +135 -50
- package/package.json +2 -1
- package/dist/chunks/analyze-result-contract-DpDcImgk.js +0 -1
- package/dist/chunks/calendar-preferences-dialog-iokD3HbE.js +0 -1
- package/dist/chunks/contracts-CoCOpd_i.js +0 -11
- package/dist/chunks/contracts-CtB2VONT.js +0 -1
- package/dist/chunks/dashboard-controls-bbEF-AbK.js +0 -52
- package/dist/chunks/dashboard-controls-id39vb7G.js +0 -2322
- package/dist/chunks/dashboard-json-DVoqS1ks.js +0 -1
- package/dist/chunks/date-formatter-B4EBSe9C.js +0 -1
- package/dist/chunks/date-formatter-BlhBftA9.js +0 -416
- package/dist/chunks/edit-dashboard-visual-CkrxZCcp.js +0 -178
- package/dist/chunks/index-S1CGUcSz.js +0 -1406
- package/dist/chunks/switch-DMT7qf_R.js +0 -138
- package/dist/chunks/validators-DMlVbd1p.js +0 -1
- package/dist/chunks/x-B6ghREd2.js +0 -31
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";const K=require("./analyze-result-contract-
|
|
1
|
+
"use strict";const K=require("./analyze-result-contract-ege_u6Nl.js"),S=require("../data-app-sdk-adapters/index.cjs"),re=K.SEMAPHOR_DATA_APP_CODEGEN_SUMMARY_SCHEMA_VERSION,T=K.SEMAPHOR_DATA_APP_CODEGEN_SUMMARY_VALIDATOR_VERSION,k="semaphor-generated-data-app-contract/v1",G="semaphor-generated-data-app-contract-manifest/v1";function x(e){return E(e)?[...K.validateSemaphorDataAppCodegenSummary(e).issues,...ae(e)]:["Plan artifact must be a Semaphor codegenSummary object."]}function ne(e){const t=x(e);if(t.length>0)throw new Error(`Invalid Semaphor codegenSummary:
|
|
2
2
|
- ${t.join(`
|
|
3
3
|
- `)}`)}function ae(e){var r;const t=E(e);if(!t)return[];const n=[];return((r=E(t.validation))==null?void 0:r.status)==="blocked"&&n.push("validation.status blocked cannot be generated. Resolve blocked semantic model gaps and replan before generating contract files."),Array.isArray(t.unsupportedInsights)&&t.unsupportedInsights.forEach((i,o)=>{var a;((a=E(i))==null?void 0:a.reason)==="missing_relationship"&&n.push(`unsupportedInsights.${o}.reason missing_relationship blocks contract generation. Call semaphor_propose_semantic_model_change, apply an approved semantic model patch, and replan before generating contract files.`)}),Array.isArray(t.views)&&t.views.forEach((i,o)=>{var s;const a=E((s=E(i))==null?void 0:s.computation);(a==null?void 0:a.kind)==="unsupported"&&a.reason==="missing_relationship"&&n.push(`views.${o}.computation.reason missing_relationship blocks contract generation. Call semaphor_propose_semantic_model_change, apply an approved semantic model patch, and replan before generating contract files.`)}),n}function E(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}const J=["sources.ts","fields.ts","inputs.ts","queries.ts","bindings.ts","accessors.ts","metadata.ts","index.ts"],ie=["USAGE.md"],Y=[...J,...ie,"contract.manifest.json"];async function se({manifest:e,generatedFiles:t}){const n=[],r=y(e);if(!r)return{issues:[{message:"Generated contract manifest must be an object.",repairHint:"Regenerate the generated contract instead of hand-editing the manifest."}]};r.schemaVersion!==G&&n.push({path:"schemaVersion",message:`schemaVersion must be ${G}. Regenerate the contract with semaphor_create_data_app_contract.`,repairHint:"Regenerate the contract with semaphor_create_data_app_contract."}),r.generatedContractSchemaVersion!==k&&n.push({path:"generatedContractSchemaVersion",message:`generatedContractSchemaVersion must be ${k}. Regenerate the contract with semaphor_generate_data_app_contract.`,repairHint:"Regenerate the contract with semaphor_generate_data_app_contract."});const i=y(r.generator);A(i==null?void 0:i.name)||n.push({path:"generator.name",message:"generator.name is required.",repairHint:"Regenerate the generated contract so manifest generator metadata is written deterministically."}),A(i==null?void 0:i.version)||n.push({path:"generator.version",message:"generator.version is required.",repairHint:"Regenerate the generated contract so manifest generator metadata is written deterministically."});for(const a of x(r.codegenSummary))n.push({path:`codegenSummary.${a}`,message:`codegenSummary.${a}`,repairHint:"Regenerate the generated contract from a valid Data App codegenSummary."});if(r.codegenSummaryValidatorVersion!==T&&n.push({path:"codegenSummaryValidatorVersion",message:`codegenSummaryValidatorVersion must be ${T}. Regenerate the contract with semaphor_generate_data_app_contract.`,repairHint:"Regenerate the contract with semaphor_generate_data_app_contract."}),typeof r.codegenSummaryHash!="string")n.push({path:"codegenSummaryHash",message:"codegenSummaryHash is required.",repairHint:"Regenerate the generated contract so manifest hashes are written deterministically."});else if(y(r.codegenSummary)){const a=await fe(r.codegenSummary);r.codegenSummaryHash!==a&&n.push({path:"codegenSummaryHash",message:"codegenSummaryHash does not match codegenSummary. Regenerate the contract instead of editing the manifest.",repairHint:"Regenerate the generated contract instead of editing the manifest."})}n.push(...de(r.codegenSummary));const o=t?oe(t):[];if(n.push(...o),t&&o.length===0&&n.push(...ce(t)),typeof r.generatedContentHash!="string")n.push({path:"generatedContentHash",message:"generatedContentHash is required.",repairHint:"Regenerate the generated contract so manifest hashes are written deterministically."});else if(t&&o.length===0){const a=await ue(t);r.generatedContentHash!==a&&n.push({path:"generatedContentHash",message:"generatedContentHash does not match generated TypeScript files. Regenerate the contract instead of hand-editing generated files.",repairHint:"Regenerate the contract instead of hand-editing generated files."})}return{issues:n}}function oe(e){var r;const t=[],n=new Set(Y);for(const i of Object.keys(e)){if(i.includes("/")||i.includes("\\")){const o=((r=i.split("/").pop())==null?void 0:r.split("\\").pop())||i;t.push({path:`generatedFiles.${i}`,message:`generatedFiles keys must be generated filenames such as "${o}", not path-qualified keys such as "${i}".`,repairHint:'Pass generatedFiles keyed by filename, for example "queries.ts", not "src/semaphor/generated/queries.ts".'});continue}n.has(i)||t.push({path:`generatedFiles.${i}`,message:`generatedFiles contains unknown generated contract file "${i}".`,repairHint:"Pass only the generated files returned by semaphor_generate_data_app_contract, keyed by filename."})}return t}function ce(e){const t=e["USAGE.md"];return typeof t!="string"?[{path:"generatedFiles.USAGE.md",message:"generatedFiles.USAGE.md is required.",repairHint:"Regenerate the generated contract so the generated usage guide is written."}]:["queries","queryOptionsForView","rowsForView","metricValuesForView","kpiPropsForView","roleValuesForView","appInputSpecs","inputOptionQueries"].filter(r=>!t.includes(`\`${r}\``)).map(r=>({path:"generatedFiles.USAGE.md",message:`generatedFiles.USAGE.md must document ${r}.`,repairHint:"Regenerate the generated contract so the usage guide matches generated exports."}))}function de(e){const t=y(e);if(!t)return[];const n=[],r=new Set(b(t.inputs).map(o=>{var a;return(a=y(o))==null?void 0:a.id}).filter(A)),i=new Set(b(t.views).map(o=>{var a;return(a=y(o))==null?void 0:a.id}).filter(A));return b(t.filterContracts).forEach((o,a)=>{const s=y(o),c=s==null?void 0:s.inputId;(!A(c)||!r.has(c))&&n.push({path:`codegenSummary.filterContracts.${a}.inputId`,message:`codegenSummary.filterContracts.${a}.inputId must reference a generated input.`,repairHint:"Regenerate the generated contract from a valid planner output."}),Array.isArray(s==null?void 0:s.bindings)&&s.bindings.forEach((u,f)=>{const p=y(u),m=p==null?void 0:p.viewId;(!A(m)||!i.has(m))&&n.push({path:`codegenSummary.filterContracts.${a}.bindings.${f}.viewId`,message:`codegenSummary.filterContracts.${a}.bindings.${f}.viewId must reference a generated view.`,repairHint:"Regenerate the generated contract from a valid planner output."});const h=y(p==null?void 0:p.fieldRef);A(h==null?void 0:h.name)||n.push({path:`codegenSummary.filterContracts.${a}.bindings.${f}.fieldRef`,message:`codegenSummary.filterContracts.${a}.bindings.${f}.fieldRef is required.`,repairHint:"Regenerate the generated contract from a valid planner output."})})}),n}async function ue(e){const t=Object.keys(e).filter(r=>r.endsWith(".ts")).sort();let n="";for(const r of t)n+=`${r}\0${e[r]}\0`;return`sha256:${await Q(n)}`}async function fe(e){return`sha256:${await Q(M(e))}`}function M(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(r=>M(r)).join(",")}]`;const t=e;return`{${Object.keys(t).sort().filter(r=>t[r]!==void 0).map(r=>`${JSON.stringify(r)}:${M(t[r])}`).join(",")}}`}async function Q(e){var r;if(!((r=globalThis.crypto)!=null&&r.subtle))throw new Error("SHA-256 digest support is required for generated contract validation.");const t=new TextEncoder().encode(e),n=await globalThis.crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}function y(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function b(e){return Array.isArray(e)?e:[]}function A(e){return typeof e=="string"&&e.length>0}function pe(e){const t=d(e),n=V(t),r=[],i=[];return I(t==null?void 0:t.views).filter(o=>{var s;const a=d((s=d(o))==null?void 0:s.sdkSpec);return!!(a!=null&&a.builder&&(a!=null&&a.spec))}).forEach((o,a)=>{var u;const s=String(((u=d(o))==null?void 0:u.id)||`view_${a}`),c=W(o,n);if(c){r.push({viewId:s,...c});return}i.push({viewId:s,path:`views.${s}.sdkSpec`,message:`Generated view execution validation could not build intent for "${s}".`})}),{requests:r,issues:i}}function W(e,t){const n=d(e),r=d(n==null?void 0:n.sdkSpec),i=d(r==null?void 0:r.spec);if(!n||!(r!=null&&r.builder)||!i)return null;const o=me(t)?t:V(d(t)),a=be(r.builder),s=d(w(i,o))||{},c=ye({view:n,builder:a,rawSpec:i,spec:{...s,id:n.id,label:Ne(n,i)},context:o});try{if(a==="analysis"){const u=c;return{intent:S.toSemaphorAnalysisIntent(u),resultShape:"analysis",analysisOptions:S.toSemaphorAnalysisQueryOptions(u)}}if(a==="metric")return{intent:S.toSemaphorMetricIntent(c),resultShape:"metric"};if(a==="records")return{intent:S.toSemaphorRecordsIntent(c),resultShape:"records"};if(a==="matrix")return{intent:S.toSemaphorMatrixIntent(c),resultShape:"matrix"};if(a==="sql")return{intent:S.toSemaphorSqlIntent(c),resultShape:"sql"}}catch{return null}return null}function ge({input:e,filterContract:t,codegenSummary:n}){const r=d(e),i=d(t),o=d(r==null?void 0:r.optionQuery)||d(i==null?void 0:i.optionQuery);if(!r||!o)return null;const a=V(d(n)),s=d(o.spec),c=he(o,s,a),u=o.valueFieldRef||o.valueField||(s==null?void 0:s.valueField),f=o.labelFieldRef||o.labelField||(s==null?void 0:s.labelField);if(!c||!u||!f)return null;const m={...d(w(s||{},a))||{},id:o.id||(s==null?void 0:s.id)||`${r.id}-options`,inputId:r.id,source:c,valueField:u,labelField:f,population:o.population||(s==null?void 0:s.population),dependencies:o.dependencies||(s==null?void 0:s.dependencies),limit:o.limit||(s==null?void 0:s.limit)||100};try{return S.toSemaphorInputOptionsIntent(w(m,a))}catch{return null}}function le({input:e,filterContract:t,binding:n,option:r,codegenSummary:i}){const o=V(d(i)),a=d(e),s=d(t),c=d(n),u=w((c==null?void 0:c.fieldRef)||(s==null?void 0:s.fieldRef)||(a==null?void 0:a.fieldRef),o),f=String((s==null?void 0:s.operator)||(a==null?void 0:a.operator)||"in"),p=Fe(c);return{inputId:String((s==null?void 0:s.inputId)||(a==null?void 0:a.id)||""),kind:"filter",operator:f,value:He(f,r.value),isActive:!0,...u?{field:u}:{},...p?{relationshipHint:p}:{}}}function V(e){return{sourcesByKey:new Map(I(e==null?void 0:e.sources).map(d).filter(Me).filter(t=>typeof t.sourceKey=="string").map(t=>[String(t.sourceKey),Z(t)]))}}function me(e){var t;return e instanceof Object&&((t=d(e))==null?void 0:t.sourcesByKey)instanceof Map}function he(e,t,n){if(typeof e.sourceKey=="string")return n.sourcesByKey.get(e.sourceKey)||{sourceKey:e.sourceKey};if(e.source)return e.source;if(t!=null&&t.source)return t.source;if(typeof(t==null?void 0:t.sourceKey)=="string")return n.sourcesByKey.get(t.sourceKey)||{sourceKey:t.sourceKey}}function ye({view:e,builder:t,rawSpec:n,spec:r,context:i}){var s;if(t!=="records"&&t!=="sql")return r;const o=d((s=d(e.visualSpec))==null?void 0:s.tableBehavior);if(!o)return r;const a={...r};if(Oe(o)==="server"&&(a.pagination={page:1,pageSize:Se({tableBehavior:o,spec:r})}),t==="records"&&Ve(o)==="server"){const c=Ae({view:e,rawSpec:n,tableBehavior:o,context:i});c&&(a.orderBy=c)}return a}function Se({tableBehavior:e,spec:t}){const n=d(e.pagination),r=d(t.pagination);return F(n==null?void 0:n.pageSize)||F(r==null?void 0:r.pageSize)||F(t.limit)||100}function Ae({view:e,rawSpec:t,tableBehavior:n,context:r}){const i=d(n.sorting),o=g(i==null?void 0:i.defaultField);if(!o)return;const s=_e({view:e,rawSpec:t,context:r}).filter(c=>we(c.lookup).includes(o));if(s.length===1)return{field:s[0].field,direction:(i==null?void 0:i.defaultDirection)==="desc"?"desc":"asc"}}function _e({view:e,rawSpec:t,context:n}){var i;const r=[];for(const o of I(t.fields))$(r,o,n);$(r,t.dateField,n),$(r,(i=d(t.orderBy))==null?void 0:i.field,n);for(const o of I(e.fields))$(r,o,n);return Te(r,o=>Ee(o.lookup))}function $(e,t,n){const r=d(t);if(typeof(r==null?void 0:r.name)!="string"||r.name.length===0)return;const i=d(w(r,n))||r;e.push({lookup:r,field:i})}function we(e){return ke([g(e.name),X(e),Ie(e)])}function Ee(e){return[X(e),g(e.name),g(e.role),g(e.aggregate)].join("|")}function X(e){return[g(e.sourceKey)||Re(e.source),g(e.name),g(e.aggregate)].filter(Boolean).join(":")}function Re(e){const t=d(e);if(!t)return"";if(typeof t.kind=="string"&&typeof t.domainId=="string"){if(typeof t.datasetId=="string")return`${t.kind}:${t.domainId}:datasetId:${t.datasetId}`;if(typeof t.datasetName=="string")return`${t.kind}:${t.domainId}:datasetName:${t.datasetName}`}return JSON.stringify(t)}function Ie(e){return Ge([ve(e),g(e.aggregate).toLowerCase(),g(e.label)||g(e.name)].filter(Boolean))}function ve(e){return typeof e.sourceKey=="string"?Ce(e.sourceKey):$e(e.source)}function $e(e){const t=d(e);return t?g(t.datasetName)||g(t.datasetId)||g(t.name)||g(t.kind):""}function Ce(e){const t=String(e).split(":");return t[t.length-1]||String(e)}function Oe(e){var t;return g((t=d(e.pagination))==null?void 0:t.mode)}function Ve(e){var t;return g((t=d(e.sorting))==null?void 0:t.mode)}function w(e,t){if(!e||typeof e!="object")return e;if(Array.isArray(e))return e.map(i=>w(i,t));const n=e;if(typeof n.sourceKey=="string"&&typeof n.kind=="string"&&(typeof n.datasetName=="string"||typeof n.datasetId=="string"))return Z(n);const r={};for(const[i,o]of Object.entries(n))i!=="sourceKey"&&(r[i]=w(o,t));if(typeof n.sourceKey=="string"){const i=t.sourcesByKey.get(n.sourceKey);i&&!r.source&&(r.source=i)}return r}function Z(e){const{sourceKey:t,...n}=e;return n}function Ne(e,t){const n=d(e.visualSpec);return(n==null?void 0:n.title)||e.title||t.label}function be(e){const t=String(e||"").replace(/^semaphor\./,"");return["metric","records","analysis","matrix","sql"].includes(t)?t:""}function Fe(e){if(e!=null&&e.relationshipHint)return e.relationshipHint;const t=I(e==null?void 0:e.relationshipsUsed).map(n=>{var r;return(r=d(n))==null?void 0:r.id}).filter(n=>typeof n=="string"&&n.length>0);return t.length>0?{relationshipIds:t}:void 0}function He(e,t){return e==="in"||e==="not_in"?[t]:e==="between"?Array.isArray(t)?t:[t,t]:t}function F(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function g(e){return typeof e=="string"?e:""}function Te(e,t){const n=new Set,r=[];for(const i of e){const o=t(i);!o||n.has(o)||(n.add(o),r.push(i))}return r}function ke(e){return Array.from(new Set(e.filter(Boolean)))}function Ge(e){return(Array.isArray(e)?e.join(" "):e).replace(/[^a-zA-Z0-9]+/g," ").trim().split(/\s+/).filter(Boolean).map((n,r)=>{const i=n.toLowerCase();return r===0?i:i.charAt(0).toUpperCase()+i.slice(1)}).join("")}function d(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function I(e){return Array.isArray(e)?e:[]}function Me(e){return e!==void 0}const De=new Set(["diagnostic_fix","fix_diagnostics","fix_inspector_warnings","fix_runtime_warnings","fix_warnings"]),Ke=new Set(["add","edit","mixed","remove"]),j=new Set(["fields","metricBindingKeys","sdkSpec"]);function xe({beforeSummary:e,afterSummary:t,migrationReport:n,operationIntent:r,constraints:i,preferences:o}){const a=l(r),s=typeof(a==null?void 0:a.kind)=="string"?a.kind.trim():"";return Ke.has(s)?{ok:!1,policy:{kind:s,mode:"invalid_operation_kind",reason:"Retired Data App operation aliases are not accepted. Use the hard-migrated analytics/layout/style operationIntent kinds."},violations:[{path:"operationIntent.kind",reason:"Use analytics_add, analytics_edit, analytics_remove, input_add, input_edit, layout_only, style_only, runtime_debug, semantic_model_repair, save_or_publish, or greenfield_create."}]}:B(o)?{ok:!1,policy:{kind:s,mode:"invalid_update_constraints",reason:"Metric aggregate override updates must use operationIntent.measureAggregateOverrides so deterministic update policy can guard the targeted edit."},violations:[{path:"preferences.measureAggregateOverrides",reason:"preferences is retired. Move measureAggregateOverrides to operationIntent.measureAggregateOverrides for update calls."}]}:B(i)?{ok:!1,policy:{kind:s,mode:"invalid_update_constraints",reason:"Metric aggregate override updates must use operationIntent.measureAggregateOverrides so deterministic update policy can guard the targeted edit."},violations:[{path:"constraints.measureAggregateOverrides",reason:"Move measureAggregateOverrides to operationIntent.measureAggregateOverrides for update calls."}]}:De.has(s)?U({beforeSummary:e,afterSummary:t,migrationReport:n,operationIntent:a,mode:"diagnostic_warning_fix",allowedViewChangeReasons:j,label:"Diagnostic warning fixes",reason:"Diagnostic warning fixes are preserve-by-default and may not add/remove views, inputs, or filter contracts."}):s==="analytics_edit"&&Array.isArray(a==null?void 0:a.measureAggregateOverrides)&&a.measureAggregateOverrides.length>0?U({beforeSummary:e,afterSummary:t,migrationReport:n,operationIntent:a,mode:"metric_aggregate_override_edit",allowedViewChangeReasons:j,label:"Metric aggregate override edits",reason:"Metric aggregate override edits are preserve-by-default and may only adjust fields/sdkSpec on targeted views."}):{ok:!0,policy:{kind:s,mode:"general_iterative_update",reason:"General generated-contract edits are allowed to change the requested contract shape. Review the migration report for expected UI work."},violations:[]}}function B(e){var t;return Array.isArray((t=l(e))==null?void 0:t.measureAggregateOverrides)}function U({beforeSummary:e,afterSummary:t,migrationReport:n,operationIntent:r,mode:i,allowedViewChangeReasons:o,label:a,reason:s}){const c=[],u=je(r==null?void 0:r.targetViewIds),f=l(n)||{};u.size===0&&c.push({path:"operationIntent.targetViewIds",reason:`${a} must declare targetViewIds so the update cannot broaden to unrelated views.`}),H({bucket:l(f.views),label:"views",operationLabel:a,violations:c}),H({bucket:l(f.inputs),label:"inputs",operationLabel:a,violations:c}),L({bucket:l(f.inputs),label:"inputs",operationLabel:a,violations:c}),H({bucket:l(f.filterContracts),label:"filterContracts",operationLabel:a,violations:c}),L({bucket:l(f.filterContracts),label:"filterContracts",operationLabel:a,violations:c});for(const m of ee(l(f.views))){u.size>0&&!u.has(_(m.id))&&c.push({path:`views.${_(m.id)||"<unknown>"}`,reason:`${a} may only change explicitly targeted views.`});const h=Array.isArray(m.reasons)?m.reasons.filter(R=>typeof R!="string"||!o.has(R)):[];h.length>0&&c.push({path:`views.${_(m.id)||"<unknown>"}`,reason:`${a} may only adjust fields/sdkSpec/metricBindingKeys; changed ${h.join(", ")}.`})}const p=qe({beforeSummary:e,afterSummary:t,targetViewIds:u,label:a});return p&&c.push(p),{ok:c.length===0,policy:{kind:_(r==null?void 0:r.kind)||"diagnostic_fix",mode:i,allowedViewChangeReasons:Array.from(o).sort(),targetViewIds:Array.from(u).sort(),reason:s},violations:c}}function qe({beforeSummary:e,afterSummary:t,targetViewIds:n,label:r}){const i=l(e),o=l(t);if(!i||!o)return{path:"codegenSummary",reason:`${r} require before/after codegen summaries for full-scope verification.`};const a=P(i),s=P(o),c=z(i.views),u=z(o.views),f=Array.isArray(a.views)?a.views:[];a.views=f;for(const p of n){const m=c.get(p),h=u.get(p);if(!m||!h)continue;const R=f.find(te=>{var q;return((q=l(te))==null?void 0:q.id)===p}),v=l(h);if(!R||!v)continue;const N=R;N.fields=C(v.fields),N.metricBindingKeys=C(v.metricBindingKeys),N.sdkSpec=C(v.sdkSpec)}return O(a)===O(s)?null:{path:"codegenSummary",reason:`${r} may only change fields/sdkSpec/metricBindingKeys on targetViewIds; another generated contract section changed.`}}function P(e){const t=C(e);for(const n of["implementationChecklist","assumptions","nextStep","nextRequiredTool","validation"])delete t[n];return Ue(t.unsupportedInsights)&&delete t.unsupportedInsights,t}function H({bucket:e,label:t,operationLabel:n,violations:r}){for(const i of D(e==null?void 0:e.added))r.push({path:`${t}.${_(i.id)||"<unknown>"}`,reason:`${n} may not add ${t}.`});for(const i of D(e==null?void 0:e.removed))r.push({path:`${t}.${_(i.id)||"<unknown>"}`,reason:`${n} may not remove ${t}.`})}function L({bucket:e,label:t,operationLabel:n,violations:r}){for(const i of ee(e))r.push({path:`${t}.${_(i.id)||"<unknown>"}`,reason:`${n} may not change ${t}.`})}function ee(e){return D(e==null?void 0:e.changed)}function D(e){return Array.isArray(e)?e.map(l).filter(Be):[]}function je(e){return Array.isArray(e)?new Set(e.filter(t=>typeof t=="string"&&t.trim().length>0).map(t=>t.trim())):new Set}function z(e){var n;const t=new Map;for(const r of Array.isArray(e)?e:[]){const i=(n=l(r))==null?void 0:n.id;typeof i=="string"&&i.trim()&&t.set(i,r)}return t}function C(e){return e===void 0?e:JSON.parse(JSON.stringify(e))}function O(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(n=>O(n)).join(",")}]`;const t=e;return`{${Object.keys(t).sort().filter(n=>t[n]!==void 0).map(n=>`${JSON.stringify(n)}:${O(t[n])}`).join(",")}}`}function l(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Be(e){return e!==void 0}function Ue(e){return Array.isArray(e)&&e.length===0}function _(e){return typeof e=="string"?e:""}exports.CODEGEN_SUMMARY_SCHEMA_VERSION=re;exports.CODEGEN_SUMMARY_VALIDATOR_VERSION=T;exports.CONTRACT_MANIFEST_SCHEMA_VERSION=G;exports.GENERATED_CONTRACT_SCHEMA_VERSION=k;exports.GENERATED_CONTRACT_TYPESCRIPT_FILES=J;exports.REQUIRED_GENERATED_CONTRACT_FILES=Y;exports.assertValidCodegenSummary=ne;exports.buildSemaphorGeneratedActiveInput=le;exports.buildSemaphorGeneratedInputOptionIntent=ge;exports.buildSemaphorGeneratedViewExecutionRequest=W;exports.buildSemaphorGeneratedViewExecutionRequests=pe;exports.evaluateSemaphorDataAppContractUpdatePolicy=xe;exports.validateCodegenSummary=x;exports.validateSemaphorGeneratedContract=se;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { S as W, a as X, v as Z } from "./analyze-result-contract-
|
|
1
|
+
import { S as W, a as X, v as Z } from "./analyze-result-contract-DnfF8kBb.js";
|
|
2
2
|
import { toSemaphorInputOptionsIntent as ee, toSemaphorAnalysisQueryOptions as te, toSemaphorAnalysisIntent as re, toSemaphorMetricIntent as ne, toSemaphorRecordsIntent as ae, toSemaphorMatrixIntent as se, toSemaphorSqlIntent as ie } from "../data-app-sdk-adapters/index.js";
|
|
3
3
|
const Je = W, x = X, G = "semaphor-generated-data-app-contract/v1", T = "semaphor-generated-data-app-contract-manifest/v1";
|
|
4
4
|
function P(e) {
|
|
@@ -899,13 +899,13 @@ export {
|
|
|
899
899
|
ue as R,
|
|
900
900
|
x as a,
|
|
901
901
|
T as b,
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
902
|
+
ce as c,
|
|
903
|
+
Ye as d,
|
|
904
|
+
Ze as e,
|
|
905
|
+
Xe as f,
|
|
906
|
+
he as g,
|
|
907
|
+
We as h,
|
|
908
|
+
et as i,
|
|
909
|
+
Qe as j,
|
|
910
910
|
P as v
|
|
911
911
|
};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";const C=require("react"),s=require("./
|
|
1
|
+
"use strict";const C=require("react"),s=require("./code-editor-tfzm8LWW.js"),f=require("./dashboard-JNK2ly_e.js"),e=require("react/jsx-runtime"),ee=require("./index-jSrCwPQz.js");require("./analyze-result-contract-ege_u6Nl.js");const ke=require("./save-Xdc4pnys.js"),ye=require("./search-Dcud9ajy.js");/**
|
|
2
2
|
* @license lucide-react v0.453.0 - ISC
|
|
3
3
|
*
|
|
4
4
|
* This source code is licensed under the ISC license.
|
|
@@ -8,4 +8,4 @@
|
|
|
8
8
|
*
|
|
9
9
|
* This source code is licensed under the ISC license.
|
|
10
10
|
* See the LICENSE file in the root directory of this source tree.
|
|
11
|
-
*/const Ee=ee.createLucideIcon("Link2",[["path",{d:"M9 17H7A5 5 0 0 1 7 7h2",key:"8i5ue5"}],["path",{d:"M15 7h2a5 5 0 1 1 0 10h-2",key:"1b9ql8"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]]);function Ie(r){const[a,o]=C.useState(null),[n,i]=C.useState(null),c=f.useEnsureReactGlobals();return C.useEffect(()=>{if(!r||r.trim()===""){o(null),i(null);return}if(!c)return;(async()=>{try{if(!r.startsWith("http://")&&!r.startsWith("https://"))throw new Error(`Invalid URL format: ${r}`);try{new URL(r)}catch{throw new Error(`Invalid URL: ${r}`)}const p=`${r.endsWith("/")?r:`${r}/`}index.js`;try{if(!(await fetch(p,{method:"HEAD"})).ok)throw new Error(`Module not found at ${p}`)}catch{}const v=await import(p);if(typeof v.useChartStore!="function")throw new Error("useChartStore is not a function");o(()=>v.useChartStore),i(null)}catch(x){const p=x instanceof Error?x.message:"Unknown error";console.error("Failed to load remote chart store:",p),i(p),o(null)}})()},[r,c]),a}function Te(r,a){if(r.length===0)return"";const o=r.find(n=>{var i,c;return((i=n.customCardPreferences)==null?void 0:i.visualType)==="multiple"||!!((c=n.customCardPreferences)!=null&&c.dataInputCardIds)});if(o)return o.id;if(a){const n=r.find(i=>i.id===a);if(n){const i=n.tabTitle;if(i=="All__Header")return r[0].id;if(i&&i.endsWith("__Header")){const m=i.split("__")[0],x=r.find(p=>p.tabTitle===m);return x?x.id:r[0].id}return a}}return r[0].id}const ue=new Set;function Le(r){return ue.add(r),()=>{ue.delete(r)}}function we(){ue.forEach(r=>{r()})}const Ae=r=>{if(!r||!("detailTableBackup"in r))return r;const{detailTableBackup:a,...o}=r;return o};async function ve(r,a,o,n,i="Opening library visual..."){if(!a||!o)throw new Error("Missing auth token or visual ID");const c=["resource-by-id","visual",o],m=n.getQueryData(c);if(m)return console.log("Using cached visual data for:",o),{data:m,fromCache:!0};console.log("Fetching visual data from network for:",o);const x=f.ue.loading(i,{position:"top-center"});try{const p=await fetch(`${r}/management/v1/visuals/${o}`,{headers:{Authorization:`Bearer ${a}`}});if(!p.ok)throw new Error("Failed to load visual");const v=await p.json();return n.setQueryData(c,v),f.ue.dismiss(x),{data:v,fromCache:!1}}catch(p){throw f.ue.dismiss(x),p}}function De(r){if(typeof r=="string")return JSON.parse(r);if(typeof r=="object")return r;throw new Error("Invalid frame object format")}function _e(r,a){var c,m;const o=(r==null?void 0:r.frameObject)??((c=r==null?void 0:r.visual)==null?void 0:c.frameObject);if(!o)return!1;const n=De(o);if(!(n!=null&&n.cards)||n.cards.length===0)return!1;const i=(m=n.cards)==null?void 0:m.find(x=>x.id===n.activeCardId);return i?(f.setupEditorWithCard({...a,frame:n,card:i,visualId:(r==null?void 0:r.id)||n.visualId}),!0):!1}function Be(){const r=s.useEditorStore(n=>{var i;return((i=n.card.customCardPreferences)==null?void 0:i.url)||""}),a=Ie(r);return{getUpdatedFrame:C.useCallback(()=>{var I;we();const{frame:n,card:i,isDevMode:c,isShowingVisual:m,selectedSchemaName:x,selectedDatamodelId:p,selectedDatabaseName:v,selectedTableName:g,selectedConnectionId:h}=s.useEditorStore.getState(),S=i.sql,w=(I=a==null?void 0:a.getState())==null?void 0:I.settings,k=s.buildSavedEditorCard(i,{isDevMode:c,cardSql:S,isShowingVisual:m,selectedSchemaName:x,selectedDatamodelId:p,selectedDatabaseName:v,selectedTableName:g,selectedConnectionId:h,remoteChartSettings:w,stripConfig:Ae}),E=n.cards.map(U=>U.id===i.id?k:U);return{...n,cards:E,activeCardId:Te(E,n.activeCardId)}},[a])}}function ae(){const{authToken:r,tokenProps:a}=f.useSemaphorContext(),o=f.useQueryClient(),n=f.useAddFrameWithFreshSemanticExecutionPayload(),i=f.useSelectedVisual(),{selectVisual:c}=f.useManagementActions(),{setFrame:m,setCard:x,setIsDevMode:p,initializeModeDrafts:v,setActiveTabCardId:g,updateDataSource:h,setQueryResultColumns:S,setSelectedConnectionId:w,setSelectedDatabaseName:k,setSelectedSchemaName:E,setSelectedTableName:I,setSelectedDatamodelId:U,setFilterValues:Y,setInlineFilterValuesMap:H,setApplyFilters:K,clearEditorContext:J}=s.useEditorActions(),{setIsDashboardEditing:q,setIsVisualEditing:l,setSelectedFrameId:D,clearSelectedFrameId:T}=s.useDashboardActions(),M=s.useDashboardStore(A=>A.selectedSheetId),Q=s.useDashboardStore(A=>A.selectedFrameId),W=s.useDashboardStore(A=>A.dashboard),G=s.useDashboardStore(A=>A.filterValues),_=s.useDashboardStore(A=>A.inlineFilterValuesMap),z=f.useVisualById((i==null?void 0:i.id)||"",{enabled:!!(i!=null&&i.id)&&!!(r!=null&&r.accessToken)}),$=C.useCallback(async A=>{try{c(A),T(),J();const{data:F,fromCache:P}=await ve(a.apiServiceUrl,(r==null?void 0:r.accessToken)||"",A.id,o,"Opening library visual...");if(!_e(F,{setFrame:m,setCard:x,setIsDevMode:p,initializeModeDrafts:v,setActiveTabCardId:g,updateDataSource:h,setQueryResultColumns:S,setSelectedConnectionId:w,setSelectedDatabaseName:k,setSelectedSchemaName:E,setSelectedTableName:I,setSelectedDatamodelId:U,setFilterValues:Y,setInlineFilterValuesMap:H,setApplyFilters:K,setIsDashboardEditing:q,setIsVisualEditing:l,dashboard:W,selectedSheetId:M,selectedFrameId:Q,filterValues:G,inlineFilterValuesMap:_}))throw new Error("Failed to setup editor with visual data");return{success:!0,fromCache:P}}catch(F){return console.error("Error editing visual:",F),{success:!1,error:"Failed to load visual for editing"}}},[r==null?void 0:r.accessToken,a.apiServiceUrl,o,c,m,x,q,l,p,v,g,h,S,w,k,E,I,U,Y,H,K,J,T,W,M,Q,G,_]),ne=C.useCallback(async A=>{var P;const F=B=>(f.ue.error(B),{success:!1,error:B});try{if(c(A),!M)return F("No sheet selected. Please select a sheet first.");const{data:B,fromCache:oe}=await ve(a.apiServiceUrl,(r==null?void 0:r.accessToken)||"",A.id,o,"Adding visual to dashboard..."),re=(B==null?void 0:B.frameObject)??((P=B==null?void 0:B.visual)==null?void 0:P.frameObject);if(!re)return F("Visual has no frame data");const R=De(re);if(!(R!=null&&R.cards)||R.cards.length===0)return F("Visual frame is malformed");const te={...f.cloneLinkedFrameWithSourceMapping(R),visualId:A.id};return await n(M,te,"end"),q(!0),D(te.id),{success:!0,fromCache:oe}}catch(B){return console.error("Error adding visual:",B),F(B instanceof Error?B.message:"Failed to add visual to dashboard")}},[r==null?void 0:r.accessToken,a.apiServiceUrl,o,c,M,q,D,n]);return{visual:z.data,isLoading:z.isLoading,isError:z.isError,error:z.error,handleEditLibraryVisual:$,handleAddLibraryVisual:ne,getUpdatedFrame:Be().getUpdatedFrame,refetch:z.refetch}}function qe(){const r=s.useEditorStore(m=>m.card.dataSource),{setSelectedConnectionId:a,setSelectedDatabaseName:o,setSelectedSchemaName:n,setSelectedTableName:i,setSelectedDatamodelId:c}=s.useEditorActions();C.useEffect(()=>{var w;if(!r)return;const{tableName:m,schemaName:x,databaseName:p,connectionId:v}=f.extractTableMetadata(r),g=(w=r.selectedEntities)==null?void 0:w[0],S=(g==null?void 0:g.type)==="model"&&"id"in g?g.id:"";a(v||""),o(p||""),n(x||""),i(m||""),c(S)},[r,a,o,n,i,c])}function pe(){var p,v;const r=s.useEditorStore(g=>g.card),a=s.useEditorStore(g=>g.frame),o=C.useMemo(()=>f.findCustomVisualConfigCard(a,r),[a,r]),{manifest:n}=f.useCustomVisual(((p=o==null?void 0:o.customCardPreferences)==null?void 0:p.url)||""),i=C.useMemo(()=>{var g;return(g=n==null?void 0:n.visuals)==null?void 0:g.find(h=>{var S;return h.name===((S=o==null?void 0:o.customCardPreferences)==null?void 0:S.componentName)})},[n,(v=o==null?void 0:o.customCardPreferences)==null?void 0:v.componentName]),c=f.resolveMultiInputType(o,i),m=C.useMemo(()=>f.getCustomVisualInputCards({frame:a,configCard:o,isMultiInputVisual:c==="multiple"}),[a,o,c]),x=C.useMemo(()=>{const g=m.findIndex(h=>(h==null?void 0:h.id)===r.id);return g<0?-1:f.getSlotIndexForCard(r,g)},[m,r]);return C.useMemo(()=>!o||c!=="multiple"||x<0?r.type:f.getEffectiveCardTypeForSlot(r,x,i==null?void 0:i.slots)??r.type,[o,c,x,r,i==null?void 0:i.slots])}function Me({type:r,isLinked:a,className:o,showLabel:n=!1,showLocal:i=!1}){const c=s.useDashboardStore(E=>E.selectedFrameId),m=f.useManagementStore(E=>E.selectedVisual),x=s.useEditorStore(E=>E.frame);let p;if(r)p=r;else if(a!==void 0)p=a?"linked":"library";else if(!!!(x!=null&&x.visualId||m!=null&&m.id)&&c)p="local";else if(m&&!c)p="library";else if(x!=null&&x.visualId&&c)p="linked";else if(m!=null&&m.id&&c)p="library";else return null;if(p==="local"&&!i)return null;const v={local:"border-slate-200/70 bg-slate-50/80 text-slate-700 shadow-sm hover:bg-slate-100/80 dark:border-slate-700 dark:bg-slate-900/70 dark:text-slate-200 dark:hover:bg-slate-800/80",linked:"border-purple-200/70 bg-gradient-to-r from-purple-50/50 to-purple-100/30 text-purple-900 shadow-sm hover:from-purple-100/60 hover:to-purple-100/50 hover:shadow-md dark:border-purple-800/50 dark:from-purple-950/40 dark:to-purple-900/30 dark:text-purple-100 dark:hover:from-purple-950/60 dark:hover:to-purple-900/50",library:"border-blue-200/70 bg-gradient-to-r from-blue-50/50 to-blue-100/30 text-blue-900 shadow-sm hover:from-blue-100/60 hover:to-blue-100/50 hover:shadow-md dark:border-blue-800/50 dark:from-blue-950/40 dark:to-blue-900/30 dark:text-blue-100 dark:hover:from-blue-950/60 dark:hover:to-blue-900/50"},g={local:"Local to this dashboard: Changes made here only affect this dashboard copy.",linked:"Linked to library: Changes made here update the library visual and all linked instances.",library:"Library visual: Share and reuse this visual across multiple dashboards."},h={local:"border-slate-200 bg-slate-50 text-slate-900 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-100",linked:"border-purple-200 bg-purple-50 text-purple-900 dark:border-purple-800 dark:bg-purple-950 dark:text-purple-100",library:"border-blue-200 bg-blue-50 text-blue-900 dark:border-blue-800 dark:bg-blue-950 dark:text-blue-100"},S={local:"fill-slate-50 dark:fill-slate-900",linked:"fill-purple-50 dark:fill-purple-950",library:"fill-blue-50 dark:fill-blue-950"},w={local:e.jsx("span",{className:"h-2 w-2 rounded-full bg-current/70"}),linked:e.jsx(Ee,{className:"h-3.5 w-3.5"}),library:e.jsx(Ne,{className:"h-3.5 w-3.5"})},k={local:"Local",linked:"Linked",library:"Library"};return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:300,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(f.Badge,{variant:"outline",className:s.cn("cursor-help select-none transition-all",v[p],o),children:[w[p],n&&e.jsx("span",{className:"ml-1 text-xs font-medium leading-none",children:k[p]})]})}),e.jsxs(s.TooltipContent,{side:"bottom",className:s.cn("max-w-xs",h[p]),children:[e.jsx(s.TooltipArrow,{className:S[p]}),e.jsx("p",{children:g[p]})]})]})})}function Oe(r,a){return{...r,sql:"",python:"",config:void 0,customCfg:"",preferences:{},interactionConfig:void 0,linkedInteractionTargetOverrides:void 0,dynamicCardPreferences:void 0,customCardPreferences:a?r.customCardPreferences:void 0,visualizationMode:"builtin",type:a?r.type:"bar"}}function me(r){const a=s.getDynamicFrameSaveIssue(r);return a?(f.ue.error(a),!1):!0}function Ue({className:r,variant:a="outline"}){const o=s.useEditorStore(c=>c.onSave),{getUpdatedFrame:n}=ae();function i(){const c=n();me(c)&&(o==null||o(c))}return e.jsxs(s.Button,{onClick:i,className:r,size:"xs",variant:a,children:[e.jsx(s.Check,{className:"h-3.5 w-3.5"}),"Accept"]})}function ze({className:r,variant:a="default"}){const o=f.useQueryClient(),[n,i]=C.useState(!1),{setIsVisualEditing:c}=s.useDashboardActions(),{getUpdatedFrame:m}=ae(),x=f.useSelectedVisual(),p=s.useEditorStore(h=>h.frame),v=f.useUpdateVisualMutation(),g=()=>{const h=m();if(!me(h))return;const S=(p==null?void 0:p.visualId)||(x==null?void 0:x.id);if(!S){f.ue.error("No visual to save");return}i(!0),v.mutate({visualId:S,data:{frameObject:h}},{onSuccess:()=>{i(!1),f.ue.success("Visual updated successfully"),o.invalidateQueries({queryKey:["resource-by-id","visual",S],exact:!0})},onError:()=>{i(!1),f.ue.error("Failed to update visual")}})};return e.jsx(s.Button,{onClick:g,className:r,size:"xs",variant:a,children:n?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}),"Saving"]}):e.jsxs(e.Fragment,{children:[e.jsx(ke.Save,{className:"h-3.5 w-3.5"}),"Save to Library"]})})}function Re({className:r}){const a=f.useQueryClient(),[o,n]=C.useState(!1),i=f.useSelectedVisual(),c=s.useEditorStore(k=>k.frame),m=s.useDashboardStore(k=>k.selectedSheetId),x=s.useDashboardStore(k=>k.dashboard),{updateFrame:p,setIsVisualEditing:v}=s.useDashboardActions(),{getUpdatedFrame:g}=ae(),h=f.useUpdateVisualMutation(),S=f.useResolveExistingFrameSemanticExecutionPayload(),w=async()=>{if(!m){f.ue.error("No sheet selected");return}const k=(c==null?void 0:c.visualId)||(i==null?void 0:i.id);if(!k){f.ue.error("No visual to update");return}n(!0);try{const E=g();if(!me(E)){n(!1);return}const I={...E,visualId:k},U=f.findDashboardFrameById(x,I.id),Y=await S(I,{previousFrame:U});await h.mutateAsync({visualId:k,data:{frameObject:E}}),p(m,I,{semanticExecutionPayload:Y}),a.invalidateQueries({queryKey:["visuals"]}),a.invalidateQueries({queryKey:["visual",k]}),f.ue.success("Saved to library and applied locally"),setTimeout(()=>{v(!1)},300)}catch(E){console.error("Failed to save and apply:",E),f.ue.error(E instanceof Error?E.message:"Failed to save and apply changes")}finally{n(!1)}};return e.jsx(s.Button,{onClick:w,className:r,size:"xs",variant:"default",disabled:o,children:o?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ke.Save,{className:"h-3.5 w-3.5"}),"Save & Apply"]})})}function Qe({className:r}){const{setTempQueryData:a,setSqlGen:o}=s.useEditorActions(),n=f.useQueryClient(),i=s.useEditorStore(h=>h.tempQueryData),c=s.useEditorStore(h=>h.onClose),m=s.useEditorStore(h=>h.card),x=pe(),p=C.useMemo(()=>x!==m.type?{...m,type:x}:m,[m,x]),{queryKey:v}=f.useEditorCardQuery(p);function g(){if(i){const{queryKey:h,queryData:S}=i;h&&S&&n.setQueryData(h,S)}o({}),c==null||c()}return e.jsxs(s.Button,{onClick:g,className:r,size:"xs",variant:"outline",children:[e.jsx(ee.X,{className:"h-3.5 w-3.5"}),"Close"]})}function Pe({label:r="Clear",variant:a="secondary",className:o}={}){const{setTempQueryData:n}=s.useEditorActions(),i=f.useQueryClient(),c=s.useEditorStore(q=>q.tempQueryData),m=s.useEditorStore(q=>q.card),x=pe(),p=C.useMemo(()=>x!==m.type?{...m,type:x}:m,[m,x]),{queryKey:v}=f.useEditorCardQuery(p),{setCardSql:g,setSqlGen:h,setCardPython:S,setCardCustomCfg:w,setCardPreferences:k,clearQueryConfig:E,setCardConfig:I,setCardType:U,setFrame:Y,setCard:H,setActiveTabCardId:K}=s.useEditorActions();function J(){var W,G,_,z;const q=i.getQueryData(v);c!=null&&c.queryData||n({queryKey:v,queryData:q}),i.setQueryData(v,null),i.removeQueries({queryKey:v,exact:!0}),g(""),h({}),E(),I(void 0),S(""),w(""),k({});const l=s.useEditorStore.getState().frame,D=s.useEditorStore.getState().card,T=f.findCustomVisualConfigCard(l,D),M=((W=T==null?void 0:T.customCardPreferences)==null?void 0:W.visualType)==="multiple"||!!((G=T==null?void 0:T.customCardPreferences)!=null&&G.dataInputCardIds)||(((_=T==null?void 0:T.customCardPreferences)==null?void 0:_.minInputs)||0)>1||(((z=T==null?void 0:T.customCardPreferences)==null?void 0:z.maxInputs)||0)>1,Q=Oe(D,M);Y({...l,cards:l.cards.map($=>$.id===Q.id?Q:$)}),K(Q.id),H(Q),M||U("bar")}return e.jsxs(s.Button,{onClick:J,className:o,size:"xs",variant:a,children:[e.jsx(ee.X,{className:"h-3.5 w-3.5"}),r]})}function Fe(r){const{control:a,onChange:o}=r;return e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx(s.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Label"}),e.jsx(s.Input,{size:"xs",value:a.label,placeholder:"Control label",onChange:n=>o(n.target.value)})]})}function $e(r){const{currentStep:a,labels:o}=r;return e.jsx("div",{className:"sticky top-0 z-10 -mx-1 border-b border-border/60 bg-background/95 px-1 pb-2.5 pt-1 backdrop-blur supports-[backdrop-filter]:bg-background/85",children:e.jsx("div",{className:"flex flex-wrap items-center gap-2 sm:gap-2.5",children:o.map((n,i)=>{const c=i+1,m=c===a,x=c<a;return e.jsxs(C.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:s.cn("flex h-5 w-5 items-center justify-center rounded-full border text-[10px] font-medium tabular-nums",m?"border-foreground bg-foreground text-background":x?"border-foreground/30 bg-foreground/10 text-foreground":"border-border/60 bg-background text-muted-foreground"),children:c}),e.jsx("span",{className:s.cn("text-[12px]",m?"font-medium text-foreground":"text-muted-foreground"),children:n})]}),i<o.length-1?e.jsx("span",{className:"h-px w-4 bg-border/60 sm:w-6","aria-hidden":"true"}):null]},n)})})})}function se(r){const{secondary:a,tertiary:o,primary:n}=r;return e.jsxs("div",{className:"sticky bottom-0 z-10 -mx-1 flex justify-end gap-2 border-t bg-background/95 px-1 pb-1 pt-3 backdrop-blur supports-[backdrop-filter]:bg-background/85",children:[a,o,n]})}function Ye(r){const{control:a,scope:o,detail:n}=r;return e.jsxs("div",{className:"flex items-start gap-2.5 rounded-control border border-border/60 bg-muted/30 px-3 py-2.5",children:[e.jsx(f.CircleCheck,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-foreground"}),e.jsxs("div",{className:"min-w-0 space-y-0.5",children:[e.jsx("div",{className:"text-[13px] font-medium text-foreground",children:a.label}),e.jsxs("div",{className:"text-[12px] text-muted-foreground",children:[s.getFriendlyTypeOption(a.type).label," ·"," ",s.getControlOptionPreview(a)," ·"," ",s.getPlacementLabel(o,a.placement)]}),n?e.jsx("div",{className:"text-[12px] text-muted-foreground",children:n}):null]})]})}function Ce(r){const{control:a,defaultValue:o,availableFieldChoices:n,availableMetricChoices:i,previewControlDefinitions:c,previewControlValues:m,onControlChange:x,onLabelChange:p,onDefaultValueChange:v,onBack:g,onNext:h,nextDisabled:S}=r;return e.jsxs("div",{className:"space-y-3",children:[e.jsx(Fe,{control:a,onChange:p}),e.jsx(f.ControlDefinitionOptionsEditor,{control:a,availableFieldChoices:n,availableMetricChoices:i,previewControlDefinitions:c,previewControlValues:m,controlLifecycle:"create",onChange:x}),e.jsx(f.ControlDefaultValueEditor,{control:a,value:o,onChange:v,allowNoDefault:!0,allowCardDefault:!0,hint:"This is the value viewers will see first.",previewControlDefinitions:c,previewControlValues:m}),e.jsx(se,{secondary:e.jsx(s.Button,{type:"button",variant:"outline",size:"xs",onClick:g,children:"Back"}),primary:e.jsx(s.Button,{type:"button",size:"xs",onClick:h,disabled:S,children:"Next"})})]})}const Ke=new Set(["grain_selector","aggregation_selector","field_selector","metric_selector"]);function Se(r){const{text:a,ariaLabel:o}=r,[n,i]=C.useState(!1);return e.jsxs("button",{type:"button","aria-label":o,onClick:async()=>{try{await navigator.clipboard.writeText(a),i(!0),setTimeout(()=>i(!1),1200)}catch(c){console.error("Failed to copy",c)}},className:"group flex w-full items-center justify-between gap-2 rounded-control bg-muted/40 px-2 py-1 text-left transition-colors hover:bg-muted/60 focus-visible:bg-muted/60 focus-visible:outline-none",children:[e.jsx("code",{className:"min-w-0 truncate font-mono text-[12px] text-foreground",children:a}),e.jsx("span",{className:"shrink-0 text-[11px] text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:n?"Copied":"Click to copy"})]})}function je(r){const{control:a,scope:o,createdReference:n,explorerContent:i,sqlDescription:c,summaryDetail:m,onBack:x,onCancel:p,onDone:v}=r,g=Ke.has(a.type),h=n.match(/\[\[param\.(.+?)\]\]/),S=h?`{{ param('${h[1]}') }}`:"";return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ye,{control:a,scope:o,detail:m}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-[13px] font-medium text-foreground",children:"How cards use this control"}),e.jsxs("div",{className:"divide-y divide-border/60 overflow-hidden rounded-control border border-border/60",children:[g?e.jsxs("div",{className:"space-y-1 px-3 py-2.5",children:[e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Explorer cards"}),e.jsx("div",{className:"text-[12px] text-muted-foreground",children:i})]}):null,e.jsxs("div",{className:"space-y-1.5 px-3 py-2.5",children:[e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"SQL cards"}),e.jsx(Se,{text:n,ariaLabel:"Copy SQL control reference"}),S?e.jsx(Se,{text:S,ariaLabel:"Copy Jinja control reference"}):null,e.jsxs("p",{className:"text-[12px] text-muted-foreground",children:[c," ",e.jsx("a",{href:"https://docs.semaphor.cloud/docs/concepts/template-expressions",target:"_blank",rel:"noreferrer",className:"underline underline-offset-2 hover:text-foreground",children:"Template expressions docs"}),"."]})]})]})]}),e.jsx(se,{secondary:e.jsx(s.Button,{type:"button",variant:"outline",size:"xs",onClick:x,children:"Back"}),tertiary:e.jsx(s.Button,{type:"button",variant:"outline",size:"xs",onClick:p,children:"Cancel"}),primary:e.jsx(s.Button,{type:"button",size:"xs",onClick:v,children:"Done"})})]})}function We(r){const a=s.createBlankControl(r.scope,r.existingControls,r.reservedIds),o=r.type===a.type?{...a,label:s.DEFAULT_LABEL_BY_TYPE[r.type]}:{...s.applyControlTypeChange({controls:[{...a,label:s.DEFAULT_LABEL_BY_TYPE[r.type]}],controlId:a.id,nextType:r.type}).controls[0],label:s.DEFAULT_LABEL_BY_TYPE[r.type]};return{step:2,control:o,defaultValue:s.getDefaultValueForType(o,void 0)}}function He({scope:r,controls:a,reservedControlIds:o,defaultValues:n,onChange:i,emptyMessage:c,initialCreateFlow:m=!1,usageByControlId:x,availableFieldChoices:p,availableMetricChoices:v,structuralParticipants:g,structuralParticipantIdsByControlId:h,card:S,allowedControlTypes:w,onCreateFlowActiveChange:k,onCreateFlowComplete:E}){const I=C.useMemo(()=>new Set(o||[]),[o]),U=s.getPlacementOptionsForScope(r),Y=s.getDefaultPlacement(r),[H,K]=C.useState(null),[J,q]=C.useState(null),[l,D]=C.useState(()=>m?{step:1,control:s.createBlankControl(r,a,Array.from(I))}:null),T=C.useRef({}),M=C.useRef(void 0),Q=C.useRef(m),W=C.useMemo(()=>{const t=s.getFriendlyControlTypeOptions({scope:r,card:S});if(!w)return t;const u=new Set(w);return t.filter(d=>u.has(d.value))},[w,S,r]),G=C.useCallback(t=>{const u=s.getFriendlyControlTypeOptions({scope:r,card:S,includeType:w?void 0:t});if(!w)return u;const d=new Set(w);return u.filter(b=>d.has(b.value))},[w,S,r]),_=C.useCallback(t=>r==="dashboard"&&(t==="field_selector"||t==="metric_selector"),[r]),z=C.useMemo(()=>l?s.getEligibleParticipantsForStructuralControl(g||[],l.control.type):[],[l,g]),$=C.useMemo(()=>{if(!l)return{fields:p||[],metrics:v||[]};if(!_(l.control.type))return{fields:p||[],metrics:v||[]};const t=l.selectedCardIds||[],u=s.getCompatibleStructuralChoiceCatalog({controlType:l.control.type,participants:g||[],selectedCardIds:t});return{fields:l.control.type==="field_selector"?u.choices.map(d=>({option:d,target:u.fieldTargetMap[d.value]})):[],metrics:l.control.type==="metric_selector"?u.choices.map(d=>({option:d,target:u.metricTargetMap[d.value]})):[]}},[p,v,l,_,g]);C.useEffect(()=>{k==null||k(!!l)},[l,k]),C.useEffect(()=>{const t=m&&!Q.current;Q.current=m,t&&(D({step:1,control:s.createBlankControl(r,a,Array.from(I))}),q(null),K(null))},[a,m,I,r]);const ne=t=>{if(!_(t.type))return{fields:p||[],metrics:v||[]};const u=(h==null?void 0:h[t.id])||[];if(u.length===0)return{fields:p||[],metrics:v||[]};const d=s.getCompatibleStructuralChoiceCatalog({controlType:t.type,participants:g||[],selectedCardIds:u});return{fields:t.type==="field_selector"?d.choices.map(b=>({option:b,target:d.fieldTargetMap[b.value]})):[],metrics:t.type==="metric_selector"?d.choices.map(b=>({option:b,target:d.metricTargetMap[b.value]})):[]}},A=t=>{if(!_(t.control.type))return{nextControl:t.control,cardBindingsById:void 0};const u=(h==null?void 0:h[t.control.id])||[],d=s.getCompatibleStructuralChoiceCatalog({controlType:t.control.type,participants:g||[],selectedCardIds:t.nextSelectedCardIds}),b=s.reconcileStructuralControlChoices({control:t.control,choices:d.choices}),j=Object.fromEntries(u.filter(N=>!t.nextSelectedCardIds.includes(N)).map(N=>[N,void 0]));return t.nextSelectedCardIds.length>0&&b.source.kind==="manual"&&b.source.options.length>0&&Object.assign(j,s.buildStructuralControlBindingsForParticipants({control:b,participants:g||[],selectedCardIds:t.nextSelectedCardIds})),{nextControl:b,cardBindingsById:j}},F=C.useCallback((t,u=n,d={type:"update"})=>{const b=t.map(j=>(s.resolveAuthoringControlDefaultValue({control:j,defaultValues:u}),s.syncSqlQueryControlExecutionRequirement(j)));i(b,u,d)},[n,i]),P=(t,u)=>{const d=a.find(L=>L.id===t);let b=a.map(L=>L.id!==t?L:u(L));const j=b.find(L=>L.id===t);let N,y;if(j&&r==="dashboard"&&(j.type==="field_selector"||j.type==="metric_selector")){const L=(h==null?void 0:h[j.id])||[],Z=A({control:j,nextSelectedCardIds:L});b=b.map(X=>X.id===t?Z.nextControl:X),N=Z.cardBindingsById,y=[j.id]}else if(d&&r==="dashboard"&&(d.type==="field_selector"||d.type==="metric_selector")){const L=(h==null?void 0:h[d.id])||[];N=Object.fromEntries(L.map(Z=>[Z,void 0])),y=[d.id]}const V=b.find(L=>L.id===t);let O=n;if(d&&V){const L=s.resolveAuthoringControlDefaultValue({control:d,defaultValues:n});d.source.kind==="manual"&&V.source.kind==="sql_query"&&(T.current[t]=L);const Z=L===void 0&&d.source.kind==="sql_query"&&V.source.kind==="manual"?T.current[t]:L,X=s.getNextEditedControlDefaultValue({previousControl:d,nextControl:V,currentDefaultValue:Z});V.source.kind==="manual"&&(T.current[t]=X),n&&(O={...n},X===void 0?delete O[t]:O[t]=X),b=b.map(be=>be.id===t?{...V,defaultValue:X}:be)}F(b,O,{type:"update",cardBindingsById:N,affectedBindingControlIds:y})},B=(t,u)=>{if(!u.trim())return;const d=f.normalizeDashboardInputVariableName(u);if(d===t||I.has(d)||a.some(N=>N.id===d&&N.id!==t))return;const b=a.map(N=>N.id===t?{...N,id:d}:N);if(!n){F(b,void 0,{type:"rename",oldId:t,newId:d});return}const j={...n};Object.prototype.hasOwnProperty.call(j,t)&&(j[d]=j[t],delete j[t]),F(b,j,{type:"rename",oldId:t,newId:d})},oe=t=>{const u=a.filter(b=>b.id!==t);if(!n){F(u,void 0,{type:"remove",controlId:t});return}const d={...n};delete d[t],F(u,d,{type:"remove",controlId:t})},re=C.useCallback(()=>{M.current=void 0,D({step:1,control:s.createBlankControl(r,a,Array.from(I))}),q(null),K(null)},[a,I,r]),R=t=>{D(u=>u&&(()=>{const d=t(u.control);u.control.source.kind==="manual"&&d.source.kind==="sql_query"&&(M.current=u.defaultValue);const b=u.defaultValue===void 0&&u.control.source.kind==="sql_query"&&d.source.kind==="manual"?M.current:u.defaultValue,j=s.getNextEditedControlDefaultValue({previousControl:u.control,nextControl:d,currentDefaultValue:b});return d.source.kind==="manual"&&(M.current=j),{...u,control:d,defaultValue:j}})())},te=t=>{D(u=>u&&(u.control.source.kind==="manual"&&(M.current=t),{...u,defaultValue:t}))},le=(()=>{if(!l)return!1;if(l.step===2&&_(l.control.type))return(l.selectedCardIds||[]).length>0;if(l.step!==2&&l.step!==3||!l.control.label.trim())return!1;const u=l.control.source.kind==="sql_query"?l.control:s.ensureManualSource(l.control);if(u.source.kind==="manual"&&(s.needsManualOptions(u)&&u.source.options.length===0||u.source.options.some(b=>b.label.trim().length===0||b.value.trim().length===0)))return!1;if(u.source.kind==="sql_query"){const{connectionId:d,sql:b,valueColumn:j}=u.source;return d.trim().length>0&&b.trim().length>0&&j.trim().length>0}return s.hasConcreteDefaultValue(s.getDefaultValueForType(u,l.defaultValue))})(),fe=()=>{var N;if(!l)return;const t=s.ensureManualSource(l.control),u=s.deriveUniqueControlId({label:t.label,fallbackId:t.id,existingControls:a,reservedIds:Array.from(I)}),d={...t,id:u},b=r==="dashboard"&&(d.type==="field_selector"||d.type==="metric_selector")&&((N=l.selectedCardIds)!=null&&N.length)?s.buildStructuralControlBindingsForParticipants({control:d,participants:g||[],selectedCardIds:l.selectedCardIds}):void 0,j=s.getDefaultValueForType(d,l.defaultValue);D({step:r==="dashboard"&&(d.type==="field_selector"||d.type==="metric_selector")?4:3,control:d,defaultValue:j,createdControlId:u,selectedCardIds:l.selectedCardIds,cardBindingsById:b})},ie=C.useCallback(()=>{D(null)},[]),xe=C.useCallback(()=>{if(!(l!=null&&l.createdControlId)){D(null);return}const t=l.control,u=l.createdControlId,d=s.getDefaultValueForType(t,l.defaultValue);if(n){const b={...n};d===void 0?delete b[u]:b[u]=d,F([...a,{...t,defaultValue:d}],b,{type:"add",cardBindingsById:l.cardBindingsById})}else F([...a,{...t,defaultValue:d}],void 0,{type:"add",cardBindingsById:l.cardBindingsById});q(u),D(null),E==null||E()},[a,l,n,F,E]),Ve=l?_(l.control.type)?["Choose type","Select cards","Configure","Finish"]:["Choose type","Configure","Finish"]:[],he=l!=null&&l.createdControlId?`[[param.${l.createdControlId}]]`:l?`[[param.${s.slugifyControlValue(l.control.label)||l.control.id}]]`:"",de=s.buildAuthoringPreviewControlValues({controls:a,defaultValues:n}),ce=l?[...a,l.control]:a,ge=l?s.buildAuthoringPreviewControlValues({controls:ce,defaultValues:n,overrides:[{controlId:l.control.id,value:l.defaultValue}]}):de;return e.jsxs("div",{className:"space-y-4",children:[l?e.jsxs("div",{className:"space-y-4 pb-1",children:[e.jsx($e,{currentStep:l.step,labels:Ve}),l.step===1&&(()=>{const t=new Set(["grain_selector","aggregation_selector","field_selector","metric_selector"]),u=new Set(["date","text"]),d=W.filter(N=>!t.has(N.value)&&!u.has(N.value)),b=W.filter(N=>t.has(N.value)),j=N=>e.jsxs("button",{type:"button",className:"rounded-control border border-border/60 bg-background px-3 py-2.5 text-left transition-colors hover:bg-muted/40 focus-visible:bg-muted/40 focus-visible:outline-none",onClick:()=>D(We({scope:r,existingControls:a,reservedIds:Array.from(I),type:N.value})),children:[e.jsx("div",{className:"text-[13px] font-medium text-foreground",children:N.label}),e.jsx("p",{className:"mt-0.5 text-[12px] text-muted-foreground",children:N.description})]},N.value);return e.jsxs("div",{className:"space-y-4",children:[r==="card"&&(S==null?void 0:S.sql)==null?e.jsx("p",{className:"text-[12px] text-muted-foreground",children:"Explorer cards support displayed metric, group by field, aggregation, and time grain controls here."}):null,d.length>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Input controls"}),e.jsx("div",{className:"grid gap-1.5 sm:grid-cols-2",children:d.map(j)})]}),b.length>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Data-driven controls"}),e.jsx("div",{className:"grid gap-1.5 sm:grid-cols-2",children:b.map(j)})]}),e.jsx(se,{secondary:e.jsx(s.Button,{type:"button",variant:"outline",size:"xs",onClick:ie,children:"Back to controls"})})]})})(),l.step===2&&_(l.control.type)&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(Fe,{control:l.control,onChange:t=>R(u=>({...u,label:t}))}),e.jsx("p",{className:"text-[12px] text-muted-foreground",children:"Choose which cards should respond to this shared control."})]}),z.length===0?e.jsx("div",{className:"rounded-control border border-border/60 bg-muted/30 px-3 py-2.5 text-[12px] text-muted-foreground",children:"No eligible cards are available yet. Add compatible metrics or group-by fields to cards first."}):e.jsx("div",{className:"space-y-1 rounded-control border border-border/60 bg-background p-2",children:z.map(t=>{const u=(l.selectedCardIds||[]).includes(t.cardId);return e.jsxs("label",{className:"flex items-start gap-2 rounded-control px-1.5 py-1 text-[13px] hover:bg-muted/40",children:[e.jsx(f.Checkbox,{checked:u,onCheckedChange:d=>D(b=>b&&{...b,selectedCardIds:d===!0?[...b.selectedCardIds||[],t.cardId]:(b.selectedCardIds||[]).filter(j=>j!==t.cardId)})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium text-foreground",children:t.title}),e.jsx("div",{className:"text-[12px] text-muted-foreground",children:l.control.type==="field_selector"?`${t.fieldChoices.length} compatible group-by fields`:`${t.metricChoices.length} compatible metrics`})]})]},t.cardId)})}),e.jsx(se,{secondary:e.jsx(s.Button,{type:"button",variant:"outline",size:"xs",onClick:()=>D(t=>t&&{...t,step:1,selectedCardIds:[]}),children:"Back"}),primary:e.jsx(s.Button,{type:"button",size:"xs",onClick:()=>D(t=>t&&{...t,step:3}),disabled:!le,children:"Next"})})]}),l.step===2&&!_(l.control.type)&&e.jsx(Ce,{control:l.control,defaultValue:l.defaultValue,availableFieldChoices:$.fields,availableMetricChoices:$.metrics,previewControlDefinitions:ce,previewControlValues:ge,onControlChange:t=>R(()=>t),onLabelChange:t=>R(u=>({...u,label:t})),onDefaultValueChange:te,onBack:()=>D(t=>t&&{...t,step:1}),onNext:fe,nextDisabled:!le}),l.step===3&&_(l.control.type)&&e.jsx(Ce,{control:l.control,defaultValue:l.defaultValue,availableFieldChoices:$.fields,availableMetricChoices:$.metrics,previewControlDefinitions:ce,previewControlValues:ge,onControlChange:t=>R(()=>t),onLabelChange:t=>R(u=>({...u,label:t})),onDefaultValueChange:te,onBack:()=>D(t=>t&&{...t,step:2}),onNext:fe,nextDisabled:!le}),l.step===3&&!_(l.control.type)&&e.jsx(je,{control:l.control,scope:r,createdReference:he,explorerContent:e.jsxs(e.Fragment,{children:["Open the card and use"," ",e.jsx("span",{className:"font-medium text-foreground",children:"Settings → Controls"})," ","to choose what this control changes."]}),sqlDescription:"Reference this control directly in the SQL editor.",onBack:()=>D(t=>t&&{...t,step:2}),onCancel:ie,onDone:xe}),l.step===4&&_(l.control.type)&&e.jsx(je,{control:l.control,scope:r,createdReference:he,summaryDetail:e.jsxs(e.Fragment,{children:["Used by ",(l.selectedCardIds||[]).length," selected card",(l.selectedCardIds||[]).length===1?"":"s"]}),explorerContent:e.jsx(e.Fragment,{children:"Selected cards have been set up to respond to this control automatically."}),sqlDescription:"SQL cards can still reference this control directly in the SQL editor.",onBack:()=>D(t=>t&&{...t,step:3}),onCancel:ie,onDone:xe})]}):null,!l&&a.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-sm text-muted-foreground",children:c}):null,!l&&a.map(t=>{const u=ne(t),d=x==null?void 0:x[t.id],b=s.resolveAuthoringControlDefaultValue({control:t,defaultValues:n}),j=J===t.id,N="inline-flex shrink-0 items-center rounded-[4px] border border-border/60 bg-muted/40 px-1.5 py-0.5 text-[11px] font-medium text-muted-foreground";return e.jsxs("div",{className:"rounded-control border border-border/60",children:[e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2.5",children:[e.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 items-start gap-2 rounded-control text-left focus:outline-none focus-visible:bg-muted/40",onClick:()=>q(y=>y===t.id?null:t.id),children:[j?e.jsx(ee.ChevronDown,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"}):e.jsx(ye.ChevronRight,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx("span",{className:"truncate text-[13px] font-medium text-foreground",children:t.label||"Untitled control"}),e.jsx("span",{className:N,children:s.getFriendlyTypeOption(t.type).label}),e.jsx("span",{className:N,children:s.getPlacementLabel(r,t.placement)})]}),e.jsxs("div",{className:"mt-0.5 text-[12px] text-muted-foreground",children:[s.getControlOptionPreview(t),d!=null&&d.status?` · ${d.status}`:""]})]})]}),e.jsx(s.Button,{type:"button",size:"xs",variant:"ghost",className:"h-7 w-7 shrink-0 p-0 text-muted-foreground",onClick:()=>oe(t.id),"aria-label":`Remove ${t.label}`,children:e.jsx(f.Trash2,{className:"h-3.5 w-3.5"})})]}),j&&e.jsxs("div",{className:"space-y-4 border-t border-border/60 px-3 py-3",children:[e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx(s.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Label"}),e.jsx(s.Input,{size:"xs",value:t.label,placeholder:"Control label",onChange:y=>P(t.id,V=>({...V,label:y.target.value}))})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx(s.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Type"}),e.jsxs(s.Select,{value:t.type,onValueChange:y=>{const V=s.applyControlTypeChange({controls:a,controlId:t.id,nextType:y,defaultValues:n});F(V.controls,V.defaultValues)},children:[e.jsx(s.SelectTrigger,{size:"xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:G(t.type).map(y=>e.jsx(s.SelectItem,{value:y.value,children:y.label},y.value))})]})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx(s.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Show in"}),e.jsxs(s.Select,{value:t.placement||Y,onValueChange:y=>P(t.id,V=>({...V,placement:y})),children:[e.jsx(s.SelectTrigger,{size:"xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:U.map(y=>e.jsx(s.SelectItem,{value:y.value,children:y.label},y.value))})]})]})]}),_(t.type)?e.jsx(f.StructuralParticipantSelector,{type:t.type,participants:s.getEligibleParticipantsForStructuralControl(g||[],t.type).map(y=>({cardId:y.cardId,title:y.title,choiceCount:t.type==="field_selector"?y.fieldChoices.length:y.metricChoices.length})),selectedCardIds:(h==null?void 0:h[t.id])||[],onChange:y=>{const V=A({control:t,nextSelectedCardIds:y}),O=a.map(L=>L.id===t.id?V.nextControl:L);F(O,n,{type:"update",cardBindingsById:V.cardBindingsById})}}):null,e.jsx(f.ControlDefinitionOptionsEditor,{control:t,availableFieldChoices:u.fields,availableMetricChoices:u.metrics,previewControlDefinitions:a,previewControlValues:de,controlLifecycle:"edit",onChange:y=>P(t.id,()=>y)}),t.initialValueStrategy==="saved_default"&&e.jsx(f.ControlDefaultValueEditor,{control:t,value:b,allowNoDefault:!0,allowCardDefault:!0,previewControlDefinitions:a,previewControlValues:de,onChange:y=>{const V=a.map(O=>O.id===t.id?{...O,defaultValue:y}:O);if(t.source.kind==="manual"&&(T.current[t.id]=y),n){const O={...n};y===void 0?delete O[t.id]:O[t.id]=y,F(V,O);return}F(V,void 0)}}),e.jsxs(f.Collapsible,{open:H===t.id,onOpenChange:y=>K(y?t.id:null),children:[e.jsx(f.CollapsibleTrigger,{asChild:!0,children:e.jsxs(s.Button,{type:"button",variant:"ghost",size:"xs",className:"-ml-2 gap-1 text-muted-foreground hover:text-foreground",children:[H===t.id?e.jsx(ee.ChevronDown,{className:"h-3.5 w-3.5"}):e.jsx(ye.ChevronRight,{className:"h-3.5 w-3.5"}),"Advanced"]})}),e.jsxs(f.CollapsibleContent,{className:"space-y-3 pt-2",children:[e.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx(s.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Variable name"}),e.jsx(f.ControlIdInput,{controlId:t.id,onCommit:y=>B(t.id,y)},t.id)]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx(s.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Initial value"}),e.jsxs(s.Select,{value:t.initialValueStrategy,onValueChange:y=>P(t.id,V=>({...V,initialValueStrategy:y})),children:[e.jsx(s.SelectTrigger,{size:"xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:s.INITIAL_VALUE_STRATEGY_OPTIONS.map(y=>e.jsx(s.SelectItem,{value:y.value,children:y.label},y.value))})]})]})]}),e.jsx(f.ControlVisibilitySettings,{control:t,onChange:y=>P(t.id,()=>y)})]})]})]})]},t.id)}),!l&&e.jsxs(s.Button,{type:"button",variant:"outline",size:"xs",onClick:re,children:[e.jsx(f.Plus,{className:"h-3.5 w-3.5"}),"Add control"]})]})}function Ge(r){const{open:a,onOpenChange:o,initialCreateFlowActive:n=!1,dismissMode:i="passive"}=r,c=a!==void 0,[m,x]=C.useState(!1),[p,v]=C.useState(n),g=c?a:m,h=C.useCallback(k=>{!k&&p&&i==="passive"||(c||x(k),k||v(!1),o==null||o(k))},[c,p,i,o]),S=C.useCallback(()=>{c||x(!1),v(!1),o==null||o(!1)},[c,o]);C.useEffect(()=>{g||v(!1)},[g]);const w=C.useCallback(k=>{p&&k.preventDefault()},[p]);return{forceClose:S,handleOpenChange:h,isCreateFlowActive:p,preventPassiveDismissDuringCreate:w,resolvedOpen:g,setIsCreateFlowActive:v}}exports.ControlDefinitionListEditor=He;exports.EditorAcceptButton=Ue;exports.EditorCancelButton=Qe;exports.EditorClearButton=Pe;exports.Library=Ne;exports.Link2=Ee;exports.VisualBadge=Me;exports.VisualSaveAndApplyButton=Re;exports.VisualSaveButton=ze;exports.flushPendingEditorDrafts=we;exports.registerPendingEditorDraftFlusher=Le;exports.useCreateFlowOverlayState=Ge;exports.useEffectiveEditorCardType=pe;exports.useSyncLegacyEditorState=qe;exports.useVisualUtils=ae;
|
|
11
|
+
*/const Ee=ee.createLucideIcon("Link2",[["path",{d:"M9 17H7A5 5 0 0 1 7 7h2",key:"8i5ue5"}],["path",{d:"M15 7h2a5 5 0 1 1 0 10h-2",key:"1b9ql8"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]]);function Ie(r){const[a,o]=C.useState(null),[n,i]=C.useState(null),c=f.useEnsureReactGlobals();return C.useEffect(()=>{if(!r||r.trim()===""){o(null),i(null);return}if(!c)return;(async()=>{try{if(!r.startsWith("http://")&&!r.startsWith("https://"))throw new Error(`Invalid URL format: ${r}`);try{new URL(r)}catch{throw new Error(`Invalid URL: ${r}`)}const p=`${r.endsWith("/")?r:`${r}/`}index.js`;try{if(!(await fetch(p,{method:"HEAD"})).ok)throw new Error(`Module not found at ${p}`)}catch{}const v=await import(p);if(typeof v.useChartStore!="function")throw new Error("useChartStore is not a function");o(()=>v.useChartStore),i(null)}catch(x){const p=x instanceof Error?x.message:"Unknown error";console.error("Failed to load remote chart store:",p),i(p),o(null)}})()},[r,c]),a}function Te(r,a){if(r.length===0)return"";const o=r.find(n=>{var i,c;return((i=n.customCardPreferences)==null?void 0:i.visualType)==="multiple"||!!((c=n.customCardPreferences)!=null&&c.dataInputCardIds)});if(o)return o.id;if(a){const n=r.find(i=>i.id===a);if(n){const i=n.tabTitle;if(i=="All__Header")return r[0].id;if(i&&i.endsWith("__Header")){const m=i.split("__")[0],x=r.find(p=>p.tabTitle===m);return x?x.id:r[0].id}return a}}return r[0].id}const ue=new Set;function Le(r){return ue.add(r),()=>{ue.delete(r)}}function De(){ue.forEach(r=>{r()})}const Ae=r=>{if(!r||!("detailTableBackup"in r))return r;const{detailTableBackup:a,...o}=r;return o};async function ve(r,a,o,n,i="Opening library visual..."){if(!a||!o)throw new Error("Missing auth token or visual ID");const c=["resource-by-id","visual",o],m=n.getQueryData(c);if(m)return console.log("Using cached visual data for:",o),{data:m,fromCache:!0};console.log("Fetching visual data from network for:",o);const x=f.ue.loading(i,{position:"top-center"});try{const p=await fetch(`${r}/management/v1/visuals/${o}`,{headers:{Authorization:`Bearer ${a}`}});if(!p.ok)throw new Error("Failed to load visual");const v=await p.json();return n.setQueryData(c,v),f.ue.dismiss(x),{data:v,fromCache:!1}}catch(p){throw f.ue.dismiss(x),p}}function we(r){if(typeof r=="string")return JSON.parse(r);if(typeof r=="object")return r;throw new Error("Invalid frame object format")}function _e(r,a){var c,m;const o=(r==null?void 0:r.frameObject)??((c=r==null?void 0:r.visual)==null?void 0:c.frameObject);if(!o)return!1;const n=we(o);if(!(n!=null&&n.cards)||n.cards.length===0)return!1;const i=(m=n.cards)==null?void 0:m.find(x=>x.id===n.activeCardId);return i?(f.setupEditorWithCard({...a,frame:n,card:i,visualId:(r==null?void 0:r.id)||n.visualId}),!0):!1}function Be(){const r=s.useEditorStore(n=>{var i;return((i=n.card.customCardPreferences)==null?void 0:i.url)||""}),a=Ie(r);return{getUpdatedFrame:C.useCallback(()=>{var I;De();const{frame:n,card:i,isDevMode:c,isShowingVisual:m,selectedSchemaName:x,selectedDatamodelId:p,selectedDatabaseName:v,selectedTableName:g,selectedConnectionId:h}=s.useEditorStore.getState(),S=i.sql,D=(I=a==null?void 0:a.getState())==null?void 0:I.settings,k=s.buildSavedEditorCard(i,{isDevMode:c,cardSql:S,isShowingVisual:m,selectedSchemaName:x,selectedDatamodelId:p,selectedDatabaseName:v,selectedTableName:g,selectedConnectionId:h,remoteChartSettings:D,stripConfig:Ae}),E=n.cards.map(U=>U.id===i.id?k:U);return{...n,cards:E,activeCardId:Te(E,n.activeCardId)}},[a])}}function ae(){const{authToken:r,tokenProps:a}=f.useSemaphorContext(),o=f.useQueryClient(),n=f.useAddFrameWithFreshSemanticExecutionPayload(),i=f.useSelectedVisual(),{selectVisual:c}=f.useManagementActions(),{setFrame:m,setCard:x,setIsDevMode:p,initializeModeDrafts:v,setActiveTabCardId:g,updateDataSource:h,setQueryResultColumns:S,setSelectedConnectionId:D,setSelectedDatabaseName:k,setSelectedSchemaName:E,setSelectedTableName:I,setSelectedDatamodelId:U,setFilterValues:Y,setInlineFilterValuesMap:H,setApplyFilters:K,clearEditorContext:J}=s.useEditorActions(),{setIsDashboardEditing:q,setIsVisualEditing:l,setSelectedFrameId:w,clearSelectedFrameId:T}=s.useDashboardActions(),M=s.useDashboardStore(A=>A.selectedSheetId),Q=s.useDashboardStore(A=>A.selectedFrameId),W=s.useDashboardStore(A=>A.dashboard),G=s.useDashboardStore(A=>A.filterValues),_=s.useDashboardStore(A=>A.inlineFilterValuesMap),z=f.useVisualById((i==null?void 0:i.id)||"",{enabled:!!(i!=null&&i.id)&&!!(r!=null&&r.accessToken)}),$=C.useCallback(async A=>{try{c(A),T(),J();const{data:F,fromCache:P}=await ve(a.apiServiceUrl,(r==null?void 0:r.accessToken)||"",A.id,o,"Opening library visual...");if(!_e(F,{setFrame:m,setCard:x,setIsDevMode:p,initializeModeDrafts:v,setActiveTabCardId:g,updateDataSource:h,setQueryResultColumns:S,setSelectedConnectionId:D,setSelectedDatabaseName:k,setSelectedSchemaName:E,setSelectedTableName:I,setSelectedDatamodelId:U,setFilterValues:Y,setInlineFilterValuesMap:H,setApplyFilters:K,setIsDashboardEditing:q,setIsVisualEditing:l,dashboard:W,selectedSheetId:M,selectedFrameId:Q,filterValues:G,inlineFilterValuesMap:_}))throw new Error("Failed to setup editor with visual data");return{success:!0,fromCache:P}}catch(F){return console.error("Error editing visual:",F),{success:!1,error:"Failed to load visual for editing"}}},[r==null?void 0:r.accessToken,a.apiServiceUrl,o,c,m,x,q,l,p,v,g,h,S,D,k,E,I,U,Y,H,K,J,T,W,M,Q,G,_]),ne=C.useCallback(async A=>{var P;const F=B=>(f.ue.error(B),{success:!1,error:B});try{if(c(A),!M)return F("No sheet selected. Please select a sheet first.");const{data:B,fromCache:oe}=await ve(a.apiServiceUrl,(r==null?void 0:r.accessToken)||"",A.id,o,"Adding visual to dashboard..."),re=(B==null?void 0:B.frameObject)??((P=B==null?void 0:B.visual)==null?void 0:P.frameObject);if(!re)return F("Visual has no frame data");const R=we(re);if(!(R!=null&&R.cards)||R.cards.length===0)return F("Visual frame is malformed");const te={...f.cloneLinkedFrameWithSourceMapping(R),visualId:A.id};return await n(M,te,"end"),q(!0),w(te.id),{success:!0,fromCache:oe}}catch(B){return console.error("Error adding visual:",B),F(B instanceof Error?B.message:"Failed to add visual to dashboard")}},[r==null?void 0:r.accessToken,a.apiServiceUrl,o,c,M,q,w,n]);return{visual:z.data,isLoading:z.isLoading,isError:z.isError,error:z.error,handleEditLibraryVisual:$,handleAddLibraryVisual:ne,getUpdatedFrame:Be().getUpdatedFrame,refetch:z.refetch}}function qe(){const r=s.useEditorStore(m=>m.card.dataSource),{setSelectedConnectionId:a,setSelectedDatabaseName:o,setSelectedSchemaName:n,setSelectedTableName:i,setSelectedDatamodelId:c}=s.useEditorActions();C.useEffect(()=>{var D;if(!r)return;const{tableName:m,schemaName:x,databaseName:p,connectionId:v}=f.extractTableMetadata(r),g=(D=r.selectedEntities)==null?void 0:D[0],S=(g==null?void 0:g.type)==="model"&&"id"in g?g.id:"";a(v||""),o(p||""),n(x||""),i(m||""),c(S)},[r,a,o,n,i,c])}function pe(){var p,v;const r=s.useEditorStore(g=>g.card),a=s.useEditorStore(g=>g.frame),o=C.useMemo(()=>f.findCustomVisualConfigCard(a,r),[a,r]),{manifest:n}=f.useCustomVisual(((p=o==null?void 0:o.customCardPreferences)==null?void 0:p.url)||""),i=C.useMemo(()=>{var g;return(g=n==null?void 0:n.visuals)==null?void 0:g.find(h=>{var S;return h.name===((S=o==null?void 0:o.customCardPreferences)==null?void 0:S.componentName)})},[n,(v=o==null?void 0:o.customCardPreferences)==null?void 0:v.componentName]),c=f.resolveMultiInputType(o,i),m=C.useMemo(()=>f.getCustomVisualInputCards({frame:a,configCard:o,isMultiInputVisual:c==="multiple"}),[a,o,c]),x=C.useMemo(()=>{const g=m.findIndex(h=>(h==null?void 0:h.id)===r.id);return g<0?-1:f.getSlotIndexForCard(r,g)},[m,r]);return C.useMemo(()=>!o||c!=="multiple"||x<0?r.type:f.getEffectiveCardTypeForSlot(r,x,i==null?void 0:i.slots)??r.type,[o,c,x,r,i==null?void 0:i.slots])}function Me({type:r,isLinked:a,className:o,showLabel:n=!1,showLocal:i=!1}){const c=s.useDashboardStore(E=>E.selectedFrameId),m=f.useManagementStore(E=>E.selectedVisual),x=s.useEditorStore(E=>E.frame);let p;if(r)p=r;else if(a!==void 0)p=a?"linked":"library";else if(!!!(x!=null&&x.visualId||m!=null&&m.id)&&c)p="local";else if(m&&!c)p="library";else if(x!=null&&x.visualId&&c)p="linked";else if(m!=null&&m.id&&c)p="library";else return null;if(p==="local"&&!i)return null;const v={local:"border-slate-200/70 bg-slate-50/80 text-slate-700 shadow-sm hover:bg-slate-100/80 dark:border-slate-700 dark:bg-slate-900/70 dark:text-slate-200 dark:hover:bg-slate-800/80",linked:"border-purple-200/70 bg-gradient-to-r from-purple-50/50 to-purple-100/30 text-purple-900 shadow-sm hover:from-purple-100/60 hover:to-purple-100/50 hover:shadow-md dark:border-purple-800/50 dark:from-purple-950/40 dark:to-purple-900/30 dark:text-purple-100 dark:hover:from-purple-950/60 dark:hover:to-purple-900/50",library:"border-blue-200/70 bg-gradient-to-r from-blue-50/50 to-blue-100/30 text-blue-900 shadow-sm hover:from-blue-100/60 hover:to-blue-100/50 hover:shadow-md dark:border-blue-800/50 dark:from-blue-950/40 dark:to-blue-900/30 dark:text-blue-100 dark:hover:from-blue-950/60 dark:hover:to-blue-900/50"},g={local:"Local to this dashboard: Changes made here only affect this dashboard copy.",linked:"Linked to library: Changes made here update the library visual and all linked instances.",library:"Library visual: Share and reuse this visual across multiple dashboards."},h={local:"border-slate-200 bg-slate-50 text-slate-900 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-100",linked:"border-purple-200 bg-purple-50 text-purple-900 dark:border-purple-800 dark:bg-purple-950 dark:text-purple-100",library:"border-blue-200 bg-blue-50 text-blue-900 dark:border-blue-800 dark:bg-blue-950 dark:text-blue-100"},S={local:"fill-slate-50 dark:fill-slate-900",linked:"fill-purple-50 dark:fill-purple-950",library:"fill-blue-50 dark:fill-blue-950"},D={local:e.jsx("span",{className:"h-2 w-2 rounded-full bg-current/70"}),linked:e.jsx(Ee,{className:"h-3.5 w-3.5"}),library:e.jsx(Ne,{className:"h-3.5 w-3.5"})},k={local:"Local",linked:"Linked",library:"Library"};return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:300,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(f.Badge,{variant:"outline",className:s.cn("cursor-help select-none transition-all",v[p],o),children:[D[p],n&&e.jsx("span",{className:"ml-1 text-xs font-medium leading-none",children:k[p]})]})}),e.jsxs(s.TooltipContent,{side:"bottom",className:s.cn("max-w-xs",h[p]),children:[e.jsx(s.TooltipArrow,{className:S[p]}),e.jsx("p",{children:g[p]})]})]})})}function Oe(r,a){return{...r,sql:"",python:"",config:void 0,customCfg:"",preferences:{},interactionConfig:void 0,linkedInteractionTargetOverrides:void 0,dynamicCardPreferences:void 0,customCardPreferences:a?r.customCardPreferences:void 0,visualizationMode:"builtin",type:a?r.type:"bar"}}function me(r){const a=s.getDynamicFrameSaveIssue(r);return a?(f.ue.error(a),!1):!0}function Ue({className:r,variant:a="outline"}){const o=s.useEditorStore(c=>c.onSave),{getUpdatedFrame:n}=ae();function i(){const c=n();me(c)&&(o==null||o(c))}return e.jsxs(s.Button,{onClick:i,className:r,size:"xs",variant:a,children:[e.jsx(s.Check,{className:"h-3.5 w-3.5"}),"Accept"]})}function ze({className:r,variant:a="default"}){const o=f.useQueryClient(),[n,i]=C.useState(!1),{setIsVisualEditing:c}=s.useDashboardActions(),{getUpdatedFrame:m}=ae(),x=f.useSelectedVisual(),p=s.useEditorStore(h=>h.frame),v=f.useUpdateVisualMutation(),g=()=>{const h=m();if(!me(h))return;const S=(p==null?void 0:p.visualId)||(x==null?void 0:x.id);if(!S){f.ue.error("No visual to save");return}i(!0),v.mutate({visualId:S,data:{frameObject:h}},{onSuccess:()=>{i(!1),f.ue.success("Visual updated successfully"),o.invalidateQueries({queryKey:["resource-by-id","visual",S],exact:!0})},onError:()=>{i(!1),f.ue.error("Failed to update visual")}})};return e.jsx(s.Button,{onClick:g,className:r,size:"xs",variant:a,children:n?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}),"Saving"]}):e.jsxs(e.Fragment,{children:[e.jsx(ke.Save,{className:"h-3.5 w-3.5"}),"Save to Library"]})})}function Re({className:r}){const a=f.useQueryClient(),[o,n]=C.useState(!1),i=f.useSelectedVisual(),c=s.useEditorStore(k=>k.frame),m=s.useDashboardStore(k=>k.selectedSheetId),x=s.useDashboardStore(k=>k.dashboard),{updateFrame:p,setIsVisualEditing:v}=s.useDashboardActions(),{getUpdatedFrame:g}=ae(),h=f.useUpdateVisualMutation(),S=f.useResolveExistingFrameSemanticExecutionPayload(),D=async()=>{if(!m){f.ue.error("No sheet selected");return}const k=(c==null?void 0:c.visualId)||(i==null?void 0:i.id);if(!k){f.ue.error("No visual to update");return}n(!0);try{const E=g();if(!me(E)){n(!1);return}const I={...E,visualId:k},U=s.findDashboardFrameById(x,I.id),Y=await S(I,{previousFrame:U});await h.mutateAsync({visualId:k,data:{frameObject:E}}),p(m,I,{semanticExecutionPayload:Y}),a.invalidateQueries({queryKey:["visuals"]}),a.invalidateQueries({queryKey:["visual",k]}),f.ue.success("Saved to library and applied locally"),setTimeout(()=>{v(!1)},300)}catch(E){console.error("Failed to save and apply:",E),f.ue.error(E instanceof Error?E.message:"Failed to save and apply changes")}finally{n(!1)}};return e.jsx(s.Button,{onClick:D,className:r,size:"xs",variant:"default",disabled:o,children:o?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ke.Save,{className:"h-3.5 w-3.5"}),"Save & Apply"]})})}function Qe({className:r}){const{setTempQueryData:a,setSqlGen:o}=s.useEditorActions(),n=f.useQueryClient(),i=s.useEditorStore(h=>h.tempQueryData),c=s.useEditorStore(h=>h.onClose),m=s.useEditorStore(h=>h.card),x=pe(),p=C.useMemo(()=>x!==m.type?{...m,type:x}:m,[m,x]),{queryKey:v}=f.useEditorCardQuery(p);function g(){if(i){const{queryKey:h,queryData:S}=i;h&&S&&n.setQueryData(h,S)}o({}),c==null||c()}return e.jsxs(s.Button,{onClick:g,className:r,size:"xs",variant:"outline",children:[e.jsx(ee.X,{className:"h-3.5 w-3.5"}),"Close"]})}function Pe({label:r="Clear",variant:a="secondary",className:o}={}){const{setTempQueryData:n}=s.useEditorActions(),i=f.useQueryClient(),c=s.useEditorStore(q=>q.tempQueryData),m=s.useEditorStore(q=>q.card),x=pe(),p=C.useMemo(()=>x!==m.type?{...m,type:x}:m,[m,x]),{queryKey:v}=f.useEditorCardQuery(p),{setCardSql:g,setSqlGen:h,setCardPython:S,setCardCustomCfg:D,setCardPreferences:k,clearQueryConfig:E,setCardConfig:I,setCardType:U,setFrame:Y,setCard:H,setActiveTabCardId:K}=s.useEditorActions();function J(){var W,G,_,z;const q=i.getQueryData(v);c!=null&&c.queryData||n({queryKey:v,queryData:q}),i.setQueryData(v,null),i.removeQueries({queryKey:v,exact:!0}),g(""),h({}),E(),I(void 0),S(""),D(""),k({});const l=s.useEditorStore.getState().frame,w=s.useEditorStore.getState().card,T=f.findCustomVisualConfigCard(l,w),M=((W=T==null?void 0:T.customCardPreferences)==null?void 0:W.visualType)==="multiple"||!!((G=T==null?void 0:T.customCardPreferences)!=null&&G.dataInputCardIds)||(((_=T==null?void 0:T.customCardPreferences)==null?void 0:_.minInputs)||0)>1||(((z=T==null?void 0:T.customCardPreferences)==null?void 0:z.maxInputs)||0)>1,Q=Oe(w,M);Y({...l,cards:l.cards.map($=>$.id===Q.id?Q:$)}),K(Q.id),H(Q),M||U("bar")}return e.jsxs(s.Button,{onClick:J,className:o,size:"xs",variant:a,children:[e.jsx(ee.X,{className:"h-3.5 w-3.5"}),r]})}function Fe(r){const{control:a,onChange:o}=r;return e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx(s.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Label"}),e.jsx(s.Input,{size:"xs",value:a.label,placeholder:"Control label",onChange:n=>o(n.target.value)})]})}function $e(r){const{currentStep:a,labels:o}=r;return e.jsx("div",{className:"sticky top-0 z-10 -mx-1 border-b border-border/60 bg-background/95 px-1 pb-2.5 pt-1 backdrop-blur supports-[backdrop-filter]:bg-background/85",children:e.jsx("div",{className:"flex flex-wrap items-center gap-2 sm:gap-2.5",children:o.map((n,i)=>{const c=i+1,m=c===a,x=c<a;return e.jsxs(C.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:s.cn("flex h-5 w-5 items-center justify-center rounded-full border text-[10px] font-medium tabular-nums",m?"border-foreground bg-foreground text-background":x?"border-foreground/30 bg-foreground/10 text-foreground":"border-border/60 bg-background text-muted-foreground"),children:c}),e.jsx("span",{className:s.cn("text-[12px]",m?"font-medium text-foreground":"text-muted-foreground"),children:n})]}),i<o.length-1?e.jsx("span",{className:"h-px w-4 bg-border/60 sm:w-6","aria-hidden":"true"}):null]},n)})})})}function se(r){const{secondary:a,tertiary:o,primary:n}=r;return e.jsxs("div",{className:"sticky bottom-0 z-10 -mx-1 flex justify-end gap-2 border-t bg-background/95 px-1 pb-1 pt-3 backdrop-blur supports-[backdrop-filter]:bg-background/85",children:[a,o,n]})}function Ye(r){const{control:a,scope:o,detail:n}=r;return e.jsxs("div",{className:"flex items-start gap-2.5 rounded-control border border-border/60 bg-muted/30 px-3 py-2.5",children:[e.jsx(f.CircleCheck,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-foreground"}),e.jsxs("div",{className:"min-w-0 space-y-0.5",children:[e.jsx("div",{className:"text-[13px] font-medium text-foreground",children:a.label}),e.jsxs("div",{className:"text-[12px] text-muted-foreground",children:[s.getFriendlyTypeOption(a.type).label," ·"," ",s.getControlOptionPreview(a)," ·"," ",s.getPlacementLabel(o,a.placement)]}),n?e.jsx("div",{className:"text-[12px] text-muted-foreground",children:n}):null]})]})}function Ce(r){const{control:a,defaultValue:o,availableFieldChoices:n,availableMetricChoices:i,previewControlDefinitions:c,previewControlValues:m,onControlChange:x,onLabelChange:p,onDefaultValueChange:v,onBack:g,onNext:h,nextDisabled:S}=r;return e.jsxs("div",{className:"space-y-3",children:[e.jsx(Fe,{control:a,onChange:p}),e.jsx(f.ControlDefinitionOptionsEditor,{control:a,availableFieldChoices:n,availableMetricChoices:i,previewControlDefinitions:c,previewControlValues:m,controlLifecycle:"create",onChange:x}),e.jsx(f.ControlDefaultValueEditor,{control:a,value:o,onChange:v,allowNoDefault:!0,allowCardDefault:!0,hint:"This is the value viewers will see first.",previewControlDefinitions:c,previewControlValues:m}),e.jsx(se,{secondary:e.jsx(s.Button,{type:"button",variant:"outline",size:"xs",onClick:g,children:"Back"}),primary:e.jsx(s.Button,{type:"button",size:"xs",onClick:h,disabled:S,children:"Next"})})]})}const Ke=new Set(["grain_selector","aggregation_selector","field_selector","metric_selector"]);function Se(r){const{text:a,ariaLabel:o}=r,[n,i]=C.useState(!1);return e.jsxs("button",{type:"button","aria-label":o,onClick:async()=>{try{await navigator.clipboard.writeText(a),i(!0),setTimeout(()=>i(!1),1200)}catch(c){console.error("Failed to copy",c)}},className:"group flex w-full items-center justify-between gap-2 rounded-control bg-muted/40 px-2 py-1 text-left transition-colors hover:bg-muted/60 focus-visible:bg-muted/60 focus-visible:outline-none",children:[e.jsx("code",{className:"min-w-0 truncate font-mono text-[12px] text-foreground",children:a}),e.jsx("span",{className:"shrink-0 text-[11px] text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:n?"Copied":"Click to copy"})]})}function je(r){const{control:a,scope:o,createdReference:n,explorerContent:i,sqlDescription:c,summaryDetail:m,onBack:x,onCancel:p,onDone:v}=r,g=Ke.has(a.type),h=n.match(/\[\[param\.(.+?)\]\]/),S=h?`{{ param('${h[1]}') }}`:"";return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ye,{control:a,scope:o,detail:m}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-[13px] font-medium text-foreground",children:"How cards use this control"}),e.jsxs("div",{className:"divide-y divide-border/60 overflow-hidden rounded-control border border-border/60",children:[g?e.jsxs("div",{className:"space-y-1 px-3 py-2.5",children:[e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Explorer cards"}),e.jsx("div",{className:"text-[12px] text-muted-foreground",children:i})]}):null,e.jsxs("div",{className:"space-y-1.5 px-3 py-2.5",children:[e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"SQL cards"}),e.jsx(Se,{text:n,ariaLabel:"Copy SQL control reference"}),S?e.jsx(Se,{text:S,ariaLabel:"Copy Jinja control reference"}):null,e.jsxs("p",{className:"text-[12px] text-muted-foreground",children:[c," ",e.jsx("a",{href:"https://docs.semaphor.cloud/docs/concepts/template-expressions",target:"_blank",rel:"noreferrer",className:"underline underline-offset-2 hover:text-foreground",children:"Template expressions docs"}),"."]})]})]})]}),e.jsx(se,{secondary:e.jsx(s.Button,{type:"button",variant:"outline",size:"xs",onClick:x,children:"Back"}),tertiary:e.jsx(s.Button,{type:"button",variant:"outline",size:"xs",onClick:p,children:"Cancel"}),primary:e.jsx(s.Button,{type:"button",size:"xs",onClick:v,children:"Done"})})]})}function We(r){const a=s.createBlankControl(r.scope,r.existingControls,r.reservedIds),o=r.type===a.type?{...a,label:s.DEFAULT_LABEL_BY_TYPE[r.type]}:{...s.applyControlTypeChange({controls:[{...a,label:s.DEFAULT_LABEL_BY_TYPE[r.type]}],controlId:a.id,nextType:r.type}).controls[0],label:s.DEFAULT_LABEL_BY_TYPE[r.type]};return{step:2,control:o,defaultValue:s.getDefaultValueForType(o,void 0)}}function He({scope:r,controls:a,reservedControlIds:o,defaultValues:n,onChange:i,emptyMessage:c,initialCreateFlow:m=!1,usageByControlId:x,availableFieldChoices:p,availableMetricChoices:v,structuralParticipants:g,structuralParticipantIdsByControlId:h,card:S,allowedControlTypes:D,onCreateFlowActiveChange:k,onCreateFlowComplete:E}){const I=C.useMemo(()=>new Set(o||[]),[o]),U=s.getPlacementOptionsForScope(r),Y=s.getDefaultPlacement(r),[H,K]=C.useState(null),[J,q]=C.useState(null),[l,w]=C.useState(()=>m?{step:1,control:s.createBlankControl(r,a,Array.from(I))}:null),T=C.useRef({}),M=C.useRef(void 0),Q=C.useRef(m),W=C.useMemo(()=>{const t=s.getFriendlyControlTypeOptions({scope:r,card:S});if(!D)return t;const u=new Set(D);return t.filter(d=>u.has(d.value))},[D,S,r]),G=C.useCallback(t=>{const u=s.getFriendlyControlTypeOptions({scope:r,card:S,includeType:D?void 0:t});if(!D)return u;const d=new Set(D);return u.filter(b=>d.has(b.value))},[D,S,r]),_=C.useCallback(t=>r==="dashboard"&&(t==="field_selector"||t==="metric_selector"),[r]),z=C.useMemo(()=>l?s.getEligibleParticipantsForStructuralControl(g||[],l.control.type):[],[l,g]),$=C.useMemo(()=>{if(!l)return{fields:p||[],metrics:v||[]};if(!_(l.control.type))return{fields:p||[],metrics:v||[]};const t=l.selectedCardIds||[],u=s.getCompatibleStructuralChoiceCatalog({controlType:l.control.type,participants:g||[],selectedCardIds:t});return{fields:l.control.type==="field_selector"?u.choices.map(d=>({option:d,target:u.fieldTargetMap[d.value]})):[],metrics:l.control.type==="metric_selector"?u.choices.map(d=>({option:d,target:u.metricTargetMap[d.value]})):[]}},[p,v,l,_,g]);C.useEffect(()=>{k==null||k(!!l)},[l,k]),C.useEffect(()=>{const t=m&&!Q.current;Q.current=m,t&&(w({step:1,control:s.createBlankControl(r,a,Array.from(I))}),q(null),K(null))},[a,m,I,r]);const ne=t=>{if(!_(t.type))return{fields:p||[],metrics:v||[]};const u=(h==null?void 0:h[t.id])||[];if(u.length===0)return{fields:p||[],metrics:v||[]};const d=s.getCompatibleStructuralChoiceCatalog({controlType:t.type,participants:g||[],selectedCardIds:u});return{fields:t.type==="field_selector"?d.choices.map(b=>({option:b,target:d.fieldTargetMap[b.value]})):[],metrics:t.type==="metric_selector"?d.choices.map(b=>({option:b,target:d.metricTargetMap[b.value]})):[]}},A=t=>{if(!_(t.control.type))return{nextControl:t.control,cardBindingsById:void 0};const u=(h==null?void 0:h[t.control.id])||[],d=s.getCompatibleStructuralChoiceCatalog({controlType:t.control.type,participants:g||[],selectedCardIds:t.nextSelectedCardIds}),b=s.reconcileStructuralControlChoices({control:t.control,choices:d.choices}),j=Object.fromEntries(u.filter(N=>!t.nextSelectedCardIds.includes(N)).map(N=>[N,void 0]));return t.nextSelectedCardIds.length>0&&b.source.kind==="manual"&&b.source.options.length>0&&Object.assign(j,s.buildStructuralControlBindingsForParticipants({control:b,participants:g||[],selectedCardIds:t.nextSelectedCardIds})),{nextControl:b,cardBindingsById:j}},F=C.useCallback((t,u=n,d={type:"update"})=>{const b=t.map(j=>(s.resolveAuthoringControlDefaultValue({control:j,defaultValues:u}),s.syncSqlQueryControlExecutionRequirement(j)));i(b,u,d)},[n,i]),P=(t,u)=>{const d=a.find(L=>L.id===t);let b=a.map(L=>L.id!==t?L:u(L));const j=b.find(L=>L.id===t);let N,y;if(j&&r==="dashboard"&&(j.type==="field_selector"||j.type==="metric_selector")){const L=(h==null?void 0:h[j.id])||[],Z=A({control:j,nextSelectedCardIds:L});b=b.map(X=>X.id===t?Z.nextControl:X),N=Z.cardBindingsById,y=[j.id]}else if(d&&r==="dashboard"&&(d.type==="field_selector"||d.type==="metric_selector")){const L=(h==null?void 0:h[d.id])||[];N=Object.fromEntries(L.map(Z=>[Z,void 0])),y=[d.id]}const V=b.find(L=>L.id===t);let O=n;if(d&&V){const L=s.resolveAuthoringControlDefaultValue({control:d,defaultValues:n});d.source.kind==="manual"&&V.source.kind==="sql_query"&&(T.current[t]=L);const Z=L===void 0&&d.source.kind==="sql_query"&&V.source.kind==="manual"?T.current[t]:L,X=s.getNextEditedControlDefaultValue({previousControl:d,nextControl:V,currentDefaultValue:Z});V.source.kind==="manual"&&(T.current[t]=X),n&&(O={...n},X===void 0?delete O[t]:O[t]=X),b=b.map(be=>be.id===t?{...V,defaultValue:X}:be)}F(b,O,{type:"update",cardBindingsById:N,affectedBindingControlIds:y})},B=(t,u)=>{if(!u.trim())return;const d=f.normalizeDashboardInputVariableName(u);if(d===t||I.has(d)||a.some(N=>N.id===d&&N.id!==t))return;const b=a.map(N=>N.id===t?{...N,id:d}:N);if(!n){F(b,void 0,{type:"rename",oldId:t,newId:d});return}const j={...n};Object.prototype.hasOwnProperty.call(j,t)&&(j[d]=j[t],delete j[t]),F(b,j,{type:"rename",oldId:t,newId:d})},oe=t=>{const u=a.filter(b=>b.id!==t);if(!n){F(u,void 0,{type:"remove",controlId:t});return}const d={...n};delete d[t],F(u,d,{type:"remove",controlId:t})},re=C.useCallback(()=>{M.current=void 0,w({step:1,control:s.createBlankControl(r,a,Array.from(I))}),q(null),K(null)},[a,I,r]),R=t=>{w(u=>u&&(()=>{const d=t(u.control);u.control.source.kind==="manual"&&d.source.kind==="sql_query"&&(M.current=u.defaultValue);const b=u.defaultValue===void 0&&u.control.source.kind==="sql_query"&&d.source.kind==="manual"?M.current:u.defaultValue,j=s.getNextEditedControlDefaultValue({previousControl:u.control,nextControl:d,currentDefaultValue:b});return d.source.kind==="manual"&&(M.current=j),{...u,control:d,defaultValue:j}})())},te=t=>{w(u=>u&&(u.control.source.kind==="manual"&&(M.current=t),{...u,defaultValue:t}))},le=(()=>{if(!l)return!1;if(l.step===2&&_(l.control.type))return(l.selectedCardIds||[]).length>0;if(l.step!==2&&l.step!==3||!l.control.label.trim())return!1;const u=l.control.source.kind==="sql_query"?l.control:s.ensureManualSource(l.control);if(u.source.kind==="manual"&&(s.needsManualOptions(u)&&u.source.options.length===0||u.source.options.some(b=>b.label.trim().length===0||b.value.trim().length===0)))return!1;if(u.source.kind==="sql_query"){const{connectionId:d,sql:b,valueColumn:j}=u.source;return d.trim().length>0&&b.trim().length>0&&j.trim().length>0}return s.hasConcreteDefaultValue(s.getDefaultValueForType(u,l.defaultValue))})(),fe=()=>{var N;if(!l)return;const t=s.ensureManualSource(l.control),u=s.deriveUniqueControlId({label:t.label,fallbackId:t.id,existingControls:a,reservedIds:Array.from(I)}),d={...t,id:u},b=r==="dashboard"&&(d.type==="field_selector"||d.type==="metric_selector")&&((N=l.selectedCardIds)!=null&&N.length)?s.buildStructuralControlBindingsForParticipants({control:d,participants:g||[],selectedCardIds:l.selectedCardIds}):void 0,j=s.getDefaultValueForType(d,l.defaultValue);w({step:r==="dashboard"&&(d.type==="field_selector"||d.type==="metric_selector")?4:3,control:d,defaultValue:j,createdControlId:u,selectedCardIds:l.selectedCardIds,cardBindingsById:b})},ie=C.useCallback(()=>{w(null)},[]),xe=C.useCallback(()=>{if(!(l!=null&&l.createdControlId)){w(null);return}const t=l.control,u=l.createdControlId,d=s.getDefaultValueForType(t,l.defaultValue);if(n){const b={...n};d===void 0?delete b[u]:b[u]=d,F([...a,{...t,defaultValue:d}],b,{type:"add",cardBindingsById:l.cardBindingsById})}else F([...a,{...t,defaultValue:d}],void 0,{type:"add",cardBindingsById:l.cardBindingsById});q(u),w(null),E==null||E()},[a,l,n,F,E]),Ve=l?_(l.control.type)?["Choose type","Select cards","Configure","Finish"]:["Choose type","Configure","Finish"]:[],he=l!=null&&l.createdControlId?`[[param.${l.createdControlId}]]`:l?`[[param.${s.slugifyControlValue(l.control.label)||l.control.id}]]`:"",de=s.buildAuthoringPreviewControlValues({controls:a,defaultValues:n}),ce=l?[...a,l.control]:a,ge=l?s.buildAuthoringPreviewControlValues({controls:ce,defaultValues:n,overrides:[{controlId:l.control.id,value:l.defaultValue}]}):de;return e.jsxs("div",{className:"space-y-4",children:[l?e.jsxs("div",{className:"space-y-4 pb-1",children:[e.jsx($e,{currentStep:l.step,labels:Ve}),l.step===1&&(()=>{const t=new Set(["grain_selector","aggregation_selector","field_selector","metric_selector"]),u=new Set(["date","text"]),d=W.filter(N=>!t.has(N.value)&&!u.has(N.value)),b=W.filter(N=>t.has(N.value)),j=N=>e.jsxs("button",{type:"button",className:"rounded-control border border-border/60 bg-background px-3 py-2.5 text-left transition-colors hover:bg-muted/40 focus-visible:bg-muted/40 focus-visible:outline-none",onClick:()=>w(We({scope:r,existingControls:a,reservedIds:Array.from(I),type:N.value})),children:[e.jsx("div",{className:"text-[13px] font-medium text-foreground",children:N.label}),e.jsx("p",{className:"mt-0.5 text-[12px] text-muted-foreground",children:N.description})]},N.value);return e.jsxs("div",{className:"space-y-4",children:[r==="card"&&(S==null?void 0:S.sql)==null?e.jsx("p",{className:"text-[12px] text-muted-foreground",children:"Explorer cards support displayed metric, group by field, aggregation, and time grain controls here."}):null,d.length>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Input controls"}),e.jsx("div",{className:"grid gap-1.5 sm:grid-cols-2",children:d.map(j)})]}),b.length>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Data-driven controls"}),e.jsx("div",{className:"grid gap-1.5 sm:grid-cols-2",children:b.map(j)})]}),e.jsx(se,{secondary:e.jsx(s.Button,{type:"button",variant:"outline",size:"xs",onClick:ie,children:"Back to controls"})})]})})(),l.step===2&&_(l.control.type)&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(Fe,{control:l.control,onChange:t=>R(u=>({...u,label:t}))}),e.jsx("p",{className:"text-[12px] text-muted-foreground",children:"Choose which cards should respond to this shared control."})]}),z.length===0?e.jsx("div",{className:"rounded-control border border-border/60 bg-muted/30 px-3 py-2.5 text-[12px] text-muted-foreground",children:"No eligible cards are available yet. Add compatible metrics or group-by fields to cards first."}):e.jsx("div",{className:"space-y-1 rounded-control border border-border/60 bg-background p-2",children:z.map(t=>{const u=(l.selectedCardIds||[]).includes(t.cardId);return e.jsxs("label",{className:"flex items-start gap-2 rounded-control px-1.5 py-1 text-[13px] hover:bg-muted/40",children:[e.jsx(f.Checkbox,{checked:u,onCheckedChange:d=>w(b=>b&&{...b,selectedCardIds:d===!0?[...b.selectedCardIds||[],t.cardId]:(b.selectedCardIds||[]).filter(j=>j!==t.cardId)})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium text-foreground",children:t.title}),e.jsx("div",{className:"text-[12px] text-muted-foreground",children:l.control.type==="field_selector"?`${t.fieldChoices.length} compatible group-by fields`:`${t.metricChoices.length} compatible metrics`})]})]},t.cardId)})}),e.jsx(se,{secondary:e.jsx(s.Button,{type:"button",variant:"outline",size:"xs",onClick:()=>w(t=>t&&{...t,step:1,selectedCardIds:[]}),children:"Back"}),primary:e.jsx(s.Button,{type:"button",size:"xs",onClick:()=>w(t=>t&&{...t,step:3}),disabled:!le,children:"Next"})})]}),l.step===2&&!_(l.control.type)&&e.jsx(Ce,{control:l.control,defaultValue:l.defaultValue,availableFieldChoices:$.fields,availableMetricChoices:$.metrics,previewControlDefinitions:ce,previewControlValues:ge,onControlChange:t=>R(()=>t),onLabelChange:t=>R(u=>({...u,label:t})),onDefaultValueChange:te,onBack:()=>w(t=>t&&{...t,step:1}),onNext:fe,nextDisabled:!le}),l.step===3&&_(l.control.type)&&e.jsx(Ce,{control:l.control,defaultValue:l.defaultValue,availableFieldChoices:$.fields,availableMetricChoices:$.metrics,previewControlDefinitions:ce,previewControlValues:ge,onControlChange:t=>R(()=>t),onLabelChange:t=>R(u=>({...u,label:t})),onDefaultValueChange:te,onBack:()=>w(t=>t&&{...t,step:2}),onNext:fe,nextDisabled:!le}),l.step===3&&!_(l.control.type)&&e.jsx(je,{control:l.control,scope:r,createdReference:he,explorerContent:e.jsxs(e.Fragment,{children:["Open the card and use"," ",e.jsx("span",{className:"font-medium text-foreground",children:"Settings → Controls"})," ","to choose what this control changes."]}),sqlDescription:"Reference this control directly in the SQL editor.",onBack:()=>w(t=>t&&{...t,step:2}),onCancel:ie,onDone:xe}),l.step===4&&_(l.control.type)&&e.jsx(je,{control:l.control,scope:r,createdReference:he,summaryDetail:e.jsxs(e.Fragment,{children:["Used by ",(l.selectedCardIds||[]).length," selected card",(l.selectedCardIds||[]).length===1?"":"s"]}),explorerContent:e.jsx(e.Fragment,{children:"Selected cards have been set up to respond to this control automatically."}),sqlDescription:"SQL cards can still reference this control directly in the SQL editor.",onBack:()=>w(t=>t&&{...t,step:3}),onCancel:ie,onDone:xe})]}):null,!l&&a.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-sm text-muted-foreground",children:c}):null,!l&&a.map(t=>{const u=ne(t),d=x==null?void 0:x[t.id],b=s.resolveAuthoringControlDefaultValue({control:t,defaultValues:n}),j=J===t.id,N="inline-flex shrink-0 items-center rounded-[4px] border border-border/60 bg-muted/40 px-1.5 py-0.5 text-[11px] font-medium text-muted-foreground";return e.jsxs("div",{className:"rounded-control border border-border/60",children:[e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2.5",children:[e.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 items-start gap-2 rounded-control text-left focus:outline-none focus-visible:bg-muted/40",onClick:()=>q(y=>y===t.id?null:t.id),children:[j?e.jsx(ee.ChevronDown,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"}):e.jsx(ye.ChevronRight,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx("span",{className:"truncate text-[13px] font-medium text-foreground",children:t.label||"Untitled control"}),e.jsx("span",{className:N,children:s.getFriendlyTypeOption(t.type).label}),e.jsx("span",{className:N,children:s.getPlacementLabel(r,t.placement)})]}),e.jsxs("div",{className:"mt-0.5 text-[12px] text-muted-foreground",children:[s.getControlOptionPreview(t),d!=null&&d.status?` · ${d.status}`:""]})]})]}),e.jsx(s.Button,{type:"button",size:"xs",variant:"ghost",className:"h-7 w-7 shrink-0 p-0 text-muted-foreground",onClick:()=>oe(t.id),"aria-label":`Remove ${t.label}`,children:e.jsx(f.Trash2,{className:"h-3.5 w-3.5"})})]}),j&&e.jsxs("div",{className:"space-y-4 border-t border-border/60 px-3 py-3",children:[e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx(s.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Label"}),e.jsx(s.Input,{size:"xs",value:t.label,placeholder:"Control label",onChange:y=>P(t.id,V=>({...V,label:y.target.value}))})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx(s.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Type"}),e.jsxs(s.Select,{value:t.type,onValueChange:y=>{const V=s.applyControlTypeChange({controls:a,controlId:t.id,nextType:y,defaultValues:n});F(V.controls,V.defaultValues)},children:[e.jsx(s.SelectTrigger,{size:"xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:G(t.type).map(y=>e.jsx(s.SelectItem,{value:y.value,children:y.label},y.value))})]})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx(s.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Show in"}),e.jsxs(s.Select,{value:t.placement||Y,onValueChange:y=>P(t.id,V=>({...V,placement:y})),children:[e.jsx(s.SelectTrigger,{size:"xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:U.map(y=>e.jsx(s.SelectItem,{value:y.value,children:y.label},y.value))})]})]})]}),_(t.type)?e.jsx(f.StructuralParticipantSelector,{type:t.type,participants:s.getEligibleParticipantsForStructuralControl(g||[],t.type).map(y=>({cardId:y.cardId,title:y.title,choiceCount:t.type==="field_selector"?y.fieldChoices.length:y.metricChoices.length})),selectedCardIds:(h==null?void 0:h[t.id])||[],onChange:y=>{const V=A({control:t,nextSelectedCardIds:y}),O=a.map(L=>L.id===t.id?V.nextControl:L);F(O,n,{type:"update",cardBindingsById:V.cardBindingsById})}}):null,e.jsx(f.ControlDefinitionOptionsEditor,{control:t,availableFieldChoices:u.fields,availableMetricChoices:u.metrics,previewControlDefinitions:a,previewControlValues:de,controlLifecycle:"edit",onChange:y=>P(t.id,()=>y)}),t.initialValueStrategy==="saved_default"&&e.jsx(f.ControlDefaultValueEditor,{control:t,value:b,allowNoDefault:!0,allowCardDefault:!0,previewControlDefinitions:a,previewControlValues:de,onChange:y=>{const V=a.map(O=>O.id===t.id?{...O,defaultValue:y}:O);if(t.source.kind==="manual"&&(T.current[t.id]=y),n){const O={...n};y===void 0?delete O[t.id]:O[t.id]=y,F(V,O);return}F(V,void 0)}}),e.jsxs(f.Collapsible,{open:H===t.id,onOpenChange:y=>K(y?t.id:null),children:[e.jsx(f.CollapsibleTrigger,{asChild:!0,children:e.jsxs(s.Button,{type:"button",variant:"ghost",size:"xs",className:"-ml-2 gap-1 text-muted-foreground hover:text-foreground",children:[H===t.id?e.jsx(ee.ChevronDown,{className:"h-3.5 w-3.5"}):e.jsx(ye.ChevronRight,{className:"h-3.5 w-3.5"}),"Advanced"]})}),e.jsxs(f.CollapsibleContent,{className:"space-y-3 pt-2",children:[e.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx(s.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Variable name"}),e.jsx(f.ControlIdInput,{controlId:t.id,onCommit:y=>B(t.id,y)},t.id)]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx(s.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Initial value"}),e.jsxs(s.Select,{value:t.initialValueStrategy,onValueChange:y=>P(t.id,V=>({...V,initialValueStrategy:y})),children:[e.jsx(s.SelectTrigger,{size:"xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:s.INITIAL_VALUE_STRATEGY_OPTIONS.map(y=>e.jsx(s.SelectItem,{value:y.value,children:y.label},y.value))})]})]})]}),e.jsx(f.ControlVisibilitySettings,{control:t,onChange:y=>P(t.id,()=>y)})]})]})]})]},t.id)}),!l&&e.jsxs(s.Button,{type:"button",variant:"outline",size:"xs",onClick:re,children:[e.jsx(f.Plus,{className:"h-3.5 w-3.5"}),"Add control"]})]})}function Ge(r){const{open:a,onOpenChange:o,initialCreateFlowActive:n=!1,dismissMode:i="passive"}=r,c=a!==void 0,[m,x]=C.useState(!1),[p,v]=C.useState(n),g=c?a:m,h=C.useCallback(k=>{!k&&p&&i==="passive"||(c||x(k),k||v(!1),o==null||o(k))},[c,p,i,o]),S=C.useCallback(()=>{c||x(!1),v(!1),o==null||o(!1)},[c,o]);C.useEffect(()=>{g||v(!1)},[g]);const D=C.useCallback(k=>{p&&k.preventDefault()},[p]);return{forceClose:S,handleOpenChange:h,isCreateFlowActive:p,preventPassiveDismissDuringCreate:D,resolvedOpen:g,setIsCreateFlowActive:v}}exports.ControlDefinitionListEditor=He;exports.EditorAcceptButton=Ue;exports.EditorCancelButton=Qe;exports.EditorClearButton=Pe;exports.Library=Ne;exports.Link2=Ee;exports.VisualBadge=Me;exports.VisualSaveAndApplyButton=Re;exports.VisualSaveButton=ze;exports.flushPendingEditorDrafts=De;exports.registerPendingEditorDraftFlusher=Le;exports.useCreateFlowOverlayState=Ge;exports.useEffectiveEditorCardType=pe;exports.useSyncLegacyEditorState=qe;exports.useVisualUtils=ae;
|