@salsita-ai/sdk 0.50.0-develop.2772b27a05 → 0.50.0-develop.2be7811d51
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/application-spec/generate-application/code/project-scaffolding.js +2 -2
- package/dist/application-spec/generate-application/code/templates/index.d.ts +1 -0
- package/dist/application-spec/generate-application/code/templates/index.js +1 -1
- package/dist/application-spec/generate-application/code/templates/skills/agents-md.js +1 -1
- package/dist/application-spec/generate-application/code/templates/skills/phoenix-cli-skill.js +1 -1
- package/dist/application-spec/generate-application/code/templates/skills/phoenix-review-skill.js +1 -1
- package/dist/application-spec/generate-application/code/templates/skills/phoenix-variants-skill.d.ts +1 -0
- package/dist/application-spec/generate-application/code/templates/skills/phoenix-variants-skill.js +6 -0
- package/dist/application-spec/generate-application/code/templates/skills/sdk-content.d.ts +12 -2
- package/dist/application-spec/generate-application/code/templates/skills/sdk-content.js +3 -3
- package/dist/application-spec/parse-application-files/spec/sections/assistant/assistant-schema.js +1 -1
- package/dist/configurator/application-runtime/extensions/systems/assistant-system/assistant-system.d.ts +17 -3
- package/dist/configurator/application-runtime/extensions/systems/assistant-system/assistant-system.js +1 -1
- package/dist/configurator/application-runtime/extensions/systems/assistant-system/change-recorder.d.ts +85 -0
- package/dist/configurator/application-runtime/extensions/systems/assistant-system/change-recorder.js +1 -0
- package/dist/configurator/application-runtime/extensions/systems/assistant-system/graphql-tools.d.ts +8 -3
- package/dist/configurator/application-runtime/extensions/systems/assistant-system/graphql-tools.js +1 -1
- package/dist/configurator/application-runtime/extensions/systems/graphql-system/entity-meta.d.ts +4 -0
- package/dist/configurator/application-runtime/extensions/systems/graphql-system/entity-meta.js +1 -1
- package/dist/configurator/application-runtime/extensions/systems/graphql-system/graphql-system.d.ts +16 -1
- package/dist/configurator/application-runtime/extensions/systems/graphql-system/graphql-system.js +1 -1
- package/dist/configurator/application-runtime/extensions/systems/graphql-system/side-effects.d.ts +9 -0
- package/dist/configurator/application-runtime/extensions/systems/graphql-system/side-effects.js +1 -0
- package/dist/docs/index.json +1 -1
- package/dist/docs/other-features/side-effects.mdx +26 -0
- package/dist/docs/phoenix/phoenix-cli.mdx +79 -0
- package/dist/docs/phoenix/project-structure.mdx +3 -2
- package/dist/domain/components/updates.d.ts +16 -0
- package/dist/domain/domain-context/store-system/store-system.js +1 -1
- package/dist/editor/Editor.js +1 -1
- package/dist/editor/graphql/GraphQLPanel.js +1 -1
- package/dist/editor/variants/VariantAnswerFooter.d.ts +17 -0
- package/dist/editor/variants/VariantAnswerFooter.js +1 -0
- package/dist/editor/variants/VariantPreviewHandler.d.ts +6 -0
- package/dist/editor/variants/VariantPreviewHandler.js +1 -0
- package/dist/editor/variants/variant-preview-styles.d.ts +49 -0
- package/dist/editor/variants/variant-preview-styles.js +1 -0
- package/dist/phoenix/application-spec/application-spec-builder.js +1 -1
- package/dist/phoenix/application-spec/generate-assistant-prompt.d.ts +3 -2
- package/dist/phoenix/application-spec/generate-assistant-prompt.js +1 -1
- package/dist/phoenix/cli.js +1 -1
- package/dist/phoenix/commands/dev.js +5 -5
- package/dist/phoenix/commands/index.d.ts +1 -0
- package/dist/phoenix/commands/index.js +1 -1
- package/dist/phoenix/commands/story-dev.js +2 -2
- package/dist/phoenix/commands/variants.d.ts +35 -0
- package/dist/phoenix/commands/variants.js +1 -0
- package/dist/phoenix/editor-server/commands-router.d.ts +68 -1
- package/dist/phoenix/editor-server/commands-router.js +1 -1
- package/dist/phoenix/editor-server/editor-router.d.ts +65 -0
- package/dist/phoenix/editor-server/editor-server.d.ts +3 -3
- package/dist/phoenix/editor-server/editor-server.js +1 -1
- package/dist/phoenix/editor-server/protocol.d.ts +1 -0
- package/dist/phoenix/editor-server/spec-router.js +1 -1
- package/dist/phoenix/editor-server/trpc.d.ts +3 -0
- package/dist/phoenix/services/application-spec-project-watcher.d.ts +13 -2
- package/dist/phoenix/services/application-spec-project-watcher.js +3 -3
- package/dist/phoenix/services/index.d.ts +4 -0
- package/dist/phoenix/services/index.js +1 -1
- package/dist/phoenix/services/phoenix-application.d.ts +21 -0
- package/dist/phoenix/services/phoenix-application.js +1 -0
- package/dist/phoenix/services/phoenix-store.d.ts +48 -0
- package/dist/phoenix/services/phoenix-store.js +1 -0
- package/dist/phoenix/services/phx-variant-previews-plugin.d.ts +9 -0
- package/dist/phoenix/services/phx-variant-previews-plugin.js +1 -0
- package/dist/phoenix/services/variant-file-session.d.ts +36 -0
- package/dist/phoenix/services/variant-file-session.js +1 -0
- package/dist/phoenix/services/variant-preview-service.d.ts +80 -0
- package/dist/phoenix/services/variant-preview-service.js +1 -0
- package/dist/phoenix/services/vite-config.js +1 -1
- package/package.json +3 -3
package/dist/configurator/application-runtime/extensions/systems/graphql-system/entity-meta.d.ts
CHANGED
|
@@ -47,12 +47,14 @@ export declare const createEntityMeta: (source: EntityMetaSource, context: Entit
|
|
|
47
47
|
root: null;
|
|
48
48
|
changedEntities: never[];
|
|
49
49
|
deletedEntityIds: never[];
|
|
50
|
+
sideEffects: never[];
|
|
50
51
|
errors: readonly DryRunError[];
|
|
51
52
|
} | {
|
|
52
53
|
ok: boolean;
|
|
53
54
|
root: unknown;
|
|
54
55
|
changedEntities: {}[];
|
|
55
56
|
deletedEntityIds: DomainEntityId<string>[];
|
|
57
|
+
sideEffects: readonly string[];
|
|
56
58
|
errors: never[];
|
|
57
59
|
} | null;
|
|
58
60
|
}[];
|
|
@@ -71,12 +73,14 @@ export declare const createEntityMeta: (source: EntityMetaSource, context: Entit
|
|
|
71
73
|
root: null;
|
|
72
74
|
changedEntities: never[];
|
|
73
75
|
deletedEntityIds: never[];
|
|
76
|
+
sideEffects: never[];
|
|
74
77
|
errors: readonly DryRunError[];
|
|
75
78
|
} | {
|
|
76
79
|
ok: boolean;
|
|
77
80
|
root: unknown;
|
|
78
81
|
changedEntities: {}[];
|
|
79
82
|
deletedEntityIds: DomainEntityId<string>[];
|
|
83
|
+
sideEffects: readonly string[];
|
|
80
84
|
errors: never[];
|
|
81
85
|
} | null;
|
|
82
86
|
}[];
|
package/dist/configurator/application-runtime/extensions/systems/graphql-system/entity-meta.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{findAssistantFieldOptions as e,findAssistantRecipeGroups as t,modifyEntityUpdateTag as i,prepareAssistantRecipeUpdates as r,readAssistantFieldOptions as n,readAssistantRecipeGroup as s,systemUpdateFactory as a}from"#package/domain";let
|
|
1
|
+
import{findAssistantFieldOptions as e,findAssistantRecipeGroups as t,modifyEntityUpdateTag as i,prepareAssistantRecipeUpdates as r,readAssistantFieldOptions as n,readAssistantRecipeGroup as s,systemUpdateFactory as a}from"#package/domain";import{readSideEffects as o}from"./side-effects.js";let d=e=>({ok:!1,root:null,changedEntities:[],deletedEntityIds:[],sideEffects:[],errors:e}),l=(e,{state:t},{recipes:i,prepareStateEmission:r,find$Entity:n})=>{let{validity:s,state:a,updates:l}=r(e,t,"committed");if(s.valid){let e=new Map(t.entities.map(e=>[e.id,e])),r=new Set(a.entities.map(e=>e.id));return{ok:!0,root:n(a.rootEntityId,a),changedEntities:a.entities.filter(t=>e.get(t.id)!==t).flatMap(e=>n(e.id,a)??[]),deletedEntityIds:t.entities.map(e=>e.id).filter(e=>!r.has(e)),sideEffects:o(l,i.resolveLocalizable),errors:[]}}return d("uncaught"===s.severity?[{type:"uncaught",entityId:null,message:s.error.message}]:s.entityViolations.filter(({violation:e})=>e.severity===s.severity).map(({entityId:e,violation:t})=>({type:t.type,entityId:e,message:void 0===t.message?null:i.resolveLocalizable(t.message)})))};export const createEntityMeta=(o,c)=>{let p=e=>()=>t(c.manifest,e,o.entity.type).flatMap(t=>{let i=s(e,t,o.entity.id,o.state,c.recipes);return i?[((e,t,i)=>{let{group:n,label:s,description:a,recipes:o}=e,{resolveLocalizable:c}=i.recipes;return{groupId:n.groupId,name:void 0===s?n.instanceName:c(s),description:n.description??(void 0===a?null:c(a)),recipes:o.map(n=>((e,t,i,n)=>{let{key:s,item:a}=e,{resolveLocalizable:o}=n.recipes;return{key:s,name:o(a.title),description:void 0===a.description?null:o(a.description),imageUrl:void 0===a.thumbnailUrl?null:o(a.thumbnailUrl),dryRun:()=>t.group.dryRuns?((e,t,i,n)=>{let{updates:s,error:a}=((e,t,{entity:i,state:n},{recipes:s})=>{try{return{updates:r(e,t,i.id,n,s),error:void 0}}catch(e){if("child"===t.target.kind)throw e;return{updates:void 0,error:e instanceof Error?e.message:String(e)}}})(e,t,i,n);return void 0===s?d([{type:"uncaught",entityId:null,message:a}]):l(s,i,n)})(e,t,i,n):null}})(n,e,t,i))}})(i,o,c)]:[]});return{...Object.fromEntries(e(c.manifest,o.entity.type).map(e=>[e.edgeName,()=>n(e,o.entity.id,o.state,c.recipes)?.map(t=>({...t,dryRun:()=>e.dryRuns?(({field:e},{value:t},r,n)=>{let{entity:s}=r,o=Object.entries(Object.entries(n.manifest.writableFields??{}).find(([e])=>e===s.type)?.[1]??{}).find(([t])=>t===e)?.[1];if(void 0===o)throw Error(`The options of "${e}" on "${s.id}" cannot be dry-run: the schema lists them, but the configurator has no writable field "${e}" on ${s.type}. Regenerate the application so the schema matches the configurator.`);let c=r.state.entities.find(e=>e.id===s.id),p={[o]:t},u=c?n.validateEntity({...c,...p}):{success:!0};return u.success?l([a.DomainEntityModification({entityId:s.id,stateDelta:p,updateTag:i})],r,n):d([{type:"uncaught",entityId:s.id,message:`Writing ${JSON.stringify(t)} to "${e}" would make "${s.id}" an invalid ${s.type}: ${u.errors.join("; ")}.${e===o?"":` The message names the stored property: ${e} is stored as ${o}.`} The option comes from the configurator and cannot be corrected from here, so do not write it.`}])})(e,t,o,c):null}))??null])),childRecipes:p("child"),replaceRecipes:p("replace")}};
|
package/dist/configurator/application-runtime/extensions/systems/graphql-system/graphql-system.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type ExecutionResult } from 'graphql';
|
|
2
|
+
import { type Localizable } from '@salsita-ai/common/utils';
|
|
2
3
|
import { type $DomainEntity, type DomainContextSelectors, type DomainEntity, type DomainServicesSelectors, type DomainState, type SpecSelectors, type StateUpdateEmission } from '#package/domain';
|
|
3
4
|
/** One single-operation GraphQL document with its own variables, as executed by {@link GraphQLSystem}. */
|
|
4
5
|
export interface GraphQLOperation {
|
|
@@ -26,13 +27,22 @@ export interface PreparedOperation {
|
|
|
26
27
|
/**
|
|
27
28
|
* What {@link GraphQLSystem.execute} returns: the results of the operations as prepared from the
|
|
28
29
|
* committed state, whether their changes were committed as one undo step, and, when the operations
|
|
29
|
-
* succeeded but their changes were not committed, the reason addressed to the caller.
|
|
30
|
+
* succeeded but their changes were not committed, the reason addressed to the caller. `sideEffects`
|
|
31
|
+
* describes the prepared changes whether or not they were committed, so a caller can weigh a held
|
|
32
|
+
* commit before the user approves it.
|
|
30
33
|
*/
|
|
31
34
|
export interface GraphQLExecution {
|
|
32
35
|
readonly results: readonly ExecutionResult[];
|
|
33
36
|
readonly committed: boolean;
|
|
34
37
|
readonly message?: string;
|
|
38
|
+
/** What the configurator did, or would do, beyond what the operations asked for, in applied order. */
|
|
39
|
+
readonly sideEffects: readonly string[];
|
|
35
40
|
}
|
|
41
|
+
/**
|
|
42
|
+
* Resolves a localizable value, or each item of a list of them, to a string in the current locale.
|
|
43
|
+
* `null` and values that are not localizable pass through, so the schema's nullability decides.
|
|
44
|
+
*/
|
|
45
|
+
export declare const localize: (value: unknown, resolveLocalizable: (message: Localizable) => string) => unknown;
|
|
36
46
|
/**
|
|
37
47
|
* Executes GraphQL operations against the schema generated from the application spec `assistant`
|
|
38
48
|
* manifest, resolving it against the committed domain state. Agent-independent: the assistant's
|
|
@@ -75,6 +85,11 @@ export declare class GraphQLSystem {
|
|
|
75
85
|
* "not run" error instead.
|
|
76
86
|
*/
|
|
77
87
|
prepare: (originalState: AnyDomainState, operations: readonly GraphQLOperation[]) => Promise<readonly PreparedOperation[]>;
|
|
88
|
+
/**
|
|
89
|
+
* The side effects of prepared operations: the hints of every update of their emissions, as the
|
|
90
|
+
* agent is told them, in applied order.
|
|
91
|
+
*/
|
|
92
|
+
readSideEffects: (prepared: readonly PreparedOperation[]) => readonly string[];
|
|
78
93
|
private readonly _prepareAndCommit;
|
|
79
94
|
/**
|
|
80
95
|
* Prepares the operations from the committed state and commits their changes as one emission,
|
package/dist/configurator/application-runtime/extensions/systems/graphql-system/graphql-system.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{GraphQLError as e,buildSchema as t,defaultFieldResolver as i,getNamedType as o,graphql as a,validateSchema as n}from"graphql";import{assertExistence as r,createSelector as s,isMessageDescriptor as l,isMultilingualString as c}from"@salsita-ai/common/utils";import{DomainEntityIdSchema as h,findAssistantMutation as d}from"#package/domain";import{createEntityMeta as m}from"./entity-meta.js";let
|
|
1
|
+
import{GraphQLError as e,buildSchema as t,defaultFieldResolver as i,getNamedType as o,graphql as a,validateSchema as n}from"graphql";import{assertExistence as r,createSelector as s,isMessageDescriptor as l,isMultilingualString as c}from"@salsita-ai/common/utils";import{DomainEntityIdSchema as h,findAssistantMutation as d}from"#package/domain";import{createEntityMeta as m}from"./entity-meta.js";import{readSideEffects as p}from"./side-effects.js";let f={errors:[new e('No assistant manifest in the application spec. The GraphQL schema is generated from the "assistant" section. Add an "assistant" section to a spec file to expose a schema.')]},u={errors:[new e("The configuration is not loaded yet, so there is no state to query. Run the query again once the configurator has finished loading.")]},y=new RegExp(h.pattern),g=e=>"object"==typeof e&&null!==e&&"type"in e&&"string"==typeof e.type&&"id"in e&&"string"==typeof e.id,v=(e,t)=>"object"==typeof e&&null!==e?Reflect.get(e,t):void 0,S=e=>e instanceof Error?e.message:String(e),x=e=>/[.!?]$/.test(e)?e:`${e}.`,_=e=>"object"==typeof e&&null!==e&&Object.getPrototypeOf(e)===Object.prototype,w=(e,t)=>{let i=_(e)?e._raw:void 0;if(g(i))return i;if(!Array.isArray(e)&&!_(e))return e;if(t.has(e))throw Error("The value contains itself. Return ids or copies of the values instead of objects that reference each other.");let o=new Set([...t,e]);return Array.isArray(e)?e.map(e=>w(e,o)):Object.fromEntries(Object.entries(e).map(([e,t])=>[e,w(t,o)]))};export const localize=(e,t)=>Array.isArray(e)?e.map(e=>localize(e,t)):"string"==typeof e||l(e)||c(e)?t(e):e;let E=t=>new e(`The GraphQL schema generated from the "assistant" manifest is invalid: ${x(t)} Regenerate the application so the schema is rebuilt from the current spec.`),$=e=>(e.errors?.length??0)>0,b=t=>({errors:[new e(`Not run: operation ${t+1} failed, so the operations after it were skipped and no change of the list takes effect. Fix the failing operation and send the whole list again.`)]});export class GraphQLSystem{_context;_selectSchema=s([s.leaf(e=>e)],e=>{try{let i=t(e),o=n(i);return o.length>0?E(o.map(e=>e.message).join(" ")):i}catch(e){return E(S(e))}});_selectFieldResolver=s([s.leaf(e=>e)],t=>(a,n,r,s)=>{if(s.parentType===s.schema.getQueryType())return i(a,n,r,s);if(s.parentType===s.schema.getMutationType())return this._resolveMutation(s.fieldName,String(s.path.key),n,r);if(!g(a))return i(a,n,r,s);if("meta"===s.fieldName){let e;return m({entity:a,state:("object"==typeof(e=v(a,"_state"))&&null!==e&&"entities"in e&&"rootEntityId"in e?e:void 0)??r.state},{manifest:r.manifest,recipes:this._recipeContext(),prepareStateEmission:(e,t,i)=>this._context.domainContextSelectors.getStoreSystem().prepareStateEmission(e,t,i),find$Entity:(e,t)=>this._find$Entity(e,t),validateEntity:e=>this._context.domainContextSelectors.getDomain().validateEntity(e)})}let{source:l,localized:c}=t[s.parentType.name]?.[s.fieldName]??{source:s.fieldName},h=((t,i)=>{try{return v(t,i)}catch(o){throw new e(`Expression "${i}" failed on ${g(t)?t.id:"an entity"}: ${x(S(o))} The expression threw while the query read it; fix the expression or the configuration state it reads.`,{originalError:o instanceof Error?o:void 0})}})(a,l);return c?localize(h,this._context.domainServicesSelectors.getResolveLocalizable()):l.startsWith("$")&&"JSON"===o(s.returnType).name?((t,i,o)=>{try{return w(o,new Set)}catch(o){throw new e(`Expression "${i}" returned a value that is not plain serializable data on ${g(t)?t.id:"an entity"}: ${x(S(o))} A JSON field can only return data that serializes to JSON.`,{originalError:o instanceof Error?o:void 0})}})(a,l,h):h});constructor(e){this._context=e}_get$Entity=(e,t)=>this._context.domainContextSelectors.getDomain().get$Entity(e,t);_find$Entity=(e,t)=>this._context.domainContextSelectors.getDomain().getEntity(e,t)?this._get$Entity(e,t):null;_recipeContext=()=>({componentReader:this._context.domainContextSelectors.getComponentReader(),recipeCooker:this._context.domainContextSelectors.getRecipeCookerSystem(),resolveLocalizable:this._context.domainServicesSelectors.getResolveLocalizable()});_rootValue={root:(e,{state:t})=>this._get$Entity(t.rootEntityId,t),entities:({ids:t},{state:i})=>{if(null==t)return i.entities.map(e=>this._get$Entity(e.id,i));var o=i.rootEntityId;let a=t.filter(e=>!y.test(e));if(a.length>0)throw new e(`${a.map(e=>`"${e}"`).join(", ")} ${1===a.length?"is not an entity id":"are not entity ids"}. Entity ids have the form "<Type>-<number>", e.g. "${o}". Use ids as returned by the "id" field.`);return t.map(e=>y.test(e)?this._find$Entity(e,i):null)},selectedEntity:(e,{state:t})=>this._find$Entity(this._context.domainContextSelectors.getNavigationSystem().getActiveSelectionState(t),t),navigation:(e,{state:t})=>{let i=this._context.domainContextSelectors.getNavigationSystem();return{navigationState:i.getActiveNavigationState(t),viewState:i.getActiveViewState(t),toolState:i.getActiveToolState(t)}}};_resolveType=e=>g(e)?e.type:void 0;initialize=()=>{};_resolveMutation=(t,i,o,a)=>{if(void 0!==a.failedMutationField)throw new e(`Not run: the earlier field "${a.failedMutationField}" of this operation failed, so "${i}" was skipped and no change of the operation takes effect. Fix the failing field and send the operation again.`);try{return this._runMutation(t,o,a)}catch(e){throw a.failedMutationField=i,e}};_runMutation=(t,i,o)=>{let a=d(t,o.manifest);if(!a)throw new e(`The schema declares the mutation "${t}", but the configurator has no implementation for it. Regenerate the application so the schema matches the configurator.`);let n=o.state,r=a.implementation(i,n,{manifest:o.manifest,action:this._context.domainContextSelectors.getActionSystem().createContext(n),resolveLocalizable:this._context.domainServicesSelectors.getResolveLocalizable()});if(r.updates.length>0){let i=this._context.domainContextSelectors.getStoreSystem().prepareStateEmission(r.updates,n,"committed");if(!i.validity.valid)throw new e(`The changes of "${t}" were not applied, because the resulting configuration is invalid: ${(e=>{if("uncaught"===e.severity)return`validating it threw: ${x(S(e.error))}`;let t=[...new Set(e.entityViolations.filter(({violation:t})=>t.severity===e.severity).map(({entityId:e})=>e))];return`it has ${e.severity} violations on ${t.join(", ")}.`})(i.validity)} Change the request so the configuration stays valid.`);o.emissions.push(i),o.state=i.state}return r.readResult({previousState:n,state:o.state})};_setup=()=>{let t=this._context.specSelectors.getAssistant();if(!t)return{ready:!1,result:f};let i=this._selectSchema(t.sdl);return i instanceof e?{ready:!1,result:{errors:[i]}}:{ready:!0,assistant:t,schema:i,fieldResolver:this._selectFieldResolver(t.fields)}};prepare=async(e,t)=>{let i,o=this._setup();if(!o.ready)return t.map(()=>({result:o.result,emissions:[]}));let n={manifest:o.assistant,state:e,emissions:[],failedMutationField:void 0},r=[];for(let[e,s]of t.entries())if(void 0===i){let t=n.emissions.length;n.failedMutationField=void 0;let l=await a({schema:o.schema,source:s.document,rootValue:this._rootValue,contextValue:n,variableValues:s.variables,operationName:s.operationName,fieldResolver:o.fieldResolver,typeResolver:this._resolveType});r.push({result:l,emissions:n.emissions.slice(t)}),$(l)&&(i=e)}else r.push({result:b(i),emissions:[]});return r};readSideEffects=e=>{let t=this._context.domainServicesSelectors.getResolveLocalizable();return e.flatMap(({emissions:e})=>e.flatMap(e=>p(e.updates,t)))};_prepareAndCommit=async e=>{let t,i,o,a=this._context.domainContextSelectors.getStoreSystem(),n=await this.prepare(a.stateSlices.committed.value.state,e),s=n.map(({result:e})=>e),l=this.readSideEffects(n),c=n.flatMap(e=>e.emissions);return s.some($)||0===c.length?{results:s,sideEffects:l,outcome:"none"}:{results:s,sideEffects:l,outcome:a.commitPrepared((t=r(c[0]),i=r(c[c.length-1]),o=c.some(e=>void 0!==e.transformationLog),{kind:"committed",previousState:t.previousState,state:i.state,updates:c.flatMap(e=>e.updates),validity:i.validity,transformationLog:o?c.flatMap(e=>e.transformationLog??[]):void 0}))}};execute=async e=>{if(!this._context.domainContextSelectors.getStoreSystem().isInitialized)return{results:e.map(()=>u),committed:!1,sideEffects:[]};let t=await this._prepareAndCommit(e),{results:i,sideEffects:o,outcome:a}="conflict"===t.outcome?await this._prepareAndCommit(e):t;return"committed"===a?{results:i,committed:!0,sideEffects:o}:"held"===a?{results:i,committed:!1,message:"The changes were not committed yet: the application held them, usually to ask the user for approval. They may still be applied once the user approves, and the next turn shows whether they were. Do not send the operations again.",sideEffects:o}:"conflict"===a?{results:i,committed:!1,message:"The changes were not committed, because the configuration changed while they were being applied. The results describe a state that was discarded. Query the current configuration and send the operations again if they still make sense.",sideEffects:o}:{results:i,committed:!1,sideEffects:o}}}
|
package/dist/configurator/application-runtime/extensions/systems/graphql-system/side-effects.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { Localizable } from '@salsita-ai/common/utils';
|
|
2
|
+
import type { DataUpdate, DomainEntity } from '#package/domain';
|
|
3
|
+
/**
|
|
4
|
+
* What the updates of an emission tell the assistant agent the configurator did beyond what was
|
|
5
|
+
* asked, in applied order with duplicates kept, the way the user gets them as snackbars. An update's
|
|
6
|
+
* `agentHint` replaces its user-facing `hint` for the agent, `null` keeps the update from the agent,
|
|
7
|
+
* and an update with neither says nothing. Empty text counts as none, as it does for the snackbar.
|
|
8
|
+
*/
|
|
9
|
+
export declare const readSideEffects: (updates: ReadonlyArray<DataUpdate<DomainEntity<string>, DomainEntity<string>>>, resolveLocalizable: (message: Localizable) => string) => readonly string[];
|
package/dist/configurator/application-runtime/extensions/systems/graphql-system/side-effects.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const readSideEffects=(e,t)=>e.flatMap(({hint:e,agentHint:a})=>null===a?[]:void 0!==a?a?[a]:[]:e?[t(e)]:[]);
|
package/dist/docs/index.json
CHANGED
|
@@ -102,6 +102,32 @@ configuratorBuilder
|
|
|
102
102
|
.buildConfig()
|
|
103
103
|
```
|
|
104
104
|
|
|
105
|
+
### Hints and the AI assistant
|
|
106
|
+
|
|
107
|
+
In a configurator with the AI assistant, the assistant is told the same hints: they arrive as
|
|
108
|
+
`sideEffects` with the result of its changes and in the dry-runs of recipes and options, so it can
|
|
109
|
+
tell the user what else happened. The hints also explain what the user changed between two messages:
|
|
110
|
+
every message carries a change record of the configuration, and each of its lines ends with the hint
|
|
111
|
+
of the last update that touched it, or with the `updateTag` when the update has none. Set `agentHint`
|
|
112
|
+
beside `hint` when the assistant needs different wording, for example with ids or values a snackbar
|
|
113
|
+
would not show:
|
|
114
|
+
|
|
115
|
+
```ts
|
|
116
|
+
phx.frontend.updates.DomainEntityModification({
|
|
117
|
+
entityId: oldPlate.id,
|
|
118
|
+
stateDelta: { finish: validMaterial.finish },
|
|
119
|
+
updateTag: 'fix.finish',
|
|
120
|
+
hint: msg`Material finish was adjusted`,
|
|
121
|
+
agentHint: `The finish of ${oldPlate.id} was changed to ${validMaterial.finish}, the only one this material comes in.`,
|
|
122
|
+
})
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
- `agentHint` is a plain string, never shown to the user and not localized.
|
|
126
|
+
- `agentHint: null` keeps the wording from the assistant while the user still gets the `hint`: the
|
|
127
|
+
update is left out of `sideEffects`, and the change record explains its line by the `updateTag`. It
|
|
128
|
+
does not hide the change itself, which the assistant can always read from the configuration.
|
|
129
|
+
- `agentHint` without a `hint` tells only the assistant.
|
|
130
|
+
|
|
105
131
|
## Example
|
|
106
132
|
|
|
107
133
|
Here you can see the live example!
|
|
@@ -491,6 +491,85 @@ phoenix screenshot -o preview.png -w 1920 --height 1080
|
|
|
491
491
|
| `--height` | `1080` | Image height in pixels |
|
|
492
492
|
| `--format` / `-f` | `png` | Image format (`png` or `jpeg`) |
|
|
493
493
|
|
|
494
|
+
### `phoenix variants`
|
|
495
|
+
|
|
496
|
+
Show several options over the configurator and wait for your pick. It is built for coding agents: when a decision is a matter of taste, such as the edge of a table top, how glossy a finish is or where a control sits, the agent writes one file per option, you choose in the browser, and the command hands your answer back to the agent.
|
|
497
|
+
|
|
498
|
+
```bash
|
|
499
|
+
phoenix variants .phoenix/variants/table-edge --title 'Which edge suits the table?' --description 'Only the edge of the top differs.'
|
|
500
|
+
```
|
|
501
|
+
|
|
502
|
+
Every `<id>.variant.js` script or `<id>.html` page in the folder is one option, shown in file-name order. Each script edits frontend project files on top of the same captured baseline. Original is always the first choice and restores that baseline. Switching options removes the previous option's edits and applies the selected script; the editor dialog has any number of choices on the left and your already loaded configurator on the right.
|
|
503
|
+
|
|
504
|
+
```js
|
|
505
|
+
// .phoenix/variants/brand/blue.variant.js
|
|
506
|
+
export const title = 'Blue brand'
|
|
507
|
+
export const description = 'A blue primary colour with the current layout.'
|
|
508
|
+
|
|
509
|
+
export default ({ read, write, remove }) => {
|
|
510
|
+
const file = 'src/handlers/theme.ts'
|
|
511
|
+
write(file, read(file).replace("main: '#E93335'", "main: '#2364aa'"))
|
|
512
|
+
}
|
|
513
|
+
```
|
|
514
|
+
|
|
515
|
+
`read(path)` always reads the baseline. `write(path, contents)` replaces or creates a file; `remove(path)` deletes it. Scripts run in the browser and collect edits; Phoenix validates and writes the batch locally. Supported files are YAML under `spec/` outside `spec/admin/`, and TypeScript under `src/components`, `transformers`, `handlers`, `elements` and `_`-prefixed shared folders. Expressions, actions and invariants also run on the server, so a script cannot edit them.
|
|
516
|
+
|
|
517
|
+
For standalone UI or branding proposals, write self-contained HTML files. Each page renders in its own iframe when selected; its `<title>` names the option and `<meta name="description" content="...">` describes it. HTML and scripts may share a set if their file names give distinct option ids.
|
|
518
|
+
|
|
519
|
+
```html
|
|
520
|
+
<!-- .phoenix/variants/brand/blue.html -->
|
|
521
|
+
<!doctype html>
|
|
522
|
+
<title>Blue studio</title>
|
|
523
|
+
<meta name="description" content="A calm blue identity with generous spacing." />
|
|
524
|
+
<style>
|
|
525
|
+
body {
|
|
526
|
+
margin: 0;
|
|
527
|
+
padding: 40px;
|
|
528
|
+
background: #f0f5fa;
|
|
529
|
+
color: #163b66;
|
|
530
|
+
font-family: sans-serif;
|
|
531
|
+
}
|
|
532
|
+
</style>
|
|
533
|
+
<h1>Made for your everyday.</h1>
|
|
534
|
+
<button>Design your table</button>
|
|
535
|
+
```
|
|
536
|
+
|
|
537
|
+
Scripts run once per selection. The completed file batch calls the existing rebuild queue directly, without a separate file-change event stream or a watcher that reapplies the option.
|
|
538
|
+
|
|
539
|
+
Use script options for controls, layout, brand, lights, visual effects, materials, positions, components, elements and transformers. Changes to the model, schemas, data or deployment settings are rejected before any files are written. Environment files, webhooks, their shared implementation dependencies, dependencies and uploaded assets cannot be overridden. Files connected through symbolic links are also excluded, so restoring the baseline preserves the original files. No server preparation or webhook rebuild runs for a variant transaction.
|
|
540
|
+
|
|
541
|
+
Picking a script keeps its exact implementation in the project. Picking an HTML page returns the selected proposal for the agent to implement; the page itself changes no project source files. Choosing Original keeps the captured baseline. Users finish by confirming Original or another option. Escape stays available to the configurator, and clicking the backdrop leaves the comparison open. The agent can use `--close` to restore the baseline source files without giving an answer. Phoenix records recovery information on disk and restores interrupted previews at the next `phoenix dev` start. It never overwrites a file edited outside the preview: switching options over such an edit is refused, and when the comparison ends, or is restored at the next start, that file is left as it is with a warning in the dev log while the others are restored. Other source changes made while a comparison is open are rebuilt once it ends.
|
|
542
|
+
|
|
543
|
+
Answers are held for four seconds with Undo and Send now.
|
|
544
|
+
|
|
545
|
+
The command prints the outcome as JSON. After `chosen` it removes the folder:
|
|
546
|
+
|
|
547
|
+
| `status` | Meaning |
|
|
548
|
+
| --------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
549
|
+
| `chosen` | An option was picked: `choice` is its id, or `null` for Original; `label` is its name. |
|
|
550
|
+
| `waiting` | The wait ran out. The preview stays open: the same command attaches to it again, and an answer given in between is returned by the next run. |
|
|
551
|
+
| `closed` | The preview was closed without an answer, by `--close` or by another set of options taking its place. The folder is kept. |
|
|
552
|
+
|
|
553
|
+
| Flag | Default | Description |
|
|
554
|
+
| ---------------------- | ----------------------------- | --------------------------------------------------------- |
|
|
555
|
+
| `--title` / `-t` | `Which option do you prefer?` | Question shown above the options |
|
|
556
|
+
| `--description` / `-d` | — | A line saying what differs between the options |
|
|
557
|
+
| `--timeout` | `540` | Seconds to wait for the answer |
|
|
558
|
+
| `--keep` | `false` | Keep the folder after the answer |
|
|
559
|
+
| `--close` | `false` | Close the open preview without an answer; needs no folder |
|
|
560
|
+
| `--port` / `-p` | `3020` | Editor WebSocket port |
|
|
561
|
+
|
|
562
|
+
Known limits:
|
|
563
|
+
|
|
564
|
+
- Variant transactions start rebuilding immediately, bypassing the normal file-watcher debounce. Hot reload still needs to parse and apply the updated implementation. There is no wait for UI or scene loading to settle; allow a visible transition to finish before judging or choosing.
|
|
565
|
+
- Only one option is displayed at a time; simultaneous comparison is not supported.
|
|
566
|
+
- For script options and Original, the dialog moves the existing configurator into the preview and returns it on close, preserving the loaded scene, camera and UI state. Opening the dialog starts no second application or initial loading screen. Configuration interactions still change the current configuration; restoring source files does not undo them.
|
|
567
|
+
- Custom scripts are trusted project code. Their file API stages edits; scripts must not make network requests or other side effects.
|
|
568
|
+
- Binary assets, CSS files, locale catalog changes, dependency changes and edits requiring a full application restart are unsupported.
|
|
569
|
+
- Storybook `story-dev` has no variant previews. A project on the legacy pipeline has no variant previews; the command says so and exits.
|
|
570
|
+
|
|
571
|
+
Generated projects carry the `phoenix-variants` agent skill, which tells coding agents when to offer options, how to write each kind and what to do with your answer.
|
|
572
|
+
|
|
494
573
|
## SDK Development
|
|
495
574
|
|
|
496
575
|
### `phoenix link`
|
|
@@ -189,7 +189,7 @@ type CustomMaterial = Phx['AdminModel']['CustomMaterial']
|
|
|
189
189
|
|
|
190
190
|
### DO NOT EDIT (Fully Auto-Generated)
|
|
191
191
|
|
|
192
|
-
- **Everything in `.phoenix/`** - Completely regenerated on each build
|
|
192
|
+
- **Everything in `.phoenix/`** - Completely regenerated on each build. The one exception is `.phoenix/variants/`, where a coding agent writes the option files for `phoenix variants`; a rebuild keeps it
|
|
193
193
|
- `tsconfig.json`, `eslint.config.js`, `prettier.config.js`, `.prettierignore`
|
|
194
194
|
- `.linguirc`, `.nvmrc`
|
|
195
195
|
- `src/locales/**/*.ts` - Compiled from `.po` catalogs
|
|
@@ -198,7 +198,7 @@ type CustomMaterial = Phx['AdminModel']['CustomMaterial']
|
|
|
198
198
|
|
|
199
199
|
### Agent Guidance
|
|
200
200
|
|
|
201
|
-
Coding agents (Claude Code, Codex, Cursor) read `AGENTS.md` and the Phoenix agent skills. `AGENTS.md` is written once with the build commands, the do-not-edit list and a pointer to the skills; after that it is yours. The `phoenix`, `phoenix-cli`, `phoenix-feedback` and `phoenix-review` skills carry the SDK conventions, CLI tooling and review checklist, and the `phoenix-create-configurator` skill walks the agent from your product documents and assets to a reviewed configurator in five stages. Phoenix keeps them in step with the installed SDK, including the reference files inside a skill folder. During the internal beta, a project created from a canary build of the SDK gets one more section in the `phoenix` skill: once per conversation the agent checks for a newer canary and, after telling you, updates the project's SDK and runs `phoenix sync`. Other skill folders are never touched.
|
|
201
|
+
Coding agents (Claude Code, Codex, Cursor) read `AGENTS.md` and the Phoenix agent skills. `AGENTS.md` is written once with the build commands, the do-not-edit list and a pointer to the skills; after that it is yours. The `phoenix`, `phoenix-cli`, `phoenix-feedback` and `phoenix-review` skills carry the SDK conventions, CLI tooling and review checklist, and the `phoenix-create-configurator` skill walks the agent from your product documents and assets to a reviewed configurator in five stages. The `phoenix-variants` skill has the agent show you several options over the dev preview when a decision is a matter of taste, and build the one you pick. Phoenix keeps them in step with the installed SDK, including the reference files inside a skill folder. During the internal beta, a project created from a canary build of the SDK gets one more section in the `phoenix` skill: once per conversation the agent checks for a newer canary and, after telling you, updates the project's SDK and runs `phoenix sync`. Other skill folders are never touched.
|
|
202
202
|
|
|
203
203
|
Projects created by earlier SDK versions had this guidance in `CLAUDE.md`, `.cursor/rules/phoenix.mdc` and `commands/review.md`. Sync removes the SDK block from the first two, keeps your own text around it, deletes a file that held nothing else, and deletes the review commands; use the `phoenix-review` skill instead of `/review`.
|
|
204
204
|
|
|
@@ -316,6 +316,7 @@ project-root/
|
|
|
316
316
|
│ │ └── builders.ts
|
|
317
317
|
│ ├── .swc/ # SWC transpiled sources
|
|
318
318
|
│ ├── .lingui/ # Compiled i18n catalogs
|
|
319
|
+
│ ├── variants/ # Option files of `phoenix variants`, written by coding agents
|
|
319
320
|
│ ├── dist/ # Build output
|
|
320
321
|
│ │ ├── frontend/ # Frontend bundles
|
|
321
322
|
│ │ └── webhooks/ # Webhook bundles
|
|
@@ -7,6 +7,8 @@ export interface ComponentModification<COMPONENT_TYPE extends SystemComponentTyp
|
|
|
7
7
|
entityId: EntityId;
|
|
8
8
|
updateTag: string;
|
|
9
9
|
hint?: Localizable;
|
|
10
|
+
/** What the assistant agent is told about this update instead of `hint`; `null` keeps the wording from it, and its change record then explains the change by `updateTag`. Never shown to the user. */
|
|
11
|
+
agentHint?: string | null;
|
|
10
12
|
componentInstance: ComponentInstance<COMPONENT_TYPE>;
|
|
11
13
|
writableState: WritableStateOfComponent<COMPONENT_TYPE>;
|
|
12
14
|
metadata?: Record<string, unknown>;
|
|
@@ -17,6 +19,8 @@ export interface EphemeralRecordModification<COMPONENT_TYPE extends SystemCompon
|
|
|
17
19
|
entityId: EntityId;
|
|
18
20
|
updateTag: string;
|
|
19
21
|
hint?: Localizable;
|
|
22
|
+
/** What the assistant agent is told about this update instead of `hint`; `null` keeps the wording from it, and its change record then explains the change by `updateTag`. Never shown to the user. */
|
|
23
|
+
agentHint?: string | null;
|
|
20
24
|
componentInstance: ComponentInstance<COMPONENT_TYPE>;
|
|
21
25
|
writableState: WritableStateOfComponent<COMPONENT_TYPE>;
|
|
22
26
|
}
|
|
@@ -25,6 +29,8 @@ export interface EphemeralRecordCreation<COMPONENT_TYPE extends SystemComponentT
|
|
|
25
29
|
entityId: EntityId;
|
|
26
30
|
updateTag: string;
|
|
27
31
|
hint?: Localizable;
|
|
32
|
+
/** What the assistant agent is told about this update instead of `hint`; `null` keeps the wording from it, and its change record then explains the change by `updateTag`. Never shown to the user. */
|
|
33
|
+
agentHint?: string | null;
|
|
28
34
|
componentInstance: ComponentInstance<COMPONENT_TYPE>;
|
|
29
35
|
initialState: StateOfComponent<COMPONENT_TYPE>;
|
|
30
36
|
}
|
|
@@ -34,6 +40,8 @@ export interface EphemeralRecordDeletion<COMPONENT_TYPE extends SystemComponentT
|
|
|
34
40
|
componentInstance: ComponentInstance<COMPONENT_TYPE>;
|
|
35
41
|
updateTag: string;
|
|
36
42
|
hint?: Localizable;
|
|
43
|
+
/** What the assistant agent is told about this update instead of `hint`; `null` keeps the wording from it, and its change record then explains the change by `updateTag`. Never shown to the user. */
|
|
44
|
+
agentHint?: string | null;
|
|
37
45
|
}
|
|
38
46
|
export type DomainEntityStateDelta<ENTITY extends DomainEntity<string>> = Partial<Omit<ENTITY, 'id' | 'type'>>;
|
|
39
47
|
export interface DomainEntityModification<ENTITY extends DomainEntity<string> = DomainEntity<string>> {
|
|
@@ -41,6 +49,8 @@ export interface DomainEntityModification<ENTITY extends DomainEntity<string> =
|
|
|
41
49
|
entityId: ENTITY['id'];
|
|
42
50
|
updateTag: string;
|
|
43
51
|
hint?: Localizable;
|
|
52
|
+
/** What the assistant agent is told about this update instead of `hint`; `null` keeps the wording from it, and its change record then explains the change by `updateTag`. Never shown to the user. */
|
|
53
|
+
agentHint?: string | null;
|
|
44
54
|
stateDelta: DomainEntityStateDelta<ENTITY>;
|
|
45
55
|
origin?: ComponentModification<SystemComponentTypeConstraint>;
|
|
46
56
|
}
|
|
@@ -55,6 +65,8 @@ export interface DomainEntityCreation<ENTITY extends DomainEntity<string>, PAREN
|
|
|
55
65
|
collection?: string;
|
|
56
66
|
parentId: PARENT['id'];
|
|
57
67
|
hint?: Localizable;
|
|
68
|
+
/** What the assistant agent is told about this update instead of `hint`; `null` keeps the wording from it, and its change record then explains the change by `updateTag`. Never shown to the user. */
|
|
69
|
+
agentHint?: string | null;
|
|
58
70
|
}
|
|
59
71
|
export interface DomainEntityReplacement<ENTITY extends DomainEntity<string>> {
|
|
60
72
|
kind: 'replaceDomainEntity';
|
|
@@ -63,12 +75,16 @@ export interface DomainEntityReplacement<ENTITY extends DomainEntity<string>> {
|
|
|
63
75
|
updateTag: string;
|
|
64
76
|
keepChildren: boolean;
|
|
65
77
|
hint?: Localizable;
|
|
78
|
+
/** What the assistant agent is told about this update instead of `hint`; `null` keeps the wording from it, and its change record then explains the change by `updateTag`. Never shown to the user. */
|
|
79
|
+
agentHint?: string | null;
|
|
66
80
|
}
|
|
67
81
|
export interface EntityDeletion<ENTITY extends DomainEntity<string>> {
|
|
68
82
|
kind: 'deleteEntity';
|
|
69
83
|
entityId: EntityId<ENTITY>;
|
|
70
84
|
updateTag: string;
|
|
71
85
|
hint?: Localizable;
|
|
86
|
+
/** What the assistant agent is told about this update instead of `hint`; `null` keeps the wording from it, and its change record then explains the change by `updateTag`. Never shown to the user. */
|
|
87
|
+
agentHint?: string | null;
|
|
72
88
|
}
|
|
73
89
|
export type DataUpdate<ENTITY extends DomainEntity<string>, PARENT extends DomainEntity<string>> = EphemeralRecordModification | EphemeralRecordCreation | EphemeralRecordDeletion | DomainEntityModification<ENTITY> | DomainEntityCreation<ENTITY, PARENT> | DomainEntityReplacement<ENTITY> | EntityDeletion<ENTITY>;
|
|
74
90
|
export type StateUpdate<ENTITY extends DomainEntity<string>, PARENT extends DomainEntity<string>> = ComponentModification<SystemComponentTypeConstraint> | DataUpdate<ENTITY, PARENT>;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{CompositeKeyMap as e,assertExistence as t,isEqualArray as i}from"@salsita-ai/common/utils";import{dragStateComponent as o}from"../../components/drag-state-component.js";import{hoverStateComponent as r}from"../../components/hover-state-component.js";import{selectionStateComponent as s}from"../../components/selection-state-component.js";import{getComponentSystemFilterState as n}from"../../components/system-component-filter.js";import{systemVirtualEntityId as a}from"../../components/system-virtual-entity.js";import{systemUpdateFactory as d}from"../../components/updates.js";import{isSystemViewportStateComponentSnapshot as m}from"../../components/viewport-state-component.js";import{isEqualComponentInstance as l}from"../../core/component.js";import{domainEntityTypeFromId as c,isVirtualEntityId as p}from"../../core/model.js";import{projectedEntitiesComponent as h}from"../../system-components/index.js";import{cloneEvalCache as f,createEvalCacheToken as v,getEvalCache as g,setEvalCache as u}from"../../utils/eval-cache.js";import{createCascadeDeletesTransformer as y}from"../relation-transformers/cascade-deletes.js";import{createCascadeRefPruningTransformer as S}from"../relation-transformers/cascade-ref-pruning.js";import{applyUpdates as I}from"./apply-updates.js";import{LifecycleStateSlice as _}from"./lifecycle-state-slice.js";import{mergeReconciliationsUpdates as x,reconcileProjectedEntities as T}from"./reconcile-projected-entities.js";let E={uninitializedError:"StoreSystem is not initialized."},k=v({clone:e=>e}),w=class InvalidInitialStateError extends Error{emission;childError;constructor(e,t,i){let o="";"uncaught"===e.validity.severity&&(o=`: ${e.validity.error.message}`),("fatal"===e.validity.severity||"fixable"===e.validity.severity)&&(o=`: ${e.validity.entityViolations.map(e=>{let i=e.violation.message;return null!=i?t(i):e.violation.type}).join(", ")}`),super(`Initial state is not valid! Severity: ${e.validity.severity}, Cause: ${o}`),this.emission=e,this.childError=i,this.name="InvalidInitialStateError"}},b=(e,t)=>{try{return e()}catch(e){throw t(e),e}};export class StoreSystem{_context;stateSlices;get isInitialized(){return this.committed.isInitialized}_onBeforeCommitHooks=[];committed=new _(E);potentiallyInvalid=new _(E);rendered=new _(E);stagedUpdates=void 0;transformToDataUpdates=(e,t)=>{let i=!1,o=e.map(e=>"modifyComponent"===e.kind?(i=!0,this.componentModificationToDataUpdate(e,t)):e);return i?o:e};createInitialTransformPipe=()=>[{transformer:this.transformToDataUpdates,priority:1/0,registrationToken:{},name:"TransformToDataUpdates"}];transformPipe=this.createInitialTransformPipe();_cascadeDeletesTransformer=(...e)=>(this._cascadeDeletesTransformerMemo??=y(this._context.selectors.getCompositionProjections()))(...e);_cascadeDeletesTransformerMemo;_refPruningTransformer=(...e)=>(this._refPruningTransformerMemo??=S(this._context.selectors.getComponentReader()))(...e);_refPruningTransformerMemo;_deselectOnDeleteTransformer=(e,t)=>{let i=new Set(e.filter(e=>"deleteEntity"===e.kind).map(e=>e.entityId));if(0===i.size)return e;let o=n(t).selectedEntityId;return o&&i.has(o)?[...e,d.EphemeralRecordModification({componentInstance:{entityId:a,componentType:s},updateTag:"AutoDeselectRemovedProjectedEntity",writableState:{selectedEntityId:t.rootEntityId}})]:e};constructor(e){this._context=e,this.stateSlices={committed:this.committed.observable,rendered:this.rendered.observable,potentiallyInvalid:this.potentiallyInvalid.observable}}_validateState=e=>this._context.selectors.getValidationProjections().validateState(e);initialize=()=>{let e=this._context.selectors.getInitialDomainState();this.stagedUpdates=void 0;let t=this._validateState(e),i={kind:"reset",state:e,validity:t,tag:void 0,transformationLog:void 0},o=i;if(!o.validity.valid&&"fatal"===o.validity.severity||"fixable"===o.validity.severity){this._context.domainServicesSelectors.getLogger().debug("Trying to fix initial emission:",o);let e=o.state,{transformedUpdates:t,transformationLog:i}=this.applyTransformers([],e,"committed"),r=I(this.transformToDataUpdates(t,e),e);f(e,r),o={kind:"reset",state:r,validity:this._validateState(r),tag:"fixed",transformationLog:i}}if(!o.validity.valid){if(this._context.domainServicesSelectors.getLogger().error("Invalid initial emission:",{initialEmission:i,fixedEmission:o}),"uncaught"===o.validity.severity)throw new w(o,this._context.domainServicesSelectors.getResolveLocalizable(),o.validity.error??void 0);throw new w(o,this._context.domainServicesSelectors.getResolveLocalizable())}this.committed.next(o),this.rendered.next(o),this.potentiallyInvalid.next(o)};registerTransformer(e,i,o){let r={};return((e,i,o)=>{let r=0;for(;r<e.length&&0>=o(t(e[r]),i);)r++;e.splice(r,0,i)})(this.transformPipe,{registrationToken:r,transformer:i,priority:e,name:o},(e,t)=>e.priority===t.priority?0:e.priority<t.priority?-1:1),()=>{let e=this.transformPipe.findIndex(e=>e.registrationToken===r);-1!==e&&this.transformPipe.splice(e,1)}}onBeforeCommit(e){return this._onBeforeCommitHooks.push(e),()=>{this._onBeforeCommitHooks=this._onBeforeCommitHooks.filter(t=>t!==e)}}componentModificationToDataUpdate=(e,t)=>{let i=e.entityId;if(!p(i)){let t=this._context.selectors.getComponentReaderIndexes().opticMap.get(c(i))?.get(e.componentInstance.componentType)?.get(e.componentInstance.instanceName);if(t?.kind==="simple"){let o=t.write(e.writableState);return{kind:"modifyDomainEntity",entityId:i,updateTag:e.updateTag,stateDelta:o,hint:e.hint,origin:e}}}let o=t.ephemeralRecords.find(t=>l(t.componentInstance,e.componentInstance));if(o)return{kind:"modifyEphemeralRecord",entityId:e.entityId,updateTag:e.updateTag,componentInstance:o.componentInstance,writableState:e.writableState,hint:e.hint};throw Error(`Component ${e.componentInstance.componentType.name} is not attached on entity #${e.entityId}`)};getNewState=(e,t)=>{let i=I(this.transformToDataUpdates(e,t),t);return f(this.rendered.isInitialized?this.rendered.value.state:t,i),i};applyTransformers(e,t,i){let o=this._context.environmentSelectors.getEnvironmentIsDev()?[]:void 0;return{transformedUpdates:this.transformPipe.reduce((e,{transformer:r,name:s})=>{let n,a=o?[]:void 0,d=a?(e,t,i)=>{n=e,a.push({phase:e,message:t,data:i})}:void 0,m=b(()=>r(e,t,i,d),r=>{this._context.domainServicesSelectors.getLogger().error("Error while applying transformer!",{name:s,updates:e,previousState:t,kind:i,transformationLog:o},r instanceof Error?r:Error(String(r)))});return a&&o&&o.push({name:s,status:n??(m===e?"no-event":"apply"),entries:a,updatesIn:e,updatesOut:m}),m},e),transformationLog:o}}_updateProjectedEntities(e,t,o){if(!e.validity.valid)return e;let r=this._context.selectors.getComponentReader().readManyComponents({componentTypes:[h]},e.state),s=g(e.previousState,k);if(s&&i(s,r))return e;let n=0,a=e,d=[];for(;a.validity.valid;){n++;let i=T(a.state.entities,r,t);if(0===i.length)break;if(n>10)throw Error(`Maximum number of reconciliation rounds reached: 10. Projected entities seem to be recursively depending on themselves.
|
|
1
|
+
import{CompositeKeyMap as e,assertExistence as t,isEqualArray as i}from"@salsita-ai/common/utils";import{dragStateComponent as o}from"../../components/drag-state-component.js";import{hoverStateComponent as r}from"../../components/hover-state-component.js";import{selectionStateComponent as s}from"../../components/selection-state-component.js";import{getComponentSystemFilterState as n}from"../../components/system-component-filter.js";import{systemVirtualEntityId as a}from"../../components/system-virtual-entity.js";import{systemUpdateFactory as d}from"../../components/updates.js";import{isSystemViewportStateComponentSnapshot as m}from"../../components/viewport-state-component.js";import{isEqualComponentInstance as l}from"../../core/component.js";import{domainEntityTypeFromId as c,isVirtualEntityId as p}from"../../core/model.js";import{projectedEntitiesComponent as h}from"../../system-components/index.js";import{cloneEvalCache as f,createEvalCacheToken as v,getEvalCache as g,setEvalCache as u}from"../../utils/eval-cache.js";import{createCascadeDeletesTransformer as y}from"../relation-transformers/cascade-deletes.js";import{createCascadeRefPruningTransformer as S}from"../relation-transformers/cascade-ref-pruning.js";import{applyUpdates as I}from"./apply-updates.js";import{LifecycleStateSlice as _}from"./lifecycle-state-slice.js";import{mergeReconciliationsUpdates as x,reconcileProjectedEntities as T}from"./reconcile-projected-entities.js";let E={uninitializedError:"StoreSystem is not initialized."},k=v({clone:e=>e}),w=class InvalidInitialStateError extends Error{emission;childError;constructor(e,t,i){let o="";"uncaught"===e.validity.severity&&(o=`: ${e.validity.error.message}`),("fatal"===e.validity.severity||"fixable"===e.validity.severity)&&(o=`: ${e.validity.entityViolations.map(e=>{let i=e.violation.message;return null!=i?t(i):e.violation.type}).join(", ")}`),super(`Initial state is not valid! Severity: ${e.validity.severity}, Cause: ${o}`),this.emission=e,this.childError=i,this.name="InvalidInitialStateError"}},b=(e,t)=>{try{return e()}catch(e){throw t(e),e}};export class StoreSystem{_context;stateSlices;get isInitialized(){return this.committed.isInitialized}_onBeforeCommitHooks=[];committed=new _(E);potentiallyInvalid=new _(E);rendered=new _(E);stagedUpdates=void 0;transformToDataUpdates=(e,t)=>{let i=!1,o=e.map(e=>"modifyComponent"===e.kind?(i=!0,this.componentModificationToDataUpdate(e,t)):e);return i?o:e};createInitialTransformPipe=()=>[{transformer:this.transformToDataUpdates,priority:1/0,registrationToken:{},name:"TransformToDataUpdates"}];transformPipe=this.createInitialTransformPipe();_cascadeDeletesTransformer=(...e)=>(this._cascadeDeletesTransformerMemo??=y(this._context.selectors.getCompositionProjections()))(...e);_cascadeDeletesTransformerMemo;_refPruningTransformer=(...e)=>(this._refPruningTransformerMemo??=S(this._context.selectors.getComponentReader()))(...e);_refPruningTransformerMemo;_deselectOnDeleteTransformer=(e,t)=>{let i=new Set(e.filter(e=>"deleteEntity"===e.kind).map(e=>e.entityId));if(0===i.size)return e;let o=n(t).selectedEntityId;return o&&i.has(o)?[...e,d.EphemeralRecordModification({componentInstance:{entityId:a,componentType:s},updateTag:"AutoDeselectRemovedProjectedEntity",writableState:{selectedEntityId:t.rootEntityId}})]:e};constructor(e){this._context=e,this.stateSlices={committed:this.committed.observable,rendered:this.rendered.observable,potentiallyInvalid:this.potentiallyInvalid.observable}}_validateState=e=>this._context.selectors.getValidationProjections().validateState(e);initialize=()=>{let e=this._context.selectors.getInitialDomainState();this.stagedUpdates=void 0;let t=this._validateState(e),i={kind:"reset",state:e,validity:t,tag:void 0,transformationLog:void 0},o=i;if(!o.validity.valid&&"fatal"===o.validity.severity||"fixable"===o.validity.severity){this._context.domainServicesSelectors.getLogger().debug("Trying to fix initial emission:",o);let e=o.state,{transformedUpdates:t,transformationLog:i}=this.applyTransformers([],e,"committed"),r=I(this.transformToDataUpdates(t,e),e);f(e,r),o={kind:"reset",state:r,validity:this._validateState(r),tag:"fixed",transformationLog:i}}if(!o.validity.valid){if(this._context.domainServicesSelectors.getLogger().error("Invalid initial emission:",{initialEmission:i,fixedEmission:o}),"uncaught"===o.validity.severity)throw new w(o,this._context.domainServicesSelectors.getResolveLocalizable(),o.validity.error??void 0);throw new w(o,this._context.domainServicesSelectors.getResolveLocalizable())}this.committed.next(o),this.rendered.next(o),this.potentiallyInvalid.next(o)};registerTransformer(e,i,o){let r={};return((e,i,o)=>{let r=0;for(;r<e.length&&0>=o(t(e[r]),i);)r++;e.splice(r,0,i)})(this.transformPipe,{registrationToken:r,transformer:i,priority:e,name:o},(e,t)=>e.priority===t.priority?0:e.priority<t.priority?-1:1),()=>{let e=this.transformPipe.findIndex(e=>e.registrationToken===r);-1!==e&&this.transformPipe.splice(e,1)}}onBeforeCommit(e){return this._onBeforeCommitHooks.push(e),()=>{this._onBeforeCommitHooks=this._onBeforeCommitHooks.filter(t=>t!==e)}}componentModificationToDataUpdate=(e,t)=>{let i=e.entityId;if(!p(i)){let t=this._context.selectors.getComponentReaderIndexes().opticMap.get(c(i))?.get(e.componentInstance.componentType)?.get(e.componentInstance.instanceName);if(t?.kind==="simple"){let o=t.write(e.writableState);return{kind:"modifyDomainEntity",entityId:i,updateTag:e.updateTag,stateDelta:o,hint:e.hint,agentHint:e.agentHint,origin:e}}}let o=t.ephemeralRecords.find(t=>l(t.componentInstance,e.componentInstance));if(o)return{kind:"modifyEphemeralRecord",entityId:e.entityId,updateTag:e.updateTag,componentInstance:o.componentInstance,writableState:e.writableState,hint:e.hint,agentHint:e.agentHint};throw Error(`Component ${e.componentInstance.componentType.name} is not attached on entity #${e.entityId}`)};getNewState=(e,t)=>{let i=I(this.transformToDataUpdates(e,t),t);return f(this.rendered.isInitialized?this.rendered.value.state:t,i),i};applyTransformers(e,t,i){let o=this._context.environmentSelectors.getEnvironmentIsDev()?[]:void 0;return{transformedUpdates:this.transformPipe.reduce((e,{transformer:r,name:s})=>{let n,a=o?[]:void 0,d=a?(e,t,i)=>{n=e,a.push({phase:e,message:t,data:i})}:void 0,m=b(()=>r(e,t,i,d),r=>{this._context.domainServicesSelectors.getLogger().error("Error while applying transformer!",{name:s,updates:e,previousState:t,kind:i,transformationLog:o},r instanceof Error?r:Error(String(r)))});return a&&o&&o.push({name:s,status:n??(m===e?"no-event":"apply"),entries:a,updatesIn:e,updatesOut:m}),m},e),transformationLog:o}}_updateProjectedEntities(e,t,o){if(!e.validity.valid)return e;let r=this._context.selectors.getComponentReader().readManyComponents({componentTypes:[h]},e.state),s=g(e.previousState,k);if(s&&i(s,r))return e;let n=0,a=e,d=[];for(;a.validity.valid;){n++;let i=T(a.state.entities,r,t);if(0===i.length)break;if(n>10)throw Error(`Maximum number of reconciliation rounds reached: 10. Projected entities seem to be recursively depending on themselves.
|
|
2
2
|
If expressions populating 'projectedEntities' components rely on other projected entities, make sure that the dependencies do not have cycles.`);let s=(d=x(d,i)).map(e=>e.dataUpdate),m=this._cascadeDeletesTransformer(s,e.previousState,o,void 0,t),l=this._refPruningTransformer(m,e.previousState,o,void 0,t),c=this._deselectOnDeleteTransformer(l,e.previousState,o,void 0,t);if(!(a=this.prepareStateEmissionWithoutTransformation([...t,...c],e.previousState,o)).validity.valid)return this._context.domainServicesSelectors.getLogger().error("Reconciliation of projected entities led to an invalid state! Reconciliation skipped.",{emission:a}),e;r=this._context.selectors.getComponentReader().readManyComponents({componentTypes:[h]},a.state)}return u(a.state,k,r),a}prepareStateEmission(e,t,i){let{transformedUpdates:o,transformationLog:r}=this.applyTransformers(e,t,i),s=this.prepareStateEmissionWithoutTransformation(o,t,i);return{...this._updateProjectedEntities(s,o,i),transformationLog:r}}emissionCache=new e([Map,WeakMap,WeakMap,WeakMap,WeakMap]);getEmissionCacheKey=(e,t,i)=>[e,t,i,this._context.selectors.getStoreRuntimeDependencies(),this._context.selectors.getExpressionContext()];prepareStateEmissionWithoutTransformation=(e,t,i)=>{let o=this.getEmissionCacheKey(i,t,e),r=this.emissionCache.get(o);if(r)return r;let s=b(()=>this.transformToDataUpdates(e,t),o=>{this._context.domainServicesSelectors.getLogger().error("Error while transforming updates to data updates!",{updates:e,previousState:t,kind:i},o instanceof Error?o:Error(String(o)))}),n=b(()=>I(s,t),o=>{this._context.domainServicesSelectors.getLogger().error("Error while applying updates!",{updates:e,previousState:t,kind:i,dataUpdates:s},o instanceof Error?o:Error(String(o)))});f(this.rendered.isInitialized?this.rendered.value.state:t,n);let a=this._validateState(n);"uncaught"===a.severity&&this._context.domainServicesSelectors.getLogger().error("There was an uncaught validation error:",{updates:e,dataUpdates:s,previousState:t,newState:n,kind:i},a.error);let d={kind:i,previousState:t,state:n,updates:s,validity:a,transformationLog:void 0};return this.emissionCache.set(o,d),d};stage(e,t=!0){this.stagedUpdates=e;let i=this.prepareStateEmission(e,this.committed.value.state,"staged");return t&&this.emit(i),i}emit(e){"staged"===e.kind?e.validity.valid&&this.rendered.nextIfDifferent(e):(e.validity.valid?(this.committed.nextIfDifferent(e),this.rendered.nextIfDifferent(e)):this.rendered.nextIfDifferent(this.committed.value),this.potentiallyInvalid.nextIfDifferent(e))}commit=()=>{if(void 0===this.stagedUpdates)return;let e=this.prepareStateEmission(this.stagedUpdates,this.committed.value.state,"committed"),t=()=>{if(this._onBeforeCommitHooks.some(i=>!1===i(e,t))){this._context.domainServicesSelectors.getLogger().debug("Commit was canceled by one of the onBeforeCommit hooks! Resetting rendered state.",e),this.rollback();return}this.stagedUpdates=void 0,this._context.domainServicesSelectors.getLogger().debug("commit",e),this.emit(e)};t()};commitPrepared=e=>{if("committed"!==e.kind||!e.validity.valid)throw Error(`commitPrepared received a ${e.validity.valid?e.kind:"invalid"} emission, but only a valid committed emission can become the committed state. Prepare the emission with kind "committed" and check its validity before committing it.`);let t=()=>e.previousState===this.committed.value.state;if(!t())return"conflict";let i=()=>{t()?o():this._context.domainServicesSelectors.getLogger().warn("A held commit was dropped, because the committed state changed since it was prepared.",e)},o=()=>this._onBeforeCommitHooks.some(t=>!1===t(e,i))?(this._context.domainServicesSelectors.getLogger().debug("A prepared commit was held by one of the onBeforeCommit hooks.",e),!1):(this._context.domainServicesSelectors.getLogger().debug("commitPrepared",e),this.stagedUpdates=void 0,this.emit(e),!0);return o()?"committed":"held"};rollback=()=>{void 0!==this.stagedUpdates&&(this.stagedUpdates=void 0,this.emit(this.committed.value))};_resetInteractionState(e){return e.ephemeralRecords.some(e=>{let t;return(t=e.componentInstance.componentType)===r||t===o})?{...e,ephemeralRecords:e.ephemeralRecords.map(e=>e.componentInstance.componentType===r?{...e,state:{hoveredEntityId:null}}:e.componentInstance.componentType===o?{...e,state:{draggedEntityId:null}}:e)}:e}_preserveViewportState(e,t){let i=t.ephemeralRecords.find(m),o=e.ephemeralRecords.filter(e=>!m(e));return{...e,ephemeralRecords:i?[...o,i]:o}}reset(e,t){let i=this.committed.value.state,o=this._preserveViewportState(e,i),r=this._resetInteractionState(o),s=this._validateState(r);if(!s.valid)throw Error("Cannot reset to an invalid state");this.stagedUpdates=void 0,this.emit({kind:"reset",state:r,validity:s,tag:t,transformationLog:void 0})}stageAndCommit(e){if(0!==e.length){this.stagedUpdates=e;try{this.commit()}finally{this.stagedUpdates=void 0}}}}
|
package/dist/editor/Editor.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as e,jsxs as i,Fragment as t}from"react/jsx-runtime";import{Box as o,Chip as n,CssBaseline as r,IconButton as s,ThemeProvider as l,Tooltip as a,Typography as d,createTheme as c,useMediaQuery as m,useTheme as p}from"@mui/material";import{ModalProvider as f}from"mui-modal-provider";import{memo as h,useCallback as u,useEffect as g,useRef as w,useState as k}from"react";import{match as x}from"ts-pattern";import{useLocalStorage as y}from"usehooks-ts";import{PhxIcon as b,SnackbarProvider as v,createThemeWithPhoenixIcons as S}from"#package/ui-sdk";import{EditorMode as P}from"./EditorMode.js";import{EditorRuntimeProvider as j,useWebComponent as V}from"./EditorRuntimeProvider.js";import{EditorAdminContextProvider as E}from"./admin/EditorAdminContext.js";import{EditorAdminMainContent as D}from"./admin/EditorAdminMainContent.js";import{EditorAdminSidebar as C}from"./admin/EditorAdminSidebar.js";import{useEditorAdminState as T}from"./admin/use-editor-admin-state.js";import{Analytics as A}from"./analytics/Analytics.js";import{AnalyticsProvider as L}from"./analytics/AnalyticsContext.js";import{Logotype as M}from"./common/Logotype.js";import{PanelIconButton as W}from"./common/PanelIconButton.js";import{BrowserConsoleReporter as R}from"./console-reporter/BrowserConsoleReporter.js";import{DataHandler as I}from"./data/DataHandler.js";import{DebugFlags as F}from"./debug-flags/DebugFlags.js";import{DiagnosticsPanel as G}from"./diagnostics/DiagnosticsPanel.js";import{DomainEditors as z}from"./domain-editors/DomainEditors.js";import{DomainSpecProvider as B,useDomainSpecContext as Q}from"./domain-editors/DomainSpecContext.js";import{DomainReflection as H}from"./domain-reflection/DomainReflection.js";import{GraphQLPanel as U}from"./graphql/GraphQLPanel.js";import{LogsPanel as q}from"./logs/LogsPanel.js";import{EditorMockProvider as O}from"./mocks/EditorMockContext.js";import{Mocks as K}from"./mocks/Mocks.js";import{ProfilerPanel as N}from"./profiler/ProfilerPanel.js";import{RemoteFilesList as X}from"./remote-files/RemoteFilesList.js";import{SceneHandler as Y}from"./scene/SceneHandler.js";import{ScreenshotHandler as $}from"./screenshot/ScreenshotHandler.js";import{EditorConnectionProvider as J}from"./services/EditorConnectionContext.js";import{EditorActionButtons as Z}from"./sidebar/EditorActionButtons.js";import{StateInspector as _}from"./state-inspector/index.js";import{StateHandler as ee}from"./state/StateHandler.js";import{SpaTemplate as ei}from"./templates/SpaTemplate.js";import{Templates as et}from"./templates/Templates.js";import{TemplatesList as eo}from"./templates/TemplatesList.js";import{TunnelProvider as en,useTunnel as er}from"./tunnel/TunnelContext.js";import{TunnelPanel as es}from"./tunnel/TunnelPanel.js";import{hasTunnelProblem as el}from"./tunnel/tunnel-view-model.js";import{VideoStudio as ea}from"./video-studio/VideoStudio.js";import{WebSocketStatus as ed}from"./websocket-status/WebSocketStatus.js";let ec=h(()=>{let i=w(null),t=V();return g(()=>{let e=i.current;if(e&&t)return e.appendChild(t),()=>{e.contains(t)&&e.removeChild(t)}},[t]),e("div",{ref:i,style:{width:"100%",height:"100%"}})}),em=S(c());export const EditorPanelView={Files:"Files",Reflections:"Reflections",Domain:"Domain",Templates:"Templates",Mocks:"Mocks",Inspector:"Inspector",Debug:"Debug",Profiler:"Profiler",GraphQL:"GraphQL",VideoStudio:"VideoStudio",Analytics:"Analytics",Diagnostics:"Diagnostics",Logs:"Logs",Tunnel:"Tunnel",WebSocketStatus:"WebSocketStatus",Admin:"Admin"};let ep=[{key:EditorPanelView.Templates,icon:"GridFour",title:"Templates"},{key:EditorPanelView.Reflections,icon:"House",title:"Reflections"},{key:EditorPanelView.Files,icon:"List",title:"Files"},{key:EditorPanelView.Domain,icon:"Gear",title:"Domain"},{key:EditorPanelView.Mocks,icon:"TagBold",title:"Mocks"},{key:EditorPanelView.Inspector,icon:"CurrencyDollar",title:"Inspector"},{key:EditorPanelView.Debug,icon:"EyeBold",title:"Debug"},{key:EditorPanelView.Profiler,icon:"Alarm",title:"Profiler"},{key:EditorPanelView.GraphQL,icon:"MagnifyingGlassBold",title:"GraphQL"},{key:EditorPanelView.VideoStudio,icon:"CameraRotate",title:"Video Studio"},{key:EditorPanelView.Analytics,icon:"Flame",title:"Analytics"},{key:EditorPanelView.Diagnostics,icon:"WarningCircle",title:"Diagnostics"},{key:EditorPanelView.Logs,icon:"BracketsCurly",title:"Logs"},{key:EditorPanelView.Tunnel,icon:"ArrowsHorizontal",title:"Webhook Tunnel"}],ef=h(r=>{let{panelView:l,setPanelView:c,width:m,setWidth:p,selectedTemplate:f,setSelectedTemplate:h,isResizing:w,setIsResizing:y,onExit:v,enableAdmin:S}=r,P=T(S),{unreadDiagnosticCount:j,markDiagnosticsRead:V}=Q(),{state:E}=er(),L=l?Math.max(m,240):38,[R,I]=k(0),B=u(()=>I(e=>e+1),[]);return g(()=>{l===EditorPanelView.Diagnostics&&V()},[V,l]),i(o,{component:"div",sx:{display:"grid",gridTemplateColumns:`${L}px min-content auto`,gridTemplateRows:"minmax(0, 1fr)",width:"100vw",height:"100vh",backgroundColor:"#ffffff",overflow:"hidden"},onMouseMove:e=>{w&&p(e.clientX)},onMouseUp:()=>{y(!1)},children:[i(o,{component:"div",sx:{display:"grid",gridTemplateColumns:"36px auto",backgroundColor:"#f8f9fa",borderRight:"1px solid #dee2e6",boxShadow:"2px 0 8px rgba(0, 0, 0, 0.06)",overflow:"hidden",height:"100%"},children:[i("div",{style:{backgroundColor:"#f8f9fa",height:"100%",display:"flex",flexDirection:"column",alignItems:"center",padding:"4px 0"},children:[e("div",{style:{marginBottom:"8px"},children:e(M,{variant:"icon-only"})}),i("div",{style:{flex:1,display:"flex",flexDirection:"column",gap:"2px"},children:[S&&i(t,{children:[e(W,{icon:"SlidersHorizontal",title:"Admin",active:l===EditorPanelView.Admin,onClick:()=>{l===EditorPanelView.Admin?c(null):c(EditorPanelView.Admin)}}),e("div",{style:{borderBottom:"1px solid #dee2e6",margin:"2px 0"}})]}),ep.map(i=>e(W,{icon:i.icon,title:i.title,active:l===i.key,badgeCount:i.key===EditorPanelView.Tunnel?+!!el(E):i.key===EditorPanelView.Diagnostics?j:0,onClick:()=>{l===i.key?c(null):c(i.key)}},i.key))]}),e(Z,{reload:B}),e("div",{style:{padding:"0 2px",paddingBottom:"4px"},children:e(W,{icon:"CloudArrowUp",title:"WebSocket Status",active:l===EditorPanelView.WebSocketStatus,onClick:()=>{l===EditorPanelView.WebSocketStatus?c(null):c(EditorPanelView.WebSocketStatus)}})}),v&&e("div",{style:{padding:"0 2px",paddingBottom:"8px"},children:e(W,{icon:"SignOut",title:"Exit Editor",variant:"danger",onClick:v})})]}),l&&i(o,{component:"div",sx:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden",backgroundColor:"#ffffff"},children:[e(o,{component:"div",sx:{p:1.5,borderBottom:"1px solid #e9ecef",backgroundColor:"#ffffff"},children:i(o,{component:"div",sx:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[i(o,{component:"div",sx:{display:"flex",flexDirection:"row",alignItems:"center"},children:[e(d,{variant:"h6",sx:{fontSize:16,fontWeight:600,color:"#212529"},children:x(l).with("Files",()=>"Files").with("Reflections",()=>"Reflections").with("Domain",()=>"Domain").with("Templates",()=>"Templates").with("Mocks",()=>"Mocks").with("Inspector",()=>"State Inspector").with("Debug",()=>"Debug").with("Profiler",()=>"Profiler").with("GraphQL",()=>"GraphQL").with("VideoStudio",()=>"Video Studio").with("Analytics",()=>"Analytics").with("Diagnostics",()=>"Diagnostics").with("Logs",()=>"Dev Server Logs").with("Tunnel",()=>"Webhook Tunnel").with("WebSocketStatus",()=>"WebSocket Status").with("Admin",()=>"Admin").otherwise(e=>e)}),e(a,{title:x(l).with("Files",()=>"Browse and inspect loaded GLTF files and their contents").with("Reflections",()=>"Inspect internal Phoenix systems state and configuration").with("Domain",()=>"Edit YAML domain specifications and component configurations").with("Templates",()=>"Select different layout templates for the configurator interface").with("Mocks",()=>"Create and manage mock data for testing session and access configurations").with("Inspector",()=>"Walk the entity tree: fields, expressions, and children").with("Debug",()=>"Toggle scene debug visuals like offset anchors, snapping, and collision meshes").with("Profiler",()=>"Make domain expressions show up as named frames in browser CPU profiles").with("GraphQL",()=>"Run GraphQL queries against the schema generated from the assistant manifest").with("VideoStudio",()=>"Create video sequences by capturing keyframes and exporting as video").with("Analytics",()=>"View parse pipeline metrics, domain stats, and diagnostics").with("Diagnostics",()=>"View latest editor warnings and errors").with("Logs",()=>"View dev server logs: spec builds, webhooks, vite, and browser console").with("Tunnel",()=>"View webhook tunnel status and the requests routed through it").with("WebSocketStatus",()=>"View WebSocket connection status and editor mode information").with("Admin",()=>"Manage admin panel, publish data, and configure settings").otherwise(()=>"Panel information"),placement:"left",arrow:!0,children:e(s,{size:"small",sx:{ml:1,color:"#6c757d",fontSize:14,p:.25,"&:hover":{backgroundColor:"#f8f9fa",color:"#495057"}},children:e(b,{name:"Info",style:{fontSize:14}})})})]}),e(o,{component:"div",sx:{display:"flex",alignItems:"center",gap:1},children:"Templates"===l&&e(n,{label:f.charAt(0).toUpperCase()+f.slice(1),variant:"outlined",size:"small",sx:{backgroundColor:"#f8f9fa",borderColor:"#dee2e6",color:"#495057",fontWeight:500,fontSize:"0.75rem"}})})]})}),i(o,{component:"div",sx:{flex:1,backgroundColor:"#ffffff",overflow:"auto"},children:["Files"===l&&e(X,{}),"Reflections"===l&&e(H,{}),"Domain"===l&&e(z,{}),"Templates"===l&&e(eo,{selectedTemplate:f,onTemplateSelect:h}),"Mocks"===l&&e(K,{}),"Inspector"===l&&e(_,{}),"Debug"===l&&e(F,{}),"Profiler"===l&&e(N,{}),"GraphQL"===l&&e(U,{}),"VideoStudio"===l&&e(ea,{}),"Analytics"===l&&e(A,{}),"Diagnostics"===l&&e(G,{}),"Logs"===l&&e(q,{}),"Tunnel"===l&&e(es,{}),"WebSocketStatus"===l&&e(ed,{}),S&&"Admin"===l&&e(C,{...P})]})]})]}),e("div",{style:{width:"2px",backgroundColor:"#dee2e6",cursor:"ew-resize",boxShadow:"1px 0 3px rgba(0, 0, 0, 0.05)"},onMouseDown:()=>{y(!0)}}),i("div",{style:{position:"relative",overflow:"hidden"},children:[e("div",{style:{position:"absolute",inset:0,zIndex:+("Admin"!==l)},children:e(et,{selectedTemplate:f,children:e(ec,{},R)})}),S&&e("div",{style:{position:"absolute",inset:0,zIndex:+("Admin"===l)},children:e(D,{})})]})]})}),eh=h(()=>e(ei,{children:e(ec,{})})),eu=h(o=>{let{wsUrl:n="ws://localhost:3020",localMode:r=!1,domainSpec:s,initialRawProjectFiles:l,onExit:a,mockTemplates:d,autoApplyTemplate:c,environmentKey:h,tagName:u,enableAdmin:w=!0}=o,x=m(p().breakpoints.up("md")),[b,S]=y("editor-width",350),[V,D]=y("editor-view",null),[C,T]=y("editor-template","spa"),[A,M]=k(!1);return g(()=>{null===V||Object.values(EditorPanelView).some(e=>e===V)&&(w||V!==EditorPanelView.Admin)||D(null)},[w,V,D]),e(f,{children:e(v,{maxSnack:5,children:e(E,{children:e(j,{tagName:u,children:e(J,{initialWsUrl:n,localMode:r,children:e(en,{children:e(P,{children:e(L,{children:e(B,{domainSpec:s,initialRawProjectFiles:l,children:i(O,{mockTemplates:d,autoApplyTemplate:c,environmentKey:h,children:[!r&&i(t,{children:[e($,{}),e(ee,{}),e(I,{}),e(Y,{}),e(R,{})]}),x?e(ef,{panelView:V,setPanelView:D,width:b,setWidth:S,selectedTemplate:C,setSelectedTemplate:T,isResizing:A,setIsResizing:M,onExit:a,enableAdmin:w}):e(eh,{})]})})})})})})})})})})});export const Editor=h(t=>i(l,{theme:em,children:[e(r,{}),e(eu,{...t})]}));
|
|
1
|
+
import{jsx as e,jsxs as i,Fragment as t}from"react/jsx-runtime";import{Box as o,Chip as n,CssBaseline as r,IconButton as s,ThemeProvider as a,Tooltip as l,Typography as d,createTheme as c,useMediaQuery as m,useTheme as p}from"@mui/material";import{ModalProvider as f}from"mui-modal-provider";import{memo as h,useCallback as u,useEffect as g,useState as w}from"react";import{match as k}from"ts-pattern";import{useLocalStorage as y}from"usehooks-ts";import{PhxIcon as x,SnackbarProvider as b,createThemeWithPhoenixIcons as v}from"#package/ui-sdk";import{EditorMode as S}from"./EditorMode.js";import{EditorRuntimeProvider as P}from"./EditorRuntimeProvider.js";import{EditorAdminContextProvider as j}from"./admin/EditorAdminContext.js";import{EditorAdminMainContent as V}from"./admin/EditorAdminMainContent.js";import{EditorAdminSidebar as E}from"./admin/EditorAdminSidebar.js";import{useEditorAdminState as D}from"./admin/use-editor-admin-state.js";import{Analytics as T}from"./analytics/Analytics.js";import{AnalyticsProvider as A}from"./analytics/AnalyticsContext.js";import{Logotype as C}from"./common/Logotype.js";import{PanelIconButton as L}from"./common/PanelIconButton.js";import{BrowserConsoleReporter as M}from"./console-reporter/BrowserConsoleReporter.js";import{DataHandler as W}from"./data/DataHandler.js";import{DebugFlags as R}from"./debug-flags/DebugFlags.js";import{DiagnosticsPanel as I}from"./diagnostics/DiagnosticsPanel.js";import{DomainEditors as F}from"./domain-editors/DomainEditors.js";import{DomainSpecProvider as G,useDomainSpecContext as z}from"./domain-editors/DomainSpecContext.js";import{DomainReflection as B}from"./domain-reflection/DomainReflection.js";import{GraphQLPanel as Q}from"./graphql/GraphQLPanel.js";import{LogsPanel as H}from"./logs/LogsPanel.js";import{EditorMockProvider as U}from"./mocks/EditorMockContext.js";import{Mocks as q}from"./mocks/Mocks.js";import{ProfilerPanel as O}from"./profiler/ProfilerPanel.js";import{RemoteFilesList as K}from"./remote-files/RemoteFilesList.js";import{SceneHandler as N}from"./scene/SceneHandler.js";import{ScreenshotHandler as X}from"./screenshot/ScreenshotHandler.js";import{EditorConnectionProvider as Y}from"./services/EditorConnectionContext.js";import{EditorActionButtons as $}from"./sidebar/EditorActionButtons.js";import{StateInspector as J}from"./state-inspector/index.js";import{StateHandler as Z}from"./state/StateHandler.js";import{SpaTemplate as _}from"./templates/SpaTemplate.js";import{Templates as ee}from"./templates/Templates.js";import{TemplatesList as ei}from"./templates/TemplatesList.js";import{TunnelProvider as et,useTunnel as eo}from"./tunnel/TunnelContext.js";import{TunnelPanel as en}from"./tunnel/TunnelPanel.js";import{hasTunnelProblem as er}from"./tunnel/tunnel-view-model.js";import{HTML_VARIANT_FRAME_ATTRIBUTE as es,VariantPreviewHandler as ea,useConfiguratorContainerRef as el}from"./variants/VariantPreviewHandler.js";import{VideoStudio as ed}from"./video-studio/VideoStudio.js";import{WebSocketStatus as ec}from"./websocket-status/WebSocketStatus.js";let em=h(()=>e("div",{ref:el(),style:{width:"100%",height:"100%"}})),ep=v(c());export const EditorPanelView={Files:"Files",Reflections:"Reflections",Domain:"Domain",Templates:"Templates",Mocks:"Mocks",Inspector:"Inspector",Debug:"Debug",Profiler:"Profiler",GraphQL:"GraphQL",VideoStudio:"VideoStudio",Analytics:"Analytics",Diagnostics:"Diagnostics",Logs:"Logs",Tunnel:"Tunnel",WebSocketStatus:"WebSocketStatus",Admin:"Admin"};let ef=[{key:EditorPanelView.Templates,icon:"GridFour",title:"Templates"},{key:EditorPanelView.Reflections,icon:"House",title:"Reflections"},{key:EditorPanelView.Files,icon:"List",title:"Files"},{key:EditorPanelView.Domain,icon:"Gear",title:"Domain"},{key:EditorPanelView.Mocks,icon:"TagBold",title:"Mocks"},{key:EditorPanelView.Inspector,icon:"CurrencyDollar",title:"Inspector"},{key:EditorPanelView.Debug,icon:"EyeBold",title:"Debug"},{key:EditorPanelView.Profiler,icon:"Alarm",title:"Profiler"},{key:EditorPanelView.GraphQL,icon:"MagnifyingGlassBold",title:"GraphQL"},{key:EditorPanelView.VideoStudio,icon:"CameraRotate",title:"Video Studio"},{key:EditorPanelView.Analytics,icon:"Flame",title:"Analytics"},{key:EditorPanelView.Diagnostics,icon:"WarningCircle",title:"Diagnostics"},{key:EditorPanelView.Logs,icon:"BracketsCurly",title:"Logs"},{key:EditorPanelView.Tunnel,icon:"ArrowsHorizontal",title:"Webhook Tunnel"}],eh=h(r=>{let{panelView:a,setPanelView:c,width:m,setWidth:p,selectedTemplate:f,setSelectedTemplate:h,isResizing:y,setIsResizing:b,onExit:v,enableAdmin:S}=r,P=D(S),{unreadDiagnosticCount:j,markDiagnosticsRead:A}=z(),{state:M}=eo(),W=a?Math.max(m,240):38,[G,U]=w(0),N=u(()=>U(e=>e+1),[]);return g(()=>{a===EditorPanelView.Diagnostics&&A()},[A,a]),i(o,{component:"div",sx:{display:"grid",gridTemplateColumns:`${W}px min-content auto`,gridTemplateRows:"minmax(0, 1fr)",width:"100vw",height:"100vh",backgroundColor:"#ffffff",overflow:"hidden"},onMouseMove:e=>{y&&p(e.clientX)},onMouseUp:()=>{b(!1)},children:[i(o,{component:"div",sx:{display:"grid",gridTemplateColumns:"36px auto",backgroundColor:"#f8f9fa",borderRight:"1px solid #dee2e6",boxShadow:"2px 0 8px rgba(0, 0, 0, 0.06)",overflow:"hidden",height:"100%"},children:[i("div",{style:{backgroundColor:"#f8f9fa",height:"100%",display:"flex",flexDirection:"column",alignItems:"center",padding:"4px 0"},children:[e("div",{style:{marginBottom:"8px"},children:e(C,{variant:"icon-only"})}),i("div",{style:{flex:1,display:"flex",flexDirection:"column",gap:"2px"},children:[S&&i(t,{children:[e(L,{icon:"SlidersHorizontal",title:"Admin",active:a===EditorPanelView.Admin,onClick:()=>{a===EditorPanelView.Admin?c(null):c(EditorPanelView.Admin)}}),e("div",{style:{borderBottom:"1px solid #dee2e6",margin:"2px 0"}})]}),ef.map(i=>e(L,{icon:i.icon,title:i.title,active:a===i.key,badgeCount:i.key===EditorPanelView.Tunnel?+!!er(M):i.key===EditorPanelView.Diagnostics?j:0,onClick:()=>{a===i.key?c(null):c(i.key)}},i.key))]}),e($,{reload:N}),e("div",{style:{padding:"0 2px",paddingBottom:"4px"},children:e(L,{icon:"CloudArrowUp",title:"WebSocket Status",active:a===EditorPanelView.WebSocketStatus,onClick:()=>{a===EditorPanelView.WebSocketStatus?c(null):c(EditorPanelView.WebSocketStatus)}})}),v&&e("div",{style:{padding:"0 2px",paddingBottom:"8px"},children:e(L,{icon:"SignOut",title:"Exit Editor",variant:"danger",onClick:v})})]}),a&&i(o,{component:"div",sx:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden",backgroundColor:"#ffffff"},children:[e(o,{component:"div",sx:{p:1.5,borderBottom:"1px solid #e9ecef",backgroundColor:"#ffffff"},children:i(o,{component:"div",sx:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[i(o,{component:"div",sx:{display:"flex",flexDirection:"row",alignItems:"center"},children:[e(d,{variant:"h6",sx:{fontSize:16,fontWeight:600,color:"#212529"},children:k(a).with("Files",()=>"Files").with("Reflections",()=>"Reflections").with("Domain",()=>"Domain").with("Templates",()=>"Templates").with("Mocks",()=>"Mocks").with("Inspector",()=>"State Inspector").with("Debug",()=>"Debug").with("Profiler",()=>"Profiler").with("GraphQL",()=>"GraphQL").with("VideoStudio",()=>"Video Studio").with("Analytics",()=>"Analytics").with("Diagnostics",()=>"Diagnostics").with("Logs",()=>"Dev Server Logs").with("Tunnel",()=>"Webhook Tunnel").with("WebSocketStatus",()=>"WebSocket Status").with("Admin",()=>"Admin").otherwise(e=>e)}),e(l,{title:k(a).with("Files",()=>"Browse and inspect loaded GLTF files and their contents").with("Reflections",()=>"Inspect internal Phoenix systems state and configuration").with("Domain",()=>"Edit YAML domain specifications and component configurations").with("Templates",()=>"Select different layout templates for the configurator interface").with("Mocks",()=>"Create and manage mock data for testing session and access configurations").with("Inspector",()=>"Walk the entity tree: fields, expressions, and children").with("Debug",()=>"Toggle scene debug visuals like offset anchors, snapping, and collision meshes").with("Profiler",()=>"Make domain expressions show up as named frames in browser CPU profiles").with("GraphQL",()=>"Run GraphQL queries against the schema generated from the assistant manifest").with("VideoStudio",()=>"Create video sequences by capturing keyframes and exporting as video").with("Analytics",()=>"View parse pipeline metrics, domain stats, and diagnostics").with("Diagnostics",()=>"View latest editor warnings and errors").with("Logs",()=>"View dev server logs: spec builds, webhooks, vite, and browser console").with("Tunnel",()=>"View webhook tunnel status and the requests routed through it").with("WebSocketStatus",()=>"View WebSocket connection status and editor mode information").with("Admin",()=>"Manage admin panel, publish data, and configure settings").otherwise(()=>"Panel information"),placement:"left",arrow:!0,children:e(s,{size:"small",sx:{ml:1,color:"#6c757d",fontSize:14,p:.25,"&:hover":{backgroundColor:"#f8f9fa",color:"#495057"}},children:e(x,{name:"Info",style:{fontSize:14}})})})]}),e(o,{component:"div",sx:{display:"flex",alignItems:"center",gap:1},children:"Templates"===a&&e(n,{label:f.charAt(0).toUpperCase()+f.slice(1),variant:"outlined",size:"small",sx:{backgroundColor:"#f8f9fa",borderColor:"#dee2e6",color:"#495057",fontWeight:500,fontSize:"0.75rem"}})})]})}),i(o,{component:"div",sx:{flex:1,backgroundColor:"#ffffff",overflow:"auto"},children:["Files"===a&&e(K,{}),"Reflections"===a&&e(B,{}),"Domain"===a&&e(F,{}),"Templates"===a&&e(ei,{selectedTemplate:f,onTemplateSelect:h}),"Mocks"===a&&e(q,{}),"Inspector"===a&&e(J,{}),"Debug"===a&&e(R,{}),"Profiler"===a&&e(O,{}),"GraphQL"===a&&e(Q,{}),"VideoStudio"===a&&e(ed,{}),"Analytics"===a&&e(T,{}),"Diagnostics"===a&&e(I,{}),"Logs"===a&&e(H,{}),"Tunnel"===a&&e(en,{}),"WebSocketStatus"===a&&e(ec,{}),S&&"Admin"===a&&e(E,{...P})]})]})]}),e("div",{style:{width:"2px",backgroundColor:"#dee2e6",cursor:"ew-resize",boxShadow:"1px 0 3px rgba(0, 0, 0, 0.05)"},onMouseDown:()=>{b(!0)}}),i("div",{style:{position:"relative",overflow:"hidden"},children:[e("div",{style:{position:"absolute",inset:0,zIndex:+("Admin"!==a)},children:e(ee,{selectedTemplate:f,children:e(em,{},G)})}),S&&e("div",{style:{position:"absolute",inset:0,zIndex:+("Admin"===a)},children:e(V,{})})]})]})}),eu=h(()=>e(_,{children:e(em,{})})),eg=h(o=>{let{wsUrl:n="ws://localhost:3020",localMode:r=!1,domainSpec:s,initialRawProjectFiles:a,onExit:l,mockTemplates:d,autoApplyTemplate:c,environmentKey:h,tagName:u,enableAdmin:k=!0}=o,x=m(p().breakpoints.up("md")),[v,V]=y("editor-width",350),[E,D]=y("editor-view",null),[T,C]=y("editor-template","spa"),[L,R]=w(!1);return g(()=>{null===E||Object.values(EditorPanelView).some(e=>e===E)&&(k||E!==EditorPanelView.Admin)||D(null)},[k,E,D]),e(f,{children:e(b,{maxSnack:5,children:e(j,{children:e(P,{tagName:u,children:e(Y,{initialWsUrl:n,localMode:r,children:e(et,{children:e(S,{children:e(A,{children:e(G,{domainSpec:s,initialRawProjectFiles:a,children:i(U,{mockTemplates:d,autoApplyTemplate:c,environmentKey:h,children:[!r&&i(t,{children:[e(X,{}),e(Z,{}),e(W,{}),e(N,{}),e(M,{})]}),e(ea,{children:x?e(eh,{panelView:E,setPanelView:D,width:v,setWidth:V,selectedTemplate:T,setSelectedTemplate:C,isResizing:L,setIsResizing:R,onExit:l,enableAdmin:k}):e(eu,{})})]})})})})})})})})})})});export const Editor=h(t=>{try{if(window.frameElement?.hasAttribute(es))return e("div",{role:"alert","data-testid":"variant-page-unavailable",style:{padding:24,fontFamily:"sans-serif"},children:"This preview page is unavailable. Ask the agent to recreate it or close the comparison."})}catch{}return i(a,{theme:ep,children:[e(r,{}),e(eg,{...t})]})});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as e,jsxs as
|
|
1
|
+
import{jsx as e,jsxs as t}from"react/jsx-runtime";import o from"@monaco-editor/react";import{Box as r,Checkbox as i,FormControlLabel as a,Stack as n,Typography as s}from"@mui/material";import{useState as l}from"react";import{EditorButton as m}from"../common/EditorButton.js";import{jsonEditorOptions as d}from"../common/monaco-config.js";import{useOptionalConfigurator as c,useOptionalDomain as p}from"../hooks/use-optional-runtime.js";import{splitOperations as u}from"./split-operations.js";let h={fontSize:"12px",fontWeight:600,color:"text.secondary"};export const GraphQLPanel=()=>{let f=c()?.graphQLSystem,g=p()?.storeSystem,[x,y]=l("query { root { id type } }"),[b,v]=l(""),[S,k]=l(!1),[j,N]=l(null),[C,w]=l(null),[z,J]=l(!1),O=async()=>{let e=u(x),t=(e=>{if(""===e.trim())return{ok:!0,variables:void 0};try{let t=JSON.parse(e);return"object"!=typeof t||null===t||Array.isArray(t)?{ok:!1,message:"Variables must be a JSON object. Wrap them in {} or clear the field."}:{ok:!0,variables:t}}catch(e){return{ok:!1,message:`Variables are not valid JSON: ${e instanceof Error?e.message:String(e)}. Fix the JSON or clear the field.`}}})(b);if(f){if(w(null),!e.ok)return void N(e.message);if(!t.ok)return void N(t.message);if(S&&!g?.isInitialized)return void N("The configuration is not loaded yet, so there is no state to run against. Run again once the configurator has finished loading.");J(!0);try{let o=e.operations.map(e=>({...e,variables:t.variables})),r=S&&g?await f.prepare(g.stateSlices.committed.value.state,o):void 0,{results:i,committed:a,message:n,sideEffects:s}=r?{results:r.map(({result:e})=>e),committed:!1,message:"Dry run: nothing was committed.",sideEffects:f.readSideEffects(r)}:await f.execute(o),l=i.map((t,o)=>({operationName:e.operations[o]?.operationName??null,...t}));N(JSON.stringify(s.length>0?{results:l,sideEffects:s}:l,null,2)),w(a?"Committed as one undo step.":n??"Nothing was committed.")}finally{J(!1)}}};return t(n,{direction:"column",spacing:1.5,sx:{px:1.5,py:1},children:[e(s,{variant:"subtitle2",sx:h,children:"Query"}),e(r,{component:"div",sx:{height:160,border:"1px solid #dee2e6"},children:e(o,{language:"graphql",value:x,onChange:e=>y(e??""),options:d})}),e(s,{variant:"subtitle2",sx:h,children:"Variables (JSON)"}),e(r,{component:"div",sx:{height:80,border:"1px solid #dee2e6"},children:e(o,{language:"json",value:b,onChange:e=>v(e??""),options:d})}),e(a,{control:e(i,{size:"small",checked:S,onChange:e=>{k(e.target.checked)},sx:{p:.5}}),label:"Dry run",sx:{ml:-.5,mr:0,"& .MuiFormControlLabel-label":{fontSize:"12px",color:"#212529"}}}),e(m,{fullWidth:!0,disabled:!f||z,onClick:()=>void O(),children:f?"Run":"Configurator is not ready"}),null!==C&&e(s,{"data-testid":"graphql-status",sx:{fontSize:"12px",color:"text.secondary"},children:C}),null!==j&&e(r,{component:"pre","data-testid":"graphql-result",sx:{m:0,p:1,fontSize:"12px",backgroundColor:"#f8f9fa",overflow:"auto",whiteSpace:"pre-wrap"},children:j})]})};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** An answer the builder gave, held back for a moment so that a slip can be undone. */
|
|
2
|
+
export interface HeldAnswer {
|
|
3
|
+
readonly secondsLeft: number;
|
|
4
|
+
readonly sending: boolean;
|
|
5
|
+
}
|
|
6
|
+
interface VariantAnswerFooterProps {
|
|
7
|
+
readonly label: string;
|
|
8
|
+
readonly canUse: boolean;
|
|
9
|
+
readonly held: HeldAnswer | null;
|
|
10
|
+
readonly sendError: string | null;
|
|
11
|
+
readonly onUse: () => void;
|
|
12
|
+
readonly onUndo: () => void;
|
|
13
|
+
readonly onSendNow: () => void;
|
|
14
|
+
}
|
|
15
|
+
/** Confirms the displayed option, with a short hold that lets an accidental answer be undone. */
|
|
16
|
+
export declare const VariantAnswerFooter: import("react").MemoExoticComponent<(props: VariantAnswerFooterProps) => import("react/jsx-runtime").JSX.Element>;
|
|
17
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{jsx as o,jsxs as e}from"react/jsx-runtime";import{CircularProgress as r,Typography as n}from"@mui/material";import{memo as f}from"react";import{EditorButton as i}from"../common/EditorButton.js";import{INK as t,actionButton as d,ellipsis as l,primaryButton as s}from"./variant-preview-styles.js";export const VariantAnswerFooter=f(f=>{let{label:a,canUse:c,held:x,sendError:p}=f;if(x){let l,s;return e("div",{role:"status",style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:12,boxSizing:"border-box",minHeight:40,padding:"0 12px",borderRadius:6,backgroundColor:t,color:"#ffffff"},children:[x.sending&&o(r,{size:16,"aria-label":"Sending",sx:{color:"#ffffff"}}),o(n,{sx:{flex:"1 1 200px",fontSize:"13px",fontWeight:600},children:(l=`“${a}” goes to the agent`,s=x.sending?" now…":` in ${x.secondsLeft} s.`,`${l}${s}`)}),!x.sending&&o(i,{autoFocus:!0,"data-testid":"variant-undo",onClick:f.onUndo,sx:{...d,backgroundColor:"transparent",border:"2px solid #ffffff",color:"#ffffff","&:hover":{backgroundColor:"rgba(255, 255, 255, 0.12)",borderColor:"#ffffff",color:"#ffffff"}},children:"Undo"}),!x.sending&&o(i,{"data-testid":"variant-send-now",onClick:f.onSendNow,sx:{...d,backgroundColor:"#ffffff",border:"2px solid #ffffff",color:t,"&:hover":{backgroundColor:"#e9ecef",borderColor:"#e9ecef",color:t}},children:"Send now"})]})}return e("div",{children:[o("div",{style:{display:"flex",justifyContent:"flex-end"},children:o(i,{"data-testid":"variant-use",disabled:!c,onClick:f.onUse,sx:{...d,...s,minWidth:0,maxWidth:"100%"},children:e("span",{style:{minWidth:0,...l},children:["Use ",a]})})}),null!==p&&o(n,{role:"alert",sx:{mt:.75,px:.5,fontSize:"13px",color:"#b02a37"},children:p})]})});
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { type ReactNode, type RefCallback } from 'react';
|
|
2
|
+
export declare const HTML_VARIANT_FRAME_ATTRIBUTE = "data-phx-html-variant";
|
|
3
|
+
export declare const useConfiguratorContainerRef: () => RefCallback<HTMLDivElement>;
|
|
4
|
+
export declare const VariantPreviewHandler: (props: {
|
|
5
|
+
readonly children: ReactNode;
|
|
6
|
+
}) => import("react/jsx-runtime").JSX.Element;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{jsx as e,jsxs as t}from"react/jsx-runtime";import{Box as r,Modal as i,Paper as n,Typography as o,useMediaQuery as a}from"@mui/material";import{createContext as l,useCallback as d,useContext as s,useEffect as p,useRef as c,useState as u}from"react";import{useWebComponent as f}from"../EditorRuntimeProvider.js";import{EditorButton as m}from"../common/EditorButton.js";import{importImplementationFile as h}from"../domain-editors/import-implementation-file.js";import{useEditorConnection as v}from"../services/EditorConnectionContext.js";import{trpc as x}from"../services/trpc.js";import{VariantAnswerFooter as g}from"./VariantAnswerFooter.js";import{INK as b,MUTED as w,variantDialogGeometry as y}from"./variant-preview-styles.js";export const HTML_VARIANT_FRAME_ATTRIBUTE="data-phx-html-variant";let E=l(null);export const useConfiguratorContainerRef=()=>{let e=s(E);if(!e)throw Error("The configurator container must be inside VariantPreviewHandler");return e};let I=l=>{let{request:d}=l,s=a("(max-width:899px)"),f=s?y.compact:y.regular,v=x.getVariantBaseline.useQuery({requestId:d.requestId},{refetchOnWindowFocus:!1}),E=x.applyVariantFiles.useMutation(),I=x.submitVariantChoice.useMutation(),[T,C]=u(null),[S,j]=u(!1),[z,R]=u(null),[V,k]=u(null),q=c(!1),A=d.variants.find(e=>e.id===T),H=A?.kind==="page"?A:null,W=A?.label??"Original";p(()=>{v.data&&C(v.data.choice)},[v.data]);let M=async e=>{if(!q.current&&v.data&&!V){q.current=!0,j(!0),R(null);try{let t=new Map,r=d.variants.find(t=>t.id===e);if(r?.kind==="script"){let e=await h(r.url);if("function"!=typeof e)throw Error("Export the variant script as the default function");let i=new Map(v.data.files.map(e=>[e.fileName,e.content]));await e({read:e=>{let t=i.get(e);if(null==t)throw Error(`The baseline has no file named ${e}`);return t},write:(e,r)=>{t.set(e,r)},remove:e=>{t.set(e,null)}})}await E.mutateAsync({requestId:d.requestId,choice:e,files:[...t].map(([e,t])=>({fileName:e,content:t}))}),C(e)}catch(e){R(e instanceof Error?e.message:String(e))}finally{q.current=!1,j(!1)}}},P=async()=>{if(V&&!V.sending){k({...V,sending:!0});try{await I.mutateAsync({requestId:d.requestId,choice:T})}catch(e){R(e instanceof Error?e.message:String(e)),k(null)}}};p(()=>{if(!V||V.sending)return;if(0===V.secondsLeft)return void P();let e=window.setTimeout(()=>{k(e=>e?{...e,secondsLeft:e.secondsLeft-1}:null)},1e3);return()=>window.clearTimeout(e)});let B=[{id:null,label:"Original",description:"The project before these changes."},...d.variants];return e(i,{open:!0,disableEscapeKeyDown:!0,BackdropProps:{sx:{bgcolor:"rgba(33, 37, 41, 0.55)"}},sx:{zIndex:1400},children:t(n,{role:"dialog","aria-labelledby":"variant-preview-title","aria-describedby":"variant-preview-description","aria-modal":"true","data-testid":"variant-preview",elevation:16,sx:{position:"fixed",inset:f.inset,zIndex:1400,borderRadius:"12px",overflow:"hidden",border:"1px solid #dee2e6",display:"grid",gridTemplateRows:`${f.header}px minmax(0, 1fr) ${f.footer}px`,bgcolor:"#fff",pointerEvents:"none"},children:[e(r,{component:"div",sx:{display:"flex",alignItems:"center",gap:2,px:s?2:3,borderBottom:"1px solid #dee2e6",bgcolor:"#fff",pointerEvents:"auto",zIndex:2},children:t(r,{component:"div",sx:{flex:1,minWidth:0},children:[e(o,{id:"variant-preview-title",component:"h2",sx:{fontSize:19,fontWeight:600,color:b,lineHeight:1.35},children:d.title}),e(o,{id:"variant-preview-description",sx:{mt:.5,fontSize:13,color:w},children:d.description})]})}),t(r,{component:"div",sx:{display:"grid",gridTemplateColumns:`${f.choices}px minmax(0, 1fr)`,minHeight:0},children:[t(r,{component:"div",role:"group","aria-label":"Variant options",sx:{p:s?1:2,minHeight:0,overflowY:"auto",borderRight:"1px solid #dee2e6",bgcolor:"#f8f9fa",pointerEvents:"auto",zIndex:2},children:[e(o,{sx:{fontSize:11,fontWeight:600,letterSpacing:"0.06em",color:w,textTransform:"uppercase",mb:1,px:.5},children:"Compare options"}),B.map(r=>{let i=T===r.id;return t(m,{"data-testid":null===r.id?"variant-baseline":"variant-tab","aria-pressed":i,disabled:S||null!==V||!v.data,fullWidth:!0,onClick:()=>{M(r.id)},sx:{display:"block",textAlign:"left",mb:.5,p:s?.875:1.125,whiteSpace:"normal",bgcolor:i?"#e9eef5":"transparent",borderColor:"transparent",boxShadow:i?"inset 2px 0 #495057":"none","&:hover":{bgcolor:i?"#e9eef5":"#eef1f4",borderColor:"#adb5bd"}},children:[e(o,{component:"span",sx:{display:"block",fontSize:13,fontWeight:600,color:b},children:r.label}),e(o,{component:"span",sx:{display:"block",mt:.375,fontSize:11.5,lineHeight:1.35,color:w},children:r.description})]},null===r.id?"original":`variant:${r.id}`)})]}),t("div",{style:{position:"relative",minWidth:0,minHeight:0,zIndex:1},children:[e("div",{ref:H?null:l.previewContainerRef,"data-testid":"variant-configurator",style:{display:H?"none":"block",width:"100%",height:"100%",pointerEvents:"auto"}}),H&&e("iframe",{title:H.label,src:H.url,"data-testid":"variant-html","data-phx-html-variant":"",style:{position:"absolute",inset:0,width:"100%",height:"100%",border:0,pointerEvents:"auto"}},H.id)]})]}),e(r,{component:"div",sx:{px:s?1.5:2,py:1.5,borderTop:"1px solid #dee2e6",bgcolor:"#fff",pointerEvents:"auto",zIndex:2,overflowY:"auto"},children:e(g,{label:W,canUse:void 0!==v.data&&!S&&null===z,held:V,sendError:z??v.error?.message??null,onUse:()=>{R(null),k({secondsLeft:4,sending:!1})},onUndo:()=>k(null),onSendNow:()=>{P()}})})]})})};export const VariantPreviewHandler=r=>{let{localMode:i}=v(),n=f(),[o,a]=u(null),l=c(null),s=c(null),p=d(()=>{let e=s.current??l.current;e&&n&&n.parentNode!==e&&e.appendChild(n)},[n]),m=d(e=>{l.current=e,p()},[p]),h=d(e=>{s.current=e,p()},[p]);return x.onVariantPreview.useSubscription(void 0,{enabled:!i,onData:a}),t(E.Provider,{value:m,children:[r.children,o&&e(I,{request:o,previewContainerRef:h},o.requestId)]})};
|