(()=>{"use strict";class CodeletSandboxCommsRpcService{async sendMessage(messagePath,data){const res=await this.sandboxComms.request(messagePath,data);if(!res.ok)throw res.error;if(res.value===undefined)throw new Error(`${messagePath}: Response cannot be empty`);return res.value}registerMessageHandler(messagePath,handler){return this.sandboxComms.handle(messagePath,(async request=>{if(request==null)throw new Error(`${messagePath}: Request cannot be undefined`);return handler(request)}))}constructor(sandboxComms){this.sandboxComms=sandboxComms}}const EDITING2_SDK_CLIENT_ID="canva-code-editing2-sdk";class Preconditions{static checkArgument(cond,msg,...args){if(!cond)throw new Error(msg==null?"invalid argument":Preconditions.format(msg,...args))}static checkState(cond,msg,...args){if(!cond)throw new Error(msg==null?"invalid state":Preconditions.format(msg,...args))}static checkEquals(a,b,msg,...args){if(a!==b)throw new Error(msg==null?Preconditions.format("{} != {}",Preconditions.stringify(a),Preconditions.stringify(b)):Preconditions.format(msg,...args))}static stringify(x){if(x==null||typeof x==="symbol")return String(x);else try{return JSON.stringify(x)}catch(e){return String(x)}}static checkExists(x,msg,...args){if(x==null)throw new Error(msg==null?"argument is null":Preconditions.format(msg,...args));return x}static format(template,...args){let i=0;return template.replace(/\{}/g,(()=>i{Preconditions.checkArgument(args.length===0);if(result==null||invalidateOnError&&(!result.ok||promiseDidReject))try{promiseDidReject=false;result=Result.Ok(fn());if(isPromiseLike(result.value))result.value.then(null,(_e=>promiseDidReject=true))}catch(e){result=Result.Err(e)}if(result.ok)return result.value;else throw result.error};return memoFn}function memoize1(fn){const cache=new WeakMap;const memoFn=(key,...rest)=>{Preconditions.checkArgument(rest.length===0);if(!cache.has(key))cache.set(key,fn(key));return cache.get(key)};return memoFn}const MessageKind={CONCRETE:1,ONEOF:2};const FieldLabel={CONSTANT:1,REQUIRED:2,OPTIONAL:3,REPEATED:4,MAP:5};const FieldKind={PRIMITIVE:1,MESSAGE:2,ENUM:3};const makeType=t=>t;const ProtoType={STRING:makeType({typeOfValue:"string"}),BOOLEAN:makeType({typeOfValue:"boolean",defaultValue:false,fixedSize:1}),DOUBLE:makeType({typeOfValue:"number",defaultValue:0,fixedSize:8}),INT32:makeType({typeOfValue:"number",defaultValue:0}),INT64:makeType({typeOfValue:"number",defaultValue:0}),BYTES:makeType({typeOfValue:"Uint8Array"})};function makeFieldConfig(tag,fieldLabel,typeOfValue,jsonFullKey,jsonFullValue,value,defaults,defaultField,defaultValue,obj,typeOfKey){return{tag,fieldLabel,typeOfValue,jsonFullKey,jsonFullValue,value,defaults,default:defaultField,defaultValue,obj,typeOfKey}}function constantField(params){const{tag,jsonFullKeyOrJsonMiniKey,jsonFullValue,value,defaults}=params;const jsonFullKey=jsonFullKeyOrJsonMiniKey===DISCRIMINATOR_JSON_MINI_KEY?undefined:jsonFullKeyOrJsonMiniKey;return makeFieldConfig(tag,FieldLabel.CONSTANT,"string",jsonFullKey,jsonFullValue,value,defaults,undefined,undefined,undefined,undefined)}function requiredField(valueType,jsonFullKey,tag,def){return makeFieldConfig(tag,FieldLabel.REQUIRED,valueType.typeOfValue,jsonFullKey,undefined,undefined,undefined,def!=null?def:valueType.defaultValue,valueType.defaultValue,undefined,undefined)}function optionalField(valueType,jsonFullKey,tag){return makeFieldConfig(tag,FieldLabel.OPTIONAL,valueType.typeOfValue,jsonFullKey,undefined,undefined,undefined,undefined,valueType.defaultValue,undefined,undefined)}function repeatedField(valueType,jsonFullKey,tag){return makeFieldConfig(tag,FieldLabel.REPEATED,valueType.typeOfValue,jsonFullKey,undefined,undefined,undefined,undefined,undefined,undefined,undefined)}function mapField(keyType,valueType){return(tagOrJsonFullKey,tagOrObj,maybeObj)=>{const{tag,jsonFullKey,other1:obj}=getOptions(tagOrJsonFullKey,tagOrObj,maybeObj);let typeOfValue;if(valueType==="object")typeOfValue="object";else if(valueType==="enum")typeOfValue="string";else typeOfValue=valueType.typeOfValue;return makeFieldConfig(tag,FieldLabel.MAP,typeOfValue,jsonFullKey,undefined,undefined,undefined,undefined,undefined,obj,keyType.typeOfValue)}}class Proto{static constantString(jsonFullKeyOrJsonMiniKey,jsonFullValueOrTag,tagOrValue,maybeValue){const{tag,jsonFullKey:jsonFullValue,other1:value}=getOptions(jsonFullValueOrTag,tagOrValue,maybeValue);return constantField({tag,jsonFullKeyOrJsonMiniKey,jsonFullValue,value,defaults:false})}static constantStringWithDefault(jsonFullKeyOrJsonMiniKey,jsonFullValueOrTag,tagOrValue,maybeValue){const{tag,jsonFullKey:jsonFullValue,other1:value}=getOptions(jsonFullValueOrTag,tagOrValue,maybeValue);return constantField({tag,jsonFullKeyOrJsonMiniKey,jsonFullValue,value,defaults:true})}static requiredObject(tagOrJsonFullKey,tagOrObj,maybeObj){const{tag,jsonFullKey,other1:obj}=getOptions(tagOrJsonFullKey,tagOrObj,maybeObj);return makeFieldConfig(tag,FieldLabel.REQUIRED,"object",jsonFullKey,undefined,undefined,undefined,undefined,undefined,obj,undefined)}static optionalObject(tagOrJsonFullKey,tagOrObj,maybeObj){const{tag,jsonFullKey,other1:obj}=getOptions(tagOrJsonFullKey,tagOrObj,maybeObj);return makeFieldConfig(tag,FieldLabel.OPTIONAL,"object",jsonFullKey,undefined,undefined,undefined,undefined,undefined,obj,undefined)}static repeatedObject(tagOrJsonFullKey,tagOrObj,maybeObj){const{tag,jsonFullKey,other1:obj}=getOptions(tagOrJsonFullKey,tagOrObj,maybeObj);return makeFieldConfig(tag,FieldLabel.REPEATED,"object",jsonFullKey,undefined,undefined,undefined,undefined,undefined,obj,undefined)}static requiredStringEnum(tagOrJsonFullKey,tagOrObj,objOrDef,maybeDef){const{tag,jsonFullKey,other1:obj,other2:def}=getOptions(tagOrJsonFullKey,tagOrObj,objOrDef,maybeDef);return makeFieldConfig(tag,FieldLabel.REQUIRED,"string",jsonFullKey,undefined,undefined,undefined,def,undefined,obj,undefined)}static optionalStringEnum(tagOrJsonFullKey,tagOrObj,maybeObj){const{tag,jsonFullKey,other1:obj}=getOptions(tagOrJsonFullKey,tagOrObj,maybeObj);return makeFieldConfig(tag,FieldLabel.OPTIONAL,"string",jsonFullKey,undefined,undefined,undefined,undefined,undefined,obj,undefined)}static repeatedStringEnum(tagOrJsonFullKey,tagOrObj,maybeObj){const{tag,jsonFullKey,other1:obj}=getOptions(tagOrJsonFullKey,tagOrObj,maybeObj);return makeFieldConfig(tag,FieldLabel.REPEATED,"string",jsonFullKey,undefined,undefined,undefined,undefined,undefined,obj,undefined)}static createMessage(schema,options={}){const init=memoize((()=>{const fields=schema();const fieldNames=Object.keys(fields);const fieldsByTag={};const constantsByTag={};for(let i=0;i{throw new TypeError(`Unproducible oneof case ${pathTrace(path)}`)}:(message,path)=>{if(message==null||typeof message!=="object")throw new TypeError(`Expected type object, found: ${moreSpecificTypeof(message)} ${pathTrace(path)}`);const{fieldMetadata}=init();const res={};for(let i=0;i{const config=schema();const discriminatorKey=Object.keys(config)[0];let discriminatorTag;let discriminatorJsonKeyEncodings;const nameToObject=new Map;const serializedToObject=new Map;const tagToObject=new Map;for(let i=0;i{const{discriminatorKey,nameToObject}=init();const type=t[discriminatorKey];const obj=nameToObject.get(type);if(!obj)throw new TypeError(`Unknown oneof deserialized case: ${JSON.stringify(type)} ${pathTrace(path)}`);return obj.serializeWithPath(t,path)};const deserializeWithPath=(o,path)=>{const{serializedToObject,discriminatorJsonKeyEncodings,defaultObject}=init();const{primaryJsonKey,secondaryJsonKey}=discriminatorJsonKeyEncodings;let type=o[primaryJsonKey];if(type==null&&secondaryJsonKey)type=o[secondaryJsonKey];if(type==null&&defaultObject)return defaultObject.deserializeWithPath(o,path);const obj=serializedToObject.get(type);if(!obj)throw new TypeError(`Unknown oneof serialized case: ${JSON.stringify(type)} ${pathTrace(path)}`);return obj.deserializeWithPath(o,path)};return{init,serialize:t=>serializeWithPath(t,[]),serializeWithPath,deserialize:o=>deserializeWithPath(o,[]),deserializeWithPath}}static createEnumUtil(schema,baseNumber=0,options={}){const init=memoize((()=>{const config=schema();const values=[];const serializedToValue=new Map;const valueToSerialized=new Map;const valueToProtobufSerialized=new Map;const protobufSerializedToValue=new Map;const unproducible=new Set;let i=0;let index=1;while(i{const{unproducible}=init();if(unproducible&&unproducible.has(value))throw new TypeError(`Unproducible enum value: ${JSON.stringify(value)} ${path?pathTrace(path):""}`);const serialized=map.get(value);if(serialized==null)throw new TypeError(`The proto enum serializer failed to serialize value ${JSON.stringify(value)} into JSON.\nIt does not recognize value ${JSON.stringify(value)} as a valid member of the TypeScript enum.\n${path?pathTrace(path):""}`);return serialized};const deserializeWithPath=(jsonValue,path)=>{const value=init().serializedToValue.get(jsonValue);if(value==null)throw new TypeError(`The proto enum deserializer failed to deserialize JSON ${JSON.stringify(jsonValue)} into an enum value.\nIt does not recognize JSON ${JSON.stringify(jsonValue)} as a valid JSON value encoding of the enum.\n${pathTrace(path)}`);return value};return{values:()=>init().values,producibleValues:()=>{const{values,unproducible}=init();if(unproducible==null)return values;return values.filter((value=>!unproducible.has(value)))},serialize:value=>getSerialized(value,init().valueToSerialized,[]),serializeWithPath:(value,path)=>getSerialized(value,init().valueToSerialized,path),deserialize:jsonValue=>deserializeWithPath(jsonValue,[]),deserializeWithPath}}}Proto.requiredDouble=(a,b,c)=>{const{tag,jsonFullKey,other1}=getOptions(a,b,c);return requiredField(ProtoType.DOUBLE,jsonFullKey,tag,other1)};Proto.requiredInt32=(a,b,c)=>{const{tag,jsonFullKey,other1}=getOptions(a,b,c);return requiredField(ProtoType.INT32,jsonFullKey,tag,other1)};Proto.requiredInt64=(a,b,c)=>{const{tag,jsonFullKey,other1}=getOptions(a,b,c);return requiredField(ProtoType.INT64,jsonFullKey,tag,other1)};Proto.optionalDouble=(a,b)=>{const{tag,jsonFullKey}=getOptions(a,b);return optionalField(ProtoType.DOUBLE,jsonFullKey,tag)};Proto.optionalInt32=(a,b)=>{const{tag,jsonFullKey}=getOptions(a,b);return optionalField(ProtoType.INT32,jsonFullKey,tag)};Proto.optionalInt64=(a,b)=>{const{tag,jsonFullKey}=getOptions(a,b);return optionalField(ProtoType.INT64,jsonFullKey,tag)};Proto.repeatedDouble=(a,b)=>{const{tag,jsonFullKey}=getOptions(a,b);return repeatedField(ProtoType.DOUBLE,jsonFullKey,tag)};Proto.repeatedInt32=(a,b)=>{const{tag,jsonFullKey}=getOptions(a,b);return repeatedField(ProtoType.INT32,jsonFullKey,tag)};Proto.repeatedInt64=(a,b)=>{const{tag,jsonFullKey}=getOptions(a,b);return repeatedField(ProtoType.INT64,jsonFullKey,tag)};Proto.requiredString=(a,b,c)=>{const{tag,jsonFullKey,other1}=getOptions(a,b,c);return requiredField(ProtoType.STRING,jsonFullKey,tag,other1)};Proto.optionalString=(a,b)=>{const{tag,jsonFullKey}=getOptions(a,b);return optionalField(ProtoType.STRING,jsonFullKey,tag)};Proto.repeatedString=(a,b)=>{const{tag,jsonFullKey}=getOptions(a,b);return repeatedField(ProtoType.STRING,jsonFullKey,tag)};Proto.requiredBoolean=(a,b,c)=>{const{tag,jsonFullKey,other1}=getOptions(a,b,c);return requiredField(ProtoType.BOOLEAN,jsonFullKey,tag,other1)};Proto.optionalBoolean=(a,b)=>{const{tag,jsonFullKey}=getOptions(a,b);return optionalField(ProtoType.BOOLEAN,jsonFullKey,tag)};Proto.repeatedBoolean=(a,b)=>{const{tag,jsonFullKey}=getOptions(a,b);return repeatedField(ProtoType.BOOLEAN,jsonFullKey,tag)};Proto.requiredBytes=(a,b,c)=>{const{tag,jsonFullKey,other1}=getOptions(a,b,c);return requiredField(ProtoType.BYTES,jsonFullKey,tag,other1)};Proto.optionalBytes=(a,b)=>{const{tag,jsonFullKey}=getOptions(a,b);return optionalField(ProtoType.BYTES,jsonFullKey,tag)};Proto.repeatedBytes=(a,b)=>{const{tag,jsonFullKey}=getOptions(a,b);return repeatedField(ProtoType.BYTES,jsonFullKey,tag)};Proto.booleanInt64Map=mapField(ProtoType.BOOLEAN,ProtoType.INT64);Proto.int32Int32Map=mapField(ProtoType.INT32,ProtoType.INT32);Proto.int32Int64Map=mapField(ProtoType.INT32,ProtoType.INT64);Proto.int32BoolMap=mapField(ProtoType.INT32,ProtoType.BOOLEAN);Proto.int32DoubleMap=mapField(ProtoType.INT32,ProtoType.DOUBLE);Proto.int32StringMap=mapField(ProtoType.INT32,ProtoType.STRING);Proto.int32StringEnumMap=mapField(ProtoType.INT32,"enum");Proto.int32ObjectMap=mapField(ProtoType.INT32,"object");Proto.int32BytesMap=mapField(ProtoType.INT32,ProtoType.BYTES);Proto.int64Int32Map=mapField(ProtoType.INT64,ProtoType.INT32);Proto.int64Int64Map=mapField(ProtoType.INT64,ProtoType.INT64);Proto.int64BooleanMap=mapField(ProtoType.INT64,ProtoType.BOOLEAN);Proto.int64DoubleMap=mapField(ProtoType.INT64,ProtoType.DOUBLE);Proto.int64StringMap=mapField(ProtoType.INT64,ProtoType.STRING);Proto.int64StringEnumMap=mapField(ProtoType.INT64,"enum");Proto.int64ObjectMap=mapField(ProtoType.INT64,"object");Proto.int64BytesMap=mapField(ProtoType.INT64,ProtoType.BYTES);Proto.doubleInt32Map=mapField(ProtoType.DOUBLE,ProtoType.INT32);Proto.doubleInt64Map=mapField(ProtoType.DOUBLE,ProtoType.INT64);Proto.doubleBoolMap=mapField(ProtoType.DOUBLE,ProtoType.BOOLEAN);Proto.doubleDoubleMap=mapField(ProtoType.DOUBLE,ProtoType.DOUBLE);Proto.doubleStringMap=mapField(ProtoType.DOUBLE,ProtoType.STRING);Proto.doubleStringEnumMap=mapField(ProtoType.DOUBLE,"enum");Proto.doubleObjectMap=mapField(ProtoType.DOUBLE,"object");Proto.doubleBytesMap=mapField(ProtoType.DOUBLE,ProtoType.BYTES);Proto.stringInt32Map=mapField(ProtoType.STRING,ProtoType.INT32);Proto.stringInt64Map=mapField(ProtoType.STRING,ProtoType.INT64);Proto.stringBooleanMap=mapField(ProtoType.STRING,ProtoType.BOOLEAN);Proto.stringDoubleMap=mapField(ProtoType.STRING,ProtoType.DOUBLE);Proto.stringStringMap=mapField(ProtoType.STRING,ProtoType.STRING);Proto.stringStringEnumMap=mapField(ProtoType.STRING,"enum");Proto.stringObjectMap=mapField(ProtoType.STRING,"object");Proto.stringBytesMap=mapField(ProtoType.STRING,ProtoType.BYTES);function deriveFieldMetadata(fields,dualDeserializationConfig){return Object.entries(fields).map((([name,config])=>{const fieldEncodings=deriveFieldEncodings(config,dualDeserializationConfig);return{config,name,primaryJsonKey:fieldEncodings.keyEncodings.primaryJsonKey,secondaryJsonKey:fieldEncodings.keyEncodings.secondaryJsonKey,primaryJsonValue:fieldEncodings.valueEncodings?.primaryJsonValue,secondaryJsonValue:fieldEncodings.valueEncodings?.secondaryJsonValue}}))}function deriveFieldEncodings(fieldConfig,dualDeserializationConfig){let valueEncodings;let jsonMiniKey=toJsonMini(fieldConfig.tag-1);if(fieldConfig.fieldLabel===FieldLabel.CONSTANT){const{primary:primaryJsonValue,secondary:secondaryJsonValue}=choosePrimaryAndSecondaryJSONFromConfig(jsonMiniKey,fieldConfig.jsonFullValue,dualDeserializationConfig);jsonMiniKey=DISCRIMINATOR_JSON_MINI_KEY;valueEncodings={primaryJsonValue,secondaryJsonValue}}const{primary:primaryJsonKey,secondary:secondaryJsonKey}=choosePrimaryAndSecondaryJSONFromConfig(jsonMiniKey,fieldConfig.jsonFullKey,dualDeserializationConfig);const keyEncodings={primaryJsonKey,secondaryJsonKey};return{keyEncodings,valueEncodings}}function choosePrimaryAndSecondaryJSONFromConfig(jsonMini,jsonFull,dualDeserializationConfig){if(!jsonFull){if(dualDeserializationConfig!==undefined)throw new Error("Dual Deserialization config templated but JSON full key/value wasn't");return{primary:jsonMini,secondary:undefined}}if(dualDeserializationConfig===undefined)return{primary:jsonFull,secondary:undefined};else if(dualDeserializationConfig===0)return{primary:jsonMini,secondary:jsonFull};else if(dualDeserializationConfig===1)return{primary:jsonFull,secondary:jsonMini};throw new Error("function should have been exhaustive, but wasn't")}function makeRepeatedTypeError(keyEncodings,value,expectedType,path){return new TypeError(`Expected repeated ${expectedType} value for key ${expectedKeys(keyEncodings)}, found: ${moreSpecificTypeof(value)} ${pathTrace(path)}`)}function makeOptionalTypeError(keyEncodings,value,expectedType,path){return new TypeError(`Expected optional ${expectedType} value for key ${expectedKeys(keyEncodings)}, found: ${moreSpecificTypeof(value)} ${pathTrace(path)}`)}function makeRequiredTypeError(keyEncodings,value,expectedType,path,index){const atIndex=index!==undefined?` at index ${index}`:"";return new TypeError(`Expected ${expectedType} value${atIndex} for key ${expectedKeys(keyEncodings)}, found: ${moreSpecificTypeof(value)} ${pathTrace(path)}`)}function expectedKeys(keyEncodings){const{primaryJsonKey,secondaryJsonKey}=keyEncodings;if(secondaryJsonKey)return`either "${primaryJsonKey}" OR "${secondaryJsonKey}"`;return`"${primaryJsonKey}"`}function expectedValues(valueEncodings){const{primaryJsonValue,secondaryJsonValue}=valueEncodings;if(secondaryJsonValue)return`either "${primaryJsonValue}" OR "${secondaryJsonValue}"`;return`"${primaryJsonValue}"`}function pathTrace(path){return`(path: .${path.join(".")})`}function moreSpecificTypeof(value){if(value===null)return"null";if(Array.isArray(value))return"array";return typeof value}const DualDeserializationConfig={MINI_PRIMARY_FULL_SECONDARY:0,FULL_PRIMARY_MINI_SECONDARY:1};const DISCRIMINATOR_JSON_MINI_KEY="A?";const JSON_MINI_ALPHABET="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";function toJsonMini(x){if(x0){builder.push(JSON_MINI_ALPHABET.charAt(x%JSON_MINI_ALPHABET.length));x=Math.floor(x/JSON_MINI_ALPHABET.length)}return builder.reverse().join("")}}function getOptions(tagOrJsonFullKey,tagOrOther1,other1OrOther2,maybeOther2){if(typeof tagOrJsonFullKey==="string")return{jsonFullKey:tagOrJsonFullKey,tag:tagOrOther1,other1:other1OrOther2,other2:maybeOther2};else return{tag:tagOrJsonFullKey,other1:tagOrOther1,other2:other1OrOther2}}function isCorrectWireType(value,typeOfValue){return typeof value===typeOfValue||isCorrectBytesWireType(value,typeOfValue)}function isCorrectBytesWireType(value,typeOfValue){return typeOfValue==="Uint8Array"&&typeof value==="string"}function toBase64(bytes){const binString=Array.from(bytes,(byte=>String.fromCodePoint(byte))).join("");return btoa(binString)}function fromBase64(base64){return Uint8Array.from(atob(base64),(m=>m.codePointAt(0)))}const AnimationDirection={AUTO:1,UP:2,DOWN:3,LEFT:4,RIGHT:5};const AnimationDirectionUtil=Proto.createEnumUtil((()=>[1,2,3,4,5]),1);const AnimationTextUnit={CHARACTER:1,WORD:2,LINE:3,PARAGRAPH:4,ELEMENT:5};const AnimationTextUnitUtil=Proto.createEnumUtil((()=>[1,2,3,4,5]),1);const AnimationTimingMode={EXACT:1,TEXT_ATTRIBUTE:2};const AnimationTimingModeUtil=Proto.createEnumUtil((()=>[1,2]),1);const AnimationConfigProto=Proto.createMessage((()=>({intensity:Proto.optionalDouble(1),scale:Proto.optionalDouble(2),direction:Proto.optionalStringEnum(3,AnimationDirectionUtil),textUnit:Proto.optionalStringEnum(4,AnimationTextUnitUtil),color:Proto.optionalString(5),timingMode:Proto.optionalStringEnum(10,AnimationTimingModeUtil),intro:Proto.optionalObject(7,AnimationIntroProto),outro:Proto.optionalObject(8,AnimationOutroProto),animationPath:Proto.optionalObject(9,AnimationPathProto)})));const AnimationIntroProto=Proto.createMessage((()=>({durationUs:Proto.optionalDouble(1),mask:Proto.optionalObject(3,AnimationMaskProto)})));const AnimationOutroProto=Proto.createMessage((()=>({durationUs:Proto.optionalDouble(1),mask:Proto.optionalObject(3,AnimationMaskProto),reverse:Proto.optionalBoolean(2)})));const AnimationMaskProto=Proto.createMessage((()=>({video:Proto.requiredString(1)})));const AnimationPathEasing={TIMED:1,LINEAR:2,EASE_IN:3,EASE_OUT:4,EASE_BOTH:5};const AnimationPathEasingUtil=Proto.createEnumUtil((()=>[1,2,3,4,5]));const AnimationPathProto=Proto.createMessage((()=>({dxs:Proto.repeatedInt32(1),dys:Proto.repeatedInt32(2),dts:Proto.repeatedInt32(3),easing:Proto.requiredStringEnum(4,AnimationPathEasingUtil),durationUs:Proto.optionalInt64(5),orientToPath:Proto.requiredBoolean(6)})));const RepeatingAnimationsProto=Proto.createMessage((()=>({rotate:Proto.optionalObject(1,RotateRepeatingAnimationProto),flicker:Proto.optionalObject(2,FlickerRepeatingAnimationProto),pulse:Proto.optionalObject(3,PulseRepeatingAnimationProto),wiggle:Proto.optionalObject(4,WiggleRepeatingAnimationProto)})));const RotateRepeatingAnimationDirection={CLOCKWISE:1,ANTICLOCKWISE:2};const RotateRepeatingAnimationDirectionUtil=Proto.createEnumUtil((()=>[1,2]),1);const RotateRepeatingAnimationProto=Proto.createMessage((()=>({intensity:Proto.requiredDouble(1),direction:Proto.requiredStringEnum(2,RotateRepeatingAnimationDirectionUtil)})));const FlickerRepeatingAnimationProto=Proto.createMessage((()=>({intensity:Proto.requiredDouble(1),randomise:Proto.requiredBoolean(2)})));const PulseRepeatingAnimationDirection={IN:1,OUT:2};const PulseRepeatingAnimationDirectionUtil=Proto.createEnumUtil((()=>[1,2]),1);const PulseRepeatingAnimationProto=Proto.createMessage((()=>({intensity:Proto.requiredDouble(1),direction:Proto.requiredStringEnum(2,PulseRepeatingAnimationDirectionUtil)})));const WiggleRepeatingAnimationProto=Proto.createMessage((()=>({intensity:Proto.requiredDouble(1)})));const Consequence={ANIMATE_IN:1};const ConsequenceUtil=Proto.createEnumUtil((()=>[1]));const Trigger={CLICK:1};const TriggerUtil=Proto.createEnumUtil((()=>[1]));const AnimationSequenceStepProto=Proto.createMessage((()=>({anchorRef:Proto.requiredString(1),trigger:Proto.requiredStringEnum(2,TriggerUtil),consequence:Proto.requiredStringEnum(3,ConsequenceUtil)})));const ElementAnimationProtoUnionFields=()=>({});const ElementAnimationProto=Proto.createOneof((()=>({type:[1,NoneElementAnimationProto,2,SequencedElementAnimationProto,3,IndependentElementAnimationProto]})),ElementAnimationProtoUnionFields);const NoneElementAnimationProto=Proto.createMessage((()=>({...ElementAnimationProtoUnionFields(),type:Proto.constantString("A?",1,"NONE")})));const SequencedElementAnimationProto=Proto.createMessage((()=>({...ElementAnimationProtoUnionFields(),type:Proto.constantString("A?",2,"SEQUENCED"),animation:Proto.requiredInt32(1),animationConfig:Proto.optionalObject(2,AnimationConfigProto)})));const IndependentElementAnimationProto=Proto.createMessage((()=>({...ElementAnimationProtoUnionFields(),type:Proto.constantString("A?",3,"INDEPENDENT"),animation:Proto.requiredInt32(1),animationConfig:Proto.optionalObject(2,AnimationConfigProto)})));const InterpolationMode={LINEAR:1,SINE:2,CUBIC_IN:3,CUBIC_OUT:4};const InterpolationModeUtil=Proto.createEnumUtil((()=>[0,1,2,3]));const OverlayTiming={RELATIVE_TIMING:1,PAGE_TIMING:2};const OverlayTimingUtil=Proto.createEnumUtil((()=>[0,1]));const VerticalDirection={UP:1,DOWN:2};const VerticalDirectionUtil=Proto.createEnumUtil((()=>[0,1]));const VideoEffectProtoUnionFields=()=>({startMs:Proto.requiredInt32(1),durationMs:Proto.optionalInt32(2),strengthKeyframes:Proto.int32ObjectMap(3,DoubleValuedKeyframeProto)});const VideoEffectProto=Proto.createOneof((()=>({type:[4,BrightnessEffectProto,5,ContrastEffectProto,6,HighlightsEffectProto,7,ShadowsEffectProto,8,WhitesEffectProto,9,BlacksEffectProto,10,SaturationEffectProto,11,VibranceEffectProto,12,TemperatureEffectProto,13,TintEffectProto,14,LutEffectProto,15,FisheyeEffectProto,16,VhsEffectProto,17,LightLeakEffectProto,18,OldTvEffectProto,19,BlackAndWhiteFilmEffectProto,20,CrtEffectProto]})),VideoEffectProtoUnionFields);const BrightnessEffectProto=Proto.createMessage((()=>({...VideoEffectProtoUnionFields(),type:Proto.constantString("A?",4,"BRIGHTNESS_EFFECT")})));const ContrastEffectProto=Proto.createMessage((()=>({...VideoEffectProtoUnionFields(),type:Proto.constantString("A?",5,"CONTRAST_EFFECT")})));const HighlightsEffectProto=Proto.createMessage((()=>({...VideoEffectProtoUnionFields(),type:Proto.constantString("A?",6,"HIGHLIGHTS_EFFECT")})));const ShadowsEffectProto=Proto.createMessage((()=>({...VideoEffectProtoUnionFields(),type:Proto.constantString("A?",7,"SHADOWS_EFFECT")})));const WhitesEffectProto=Proto.createMessage((()=>({...VideoEffectProtoUnionFields(),type:Proto.constantString("A?",8,"WHITES_EFFECT")})));const BlacksEffectProto=Proto.createMessage((()=>({...VideoEffectProtoUnionFields(),type:Proto.constantString("A?",9,"BLACKS_EFFECT")})));const SaturationEffectProto=Proto.createMessage((()=>({...VideoEffectProtoUnionFields(),type:Proto.constantString("A?",10,"SATURATION_EFFECT")})));const VibranceEffectProto=Proto.createMessage((()=>({...VideoEffectProtoUnionFields(),type:Proto.constantString("A?",11,"VIBRANCE_EFFECT")})));const TemperatureEffectProto=Proto.createMessage((()=>({...VideoEffectProtoUnionFields(),type:Proto.constantString("A?",12,"TEMPERATURE_EFFECT")})));const TintEffectProto=Proto.createMessage((()=>({...VideoEffectProtoUnionFields(),type:Proto.constantString("A?",13,"TINT_EFFECT")})));const LutEffectProto=Proto.createMessage((()=>({...VideoEffectProtoUnionFields(),type:Proto.constantString("A?",14,"LUT_EFFECT"),lut:Proto.requiredObject(51,LutRefProto)})));const FisheyeEffectProto=Proto.createMessage((()=>({...VideoEffectProtoUnionFields(),type:Proto.constantString("A?",15,"FISHEYE_EFFECT"),curvatureRadius:Proto.requiredDouble(52),backgroundColor:Proto.optionalString(53),warpAmount:Proto.requiredDouble(54)})));const VhsEffectProto=Proto.createMessage((()=>({...VideoEffectProtoUnionFields(),type:Proto.constantString("A?",16,"VHS_EFFECT"),scanlineLoopDurationMs:Proto.requiredInt32(55),degradationIntensity:Proto.requiredDouble(56),bandDirection:Proto.requiredStringEnum(57,VerticalDirectionUtil),overlayTiming:Proto.optionalStringEnum(58,OverlayTimingUtil)})));const LightLeakEffectProto=Proto.createMessage((()=>({...VideoEffectProtoUnionFields(),type:Proto.constantString("A?",17,"LIGHT_LEAK_EFFECT"),colors:Proto.repeatedString(59),seed:Proto.requiredInt32(60),angle:Proto.requiredDouble(61),stretch:Proto.requiredDouble(62)})));const OldTvEffectProto=Proto.createMessage((()=>({...VideoEffectProtoUnionFields(),type:Proto.constantString("A?",18,"OLD_TV_EFFECT"),distortionIntensity:Proto.requiredDouble(63),scanlineDirection:Proto.requiredStringEnum(64,VerticalDirectionUtil),scanlineLoopDurationMs:Proto.requiredDouble(65)})));const BlackAndWhiteFilmEffectProto=Proto.createMessage((()=>({...VideoEffectProtoUnionFields(),type:Proto.constantString("A?",19,"BLACK_AND_WHITE_FILM_EFFECT"),degradationIntensity:Proto.requiredDouble(66),cameraShakeIntensity:Proto.requiredDouble(67),dustArtifactsColor:Proto.requiredString(68)})));const CrtEffectProto=Proto.createMessage((()=>({...VideoEffectProtoUnionFields(),type:Proto.constantString("A?",20,"CRT_EFFECT"),distortionIntensity:Proto.requiredDouble(69)})));const DoubleValuedKeyframeProto=Proto.createMessage((()=>({interpolationMode:Proto.requiredStringEnum(1,InterpolationModeUtil,1),value:Proto.requiredDouble(2)})));const LutRefProto=Proto.createMessage((()=>({id:Proto.requiredString(1)})));const AudioEffectProtoUnionFields=()=>({startUs:Proto.requiredInt64(1),durationUs:Proto.optionalInt64(2),strengthKeyframes:Proto.int64ObjectMap(3,DoubleValuedKeyframeProto)});const AudioEffectProto=Proto.createOneof((()=>({type:[4,GainAudioEffectProto,5,DuckingAudioEffectProto]})),AudioEffectProtoUnionFields);const GainAudioEffectProto=Proto.createMessage((()=>({...AudioEffectProtoUnionFields(),type:Proto.constantString("A?",4,"GAIN"),maxGainDb:Proto.requiredDouble(51)})));const DuckingAudioEffectProto=Proto.createMessage((()=>({...AudioEffectProtoUnionFields(),type:Proto.constantString("A?",5,"DUCKING"),attenuationDb:Proto.requiredDouble(51),attackDurationUs:Proto.requiredInt64(52),releaseDurationUs:Proto.requiredInt64(53),holdDurationUs:Proto.requiredInt64(54),interpolationMode:Proto.requiredStringEnum(55,InterpolationModeUtil)})));const BlockAlignment={START:1,MIDDLE:2,END:3};const BlockAlignmentUtil=Proto.createEnumUtil((()=>[1,2,3]),1);const ResourceType={FONT:1,MEDIA:2,VIDEO:3,AUDIO:4,EMBED:5,SCENE:6,MOTION_GRAPHIC:7,BLUEPRINT:8};const ResourceTypeUtil=Proto.createEnumUtil((()=>[1,2,3,4,5,6,8,{unproducible:true},7]));const EntityIdType={DOCUMENT_BLUEPRINT:1,PAGE:2,ELEMENT:3,ITEM:4,TEXT_INTERNAL:5,SHEET_INTERNAL:6,AUDIO_TRACK:7,VIDEO_FILL:8,VARIABLE:9};const EntityIdTypeUtil=Proto.createEnumUtil((()=>[1,2,3,4,5,6,7,8,9]));const LoopMode={NONE:1,REPEAT:2};const LoopModeUtil=Proto.createEnumUtil((()=>[1,2]),1);const VariableType={DOUBLE:1,NON_NEGATIVE_DOUBLE:2,STRING:3,BOOLEAN:4,IMAGE_OR_VIDEO:5,RICHTEXT2:6,POINT:7,POSITIONED_ELEMENT_ANCHOR:8,COLOR_OR_GRADIENT:9};const VariableTypeUtil=Proto.createEnumUtil((()=>[1,2,3,4,5,6,7,8,9]),1);const UnaryConditionOperator={PRESENT:1,ABSENT:2};const UnaryConditionOperatorUtil=Proto.createEnumUtil((()=>[1,2]));const BinaryConditionOperator={EQUAL:1,NOT_EQUAL:2,LESS_THAN:3,LESS_THAN_OR_EQUAL_TO:4,GREATER_THAN:5,GREATER_THAN_OR_EQUAL_TO:6,CONTAINS:7,NOT_CONTAINS:8};const BinaryConditionOperatorUtil=Proto.createEnumUtil((()=>[1,2,3,4,5,6,7,8]));const AlignedBoxProto=Proto.createMessage((()=>({top:Proto.requiredDouble(1),left:Proto.requiredDouble(2),width:Proto.requiredDouble(4),height:Proto.requiredDouble(3)})));const AlignedBox2Proto=Proto.createMessage((()=>({top:Proto.requiredDouble(1),left:Proto.requiredDouble(2),width:Proto.requiredDouble(3),height:Proto.requiredDouble(4)})));const AltTextProto=Proto.createMessage((()=>({text:Proto.requiredString(1),decorative:Proto.requiredBoolean(2)})));const PointProto=Proto.createMessage((()=>({top:Proto.requiredDouble(1),left:Proto.requiredDouble(2)})));const ContentDimensionsProto=Proto.createMessage((()=>({width:Proto.requiredDouble(1),height:Proto.requiredDouble(2)})));const RefProto=Proto.createMessage((()=>({id:Proto.requiredString(1),version:Proto.requiredInt32(2)})));const ResourceRefProtoUnionFields=()=>({});const ResourceRefProto=Proto.createOneof((()=>({type:[30,ResolvedRefProto,31,UnresolvedRefProto]})),ResourceRefProtoUnionFields,{defaultCase:()=>ResolvedRefProto});const ResolvedRefProto=Proto.createMessage((()=>({...ResourceRefProtoUnionFields(),type:Proto.constantStringWithDefault("A?",30,"RESOLVED"),id:Proto.requiredString(1),version:Proto.requiredInt32(2)})));const UnresolvedRefProto=Proto.createMessage((()=>({...ResourceRefProtoUnionFields(),type:Proto.constantString("A?",31,"UNRESOLVED"),token:Proto.requiredString(3)})));const TypedResourceRefProto=Proto.createMessage((()=>({id:Proto.requiredString(1),version:Proto.requiredInt32(2),type:Proto.requiredStringEnum(3,ResourceTypeUtil)})));const EntityRefProto=Proto.createMessage((()=>({id:Proto.requiredString(1),type:Proto.requiredStringEnum(2,EntityIdTypeUtil)})));const AppConfigProto=Proto.createMessage((()=>({app:Proto.requiredObject(1,RefProto),atomicData:Proto.stringStringMap(2)})));const MentionProto=Proto.createMessage((()=>({text:Proto.requiredString(1),user:Proto.requiredString(2),brand:Proto.requiredString(3)})));const EmbedProto=Proto.createMessage((()=>({text:Proto.requiredString(1),url:Proto.requiredString(2)})));const UnitProto=Proto.createMessage((()=>({})));const VariableBindingProto=Proto.createMessage((()=>({variable:Proto.requiredString(1)})));const VariableSpecProto=Proto.createMessage((()=>({variable:Proto.requiredObject(1,VariableTypeProto)})));const VariableTypeProto=Proto.createMessage((()=>({type:Proto.requiredStringEnum(1,VariableTypeUtil)})));const ConditionProtoUnionFields=()=>({});const ConditionProto=Proto.createOneof((()=>({type:[1,UnaryConditionProto,2,BinaryConditionProto]})),ConditionProtoUnionFields);const UnaryConditionProto=Proto.createMessage((()=>({...ConditionProtoUnionFields(),type:Proto.constantString("A?",1,"UNARY"),operator:Proto.requiredStringEnum(31,UnaryConditionOperatorUtil)})));const BinaryConditionProto=Proto.createMessage((()=>({...ConditionProtoUnionFields(),type:Proto.constantString("A?",2,"BINARY"),operator:Proto.requiredStringEnum(32,BinaryConditionOperatorUtil),value:Proto.requiredObject(33,ConditionValueProto)})));const ConditionValueProtoUnionFields=()=>({});const ConditionValueProto=Proto.createOneof((()=>({type:[1,ConditionBooleanValueProto,2,ConditionNumberValueProto,3,ConditionTextValueProto,4,ConditionAbsoluteDateValueProto]})),ConditionValueProtoUnionFields);const ConditionBooleanValueProto=Proto.createMessage((()=>({...ConditionValueProtoUnionFields(),type:Proto.constantString("A?",1,"BOOLEAN"),value:Proto.requiredBoolean(31)})));const ConditionNumberValueProto=Proto.createMessage((()=>({...ConditionValueProtoUnionFields(),type:Proto.constantString("A?",2,"NUMBER"),value:Proto.requiredDouble(32)})));const ConditionTextValueProto=Proto.createMessage((()=>({...ConditionValueProtoUnionFields(),type:Proto.constantString("A?",3,"TEXT"),value:Proto.requiredString(33)})));const ConditionAbsoluteDateValueProto=Proto.createMessage((()=>({...ConditionValueProtoUnionFields(),type:Proto.constantString("A?",4,"ABSOLUTE_DATE"),value:Proto.requiredInt64(34)})));const AudioProto=Proto.createMessage((()=>({tracks:Proto.repeatedObject(1,AudioTrackProto),trackTombstones:Proto.repeatedInt32(2)})));const AudioTrackProto=Proto.createMessage((()=>({audio:Proto.requiredString(1),id:Proto.optionalString(9),trim:Proto.optionalObject(2,AudioTrimProto),loop:Proto.requiredStringEnum(3,LoopModeUtil,LoopMode.REPEAT),volume:Proto.requiredDouble(4,1),startUs:Proto.optionalDouble(5),durationUs:Proto.optionalDouble(6),fadeIn:Proto.optionalObject(7,FadeAudioEffectProto),fadeOut:Proto.optionalObject(8,FadeAudioEffectProto),audioEffects:Proto.repeatedObject(10,AudioEffectProto),audioEffectTombstones:Proto.repeatedInt32(11)})));const AudioTrimProto=Proto.createMessage((()=>({startUs:Proto.requiredDouble(1),endUs:Proto.requiredDouble(2)})));const FadeAudioEffectProto=Proto.createMessage((()=>({durationUs:Proto.requiredDouble(1),easing:Proto.requiredObject(2,AudioEffectEasingProto)})));const AudioEffectEasingProtoUnionFields=()=>({});const AudioEffectEasingProto=Proto.createOneof((()=>({type:[1,LogisticSigmoidProto]})),AudioEffectEasingProtoUnionFields);const LogisticSigmoidProto=Proto.createMessage((()=>({...AudioEffectEasingProtoUnionFields(),type:Proto.constantString("A?",1,"LOGISTIC_SIGMOID")})));const AudioFadeProto=Proto.createMessage((()=>({fadeIn:Proto.optionalObject(1,FadeAudioEffectProto),fadeOut:Proto.optionalObject(2,FadeAudioEffectProto)})));const TransitionProtoUnionFields=()=>({durationUs:Proto.requiredDouble(2)});const TransitionProto=Proto.createOneof((()=>({type:[27,CrossDissolveTransitionProto,28,SlideTransitionProto,29,WipeCircleTransitionProto,30,WipeLineTransitionProto,31,MatchTransitionProto,32,StackTransitionProto,33,ChopTransitionProto,34,ColorWipeTransitionProto,35,FlowTransitionProto,36,Reserved36TransitionProto,37,Reserved37TransitionProto,38,Reserved38TransitionProto,39,Reserved39TransitionProto,40,Reserved40TransitionProto,41,Reserved41TransitionProto,42,Reserved42TransitionProto,43,Reserved43TransitionProto,44,Reserved44TransitionProto,45,Reserved45TransitionProto,46,Reserved46TransitionProto]})),TransitionProtoUnionFields);const CrossDissolveTransitionProto=Proto.createMessage((()=>({...TransitionProtoUnionFields(),type:Proto.constantString("A?",27,"CROSS_DISSOLVE")})));const SlideTransitionDirection={UP:1,LEFT:2,DOWN:3,RIGHT:4};const SlideTransitionDirectionUtil=Proto.createEnumUtil((()=>[1,2,3,4]),1);const SlideTransitionProto=Proto.createMessage((()=>({...TransitionProtoUnionFields(),type:Proto.constantString("A?",28,"SLIDE"),direction:Proto.requiredStringEnum(27,SlideTransitionDirectionUtil)})));const WipeCircleTransitionDirection={INWARDS:1,OUTWARDS:2};const WipeCircleTransitionDirectionUtil=Proto.createEnumUtil((()=>[1,2]),1);const WipeCircleTransitionProto=Proto.createMessage((()=>({...TransitionProtoUnionFields(),type:Proto.constantString("A?",29,"WIPE_CIRCLE"),direction:Proto.requiredStringEnum(27,WipeCircleTransitionDirectionUtil)})));const WipeLineTransitionDirection={UP:1,LEFT:2,DOWN:3,RIGHT:4};const WipeLineTransitionDirectionUtil=Proto.createEnumUtil((()=>[1,2,3,4]),1);const WipeLineTransitionProto=Proto.createMessage((()=>({...TransitionProtoUnionFields(),type:Proto.constantString("A?",30,"WIPE_LINE"),direction:Proto.requiredStringEnum(27,WipeLineTransitionDirectionUtil)})));const MatchTransitionProto=Proto.createMessage((()=>({...TransitionProtoUnionFields(),type:Proto.constantString("A?",31,"MATCH")})));const StackTransitionDirection={UP:1,LEFT:2,DOWN:3,RIGHT:4};const StackTransitionDirectionUtil=Proto.createEnumUtil((()=>[1,2,3,4]));const StackTransitionProto=Proto.createMessage((()=>({...TransitionProtoUnionFields(),type:Proto.constantString("A?",32,"STACK"),direction:Proto.requiredStringEnum(27,StackTransitionDirectionUtil)})));const ChopTransitionOrigin={TOP_LEFT:1,TOP_RIGHT:2,BOTTOM_LEFT:3,BOTTOM_RIGHT:4};const ChopTransitionOriginUtil=Proto.createEnumUtil((()=>[1,2,3,4]));const ChopTransitionDirection={CLOCKWISE:1,ANTICLOCKWISE:2};const ChopTransitionDirectionUtil=Proto.createEnumUtil((()=>[1,2]));const ChopTransitionProto=Proto.createMessage((()=>({...TransitionProtoUnionFields(),type:Proto.constantString("A?",33,"CHOP"),origin:Proto.requiredStringEnum(27,ChopTransitionOriginUtil),direction:Proto.requiredStringEnum(28,ChopTransitionDirectionUtil)})));const ColorWipeTransitionDirection={UP:1,LEFT:2,DOWN:3,RIGHT:4,UP_LEFT:5,UP_RIGHT:6,DOWN_LEFT:7,DOWN_RIGHT:8};const ColorWipeTransitionDirectionUtil=Proto.createEnumUtil((()=>[1,2,3,4,5,6,7,8]));const ColorWipeTransitionProto=Proto.createMessage((()=>({...TransitionProtoUnionFields(),type:Proto.constantString("A?",34,"COLOR_WIPE"),colors:Proto.repeatedString(27),direction:Proto.requiredStringEnum(28,ColorWipeTransitionDirectionUtil)})));const FlowTransitionDirection={UP:1,LEFT:2,DOWN:3,RIGHT:4};const FlowTransitionDirectionUtil=Proto.createEnumUtil((()=>[1,2,3,4]));const FlowTransitionProto=Proto.createMessage((()=>({...TransitionProtoUnionFields(),type:Proto.constantString("A?",35,"FLOW"),direction:Proto.requiredStringEnum(27,FlowTransitionDirectionUtil)})));const Reserved36TransitionProto=Proto.createMessage((()=>({...TransitionProtoUnionFields(),type:Proto.constantString("A?",36,"RESERVED_36")})));const Reserved37TransitionProto=Proto.createMessage((()=>({...TransitionProtoUnionFields(),type:Proto.constantString("A?",37,"RESERVED_37")})));const Reserved38TransitionProto=Proto.createMessage((()=>({...TransitionProtoUnionFields(),type:Proto.constantString("A?",38,"RESERVED_38")})));const Reserved39TransitionProto=Proto.createMessage((()=>({...TransitionProtoUnionFields(),type:Proto.constantString("A?",39,"RESERVED_39")})));const Reserved40TransitionProto=Proto.createMessage((()=>({...TransitionProtoUnionFields(),type:Proto.constantString("A?",40,"RESERVED_40")})));const Reserved41TransitionProto=Proto.createMessage((()=>({...TransitionProtoUnionFields(),type:Proto.constantString("A?",41,"RESERVED_41")})));const Reserved42TransitionProto=Proto.createMessage((()=>({...TransitionProtoUnionFields(),type:Proto.constantString("A?",42,"RESERVED_42")})));const Reserved43TransitionProto=Proto.createMessage((()=>({...TransitionProtoUnionFields(),type:Proto.constantString("A?",43,"RESERVED_43")})));const Reserved44TransitionProto=Proto.createMessage((()=>({...TransitionProtoUnionFields(),type:Proto.constantString("A?",44,"RESERVED_44")})));const Reserved45TransitionProto=Proto.createMessage((()=>({...TransitionProtoUnionFields(),type:Proto.constantString("A?",45,"RESERVED_45")})));const Reserved46TransitionProto=Proto.createMessage((()=>({...TransitionProtoUnionFields(),type:Proto.constantString("A?",46,"RESERVED_46")})));const ImageBoxProto=Proto.createMessage((()=>({top:Proto.requiredDouble(1),left:Proto.requiredDouble(2),width:Proto.requiredDouble(4),height:Proto.requiredDouble(3),rotation:Proto.requiredDouble(5)})));const ImageFilterProto=Proto.createMessage((()=>({preset:Proto.optionalObject(9,ImageFilterPresetProto),brightness:Proto.requiredDouble(1),contrast:Proto.requiredDouble(2),saturation:Proto.requiredDouble(3),tint:Proto.requiredDouble(4),tintAmount:Proto.requiredDouble(5),blur:Proto.requiredDouble(6),xpro:Proto.requiredDouble(8),warmth:Proto.requiredDouble(10),clarity:Proto.requiredDouble(11),vibrance:Proto.requiredDouble(12),highlights:Proto.requiredDouble(13),shadows:Proto.requiredDouble(14),vignette:Proto.requiredDouble(7),fade:Proto.requiredDouble(15)})));const ImageFilterPresetProto=Proto.createMessage((()=>({id:Proto.requiredString(1),intensity:Proto.requiredDouble(2)})));const StrokeProto=Proto.createMessage((()=>({weight:Proto.requiredDouble(1),color:Proto.optionalString(2),fill:Proto.optionalObject(5,FillProto),dashPattern:Proto.repeatedInt32(3),flatCaps:Proto.requiredBoolean(32)})));const FillSequenceProto=Proto.createMessage((()=>({fills:Proto.repeatedObject(1,FillProto),fillTombstones:Proto.repeatedInt32(2)})));const FillVariableReferencesProto=Proto.createMessage((()=>({imageOrVideo:Proto.optionalObject(2,VariableBindingProto),colorOrGradient:Proto.optionalObject(3,VariableBindingProto)})));const FillProto=Proto.createMessage((()=>({dropTarget:Proto.optionalBoolean(1),image:Proto.optionalObject(2,ImageFillProto),video:Proto.optionalObject(9,VideoFillProto),gradient:Proto.optionalObject(11,GradientFillProto),color:Proto.optionalString(3),transparency:Proto.requiredDouble(4),locked:Proto.requiredBoolean(6),preventUnlock:Proto.requiredBoolean(10),contentRole:Proto.optionalString(5),datasetFieldId:Proto.optionalString(12),durationUs:Proto.optionalInt64(14),transition:Proto.optionalObject(13,TransitionProto),flipX:Proto.requiredBoolean(7),flipY:Proto.requiredBoolean(8),variableReferences:Proto.optionalObject(15,FillVariableReferencesProto),animation:Proto.optionalObject(16,ElementAnimationProto),repeatingAnimations:Proto.optionalObject(17,RepeatingAnimationsProto)})));const ImageFillProto=Proto.createMessage((()=>({media:Proto.requiredObject(1,ResourceRefProto),derivedMedia:Proto.optionalObject(9,ResourceRefProto),imageBox:Proto.optionalObject(2,ImageBoxProto),transparency:Proto.requiredDouble(5),recoloring:Proto.stringStringMap(3),filter:Proto.optionalObject(4,ImageFilterProto),altText:Proto.optionalObject(10,AltTextProto)})));const VideoTrimProto=Proto.createMessage((()=>({startUs:Proto.requiredDouble(1),endUs:Proto.requiredDouble(2)})));const VideoFillProto=Proto.createMessage((()=>({video:Proto.requiredString(1),id:Proto.optionalString(13),imageBox:Proto.requiredObject(2,ImageBoxProto),transparency:Proto.requiredDouble(3),recoloring:Proto.stringStringMap(10),filter:Proto.optionalObject(4,ImageFilterProto),videoEffects:Proto.repeatedObject(14,VideoEffectProto),videoEffectTombstones:Proto.repeatedInt32(15),audioEffects:Proto.repeatedObject(17,AudioEffectProto),audioEffectTombstones:Proto.repeatedInt32(18),trim:Proto.optionalObject(5,VideoTrimProto),presentationLoop:Proto.requiredStringEnum(6,LoopModeUtil,LoopMode.NONE),autoplay:Proto.requiredBoolean(9,true),playbackRate:Proto.optionalDouble(11),volume:Proto.requiredDouble(7,1),altText:Proto.optionalObject(12,AltTextProto),audioFade:Proto.optionalObject(16,AudioFadeProto)})));const GradientFillProtoUnionFields=()=>({});const GradientFillProto=Proto.createOneof((()=>({type:[1,LinearGradientFillProto,2,RadialGradientFillProto]})),GradientFillProtoUnionFields);const LinearGradientFillProto=Proto.createMessage((()=>({...GradientFillProtoUnionFields(),type:Proto.constantString("A?",1,"LINEAR"),stops:Proto.repeatedObject(1,GradientStopProto),rotation:Proto.requiredDouble(2)})));const RadialGradientFillProto=Proto.createMessage((()=>({...GradientFillProtoUnionFields(),type:Proto.constantString("A?",2,"RADIAL"),stops:Proto.repeatedObject(1,GradientStopProto),center:Proto.requiredObject(2,PointProto)})));const GradientStopProto=Proto.createMessage((()=>({color:Proto.requiredString(1),transparency:Proto.requiredDouble(2),position:Proto.requiredDouble(3)})));const TextConfigProto=Proto.createMessage((()=>({characters:Proto.repeatedString(1),cellSequence:Proto.repeatedInt32(2),attributeGradients:Proto.repeatedObject(3,TextAttributeGradientProto),attributeSequence:Proto.repeatedInt32(4),selections:Proto.stringObjectMap(5,SelectionProto)})));const TextAttributeGradientProto=Proto.createMessage((()=>({setFontFamily:Proto.optionalString(1),unsetFontFamily:Proto.requiredBoolean(2),setBlockFontFamily:Proto.optionalString(3),unsetBlockFontFamily:Proto.requiredBoolean(4),setFontSize:Proto.optionalString(5),unsetFontSize:Proto.requiredBoolean(6),setBlockFontSize:Proto.optionalString(7),unsetBlockFontSize:Proto.requiredBoolean(8),setFontWeight:Proto.optionalString(9),unsetFontWeight:Proto.requiredBoolean(10),setFontStyle:Proto.optionalString(11),unsetFontStyle:Proto.requiredBoolean(12),setColor:Proto.optionalString(13),unsetColor:Proto.requiredBoolean(14),setDecoration:Proto.optionalString(15),unsetDecoration:Proto.requiredBoolean(16),setLink:Proto.optionalString(17),unsetLink:Proto.requiredBoolean(18),setStartUs:Proto.optionalString(19),unsetStartUs:Proto.requiredBoolean(20),setLetterSpacing:Proto.optionalString(21),unsetLetterSpacing:Proto.requiredBoolean(22),setBlockLetterSpacing:Proto.optionalString(23),unsetBlockLetterSpacing:Proto.requiredBoolean(24),setLineHeight:Proto.optionalString(25),unsetLineHeight:Proto.requiredBoolean(26),setDirection:Proto.optionalString(27),unsetDirection:Proto.requiredBoolean(28),setTextAlign:Proto.optionalString(29),unsetTextAlign:Proto.requiredBoolean(30),setListMarker:Proto.optionalString(31),unsetListMarker:Proto.requiredBoolean(32),setListLevel:Proto.optionalString(33),unsetListLevel:Proto.requiredBoolean(34),setMarginInlineStart:Proto.optionalString(35),unsetMarginInlineStart:Proto.requiredBoolean(36),setMarginBlockEnd:Proto.optionalString(75),unsetMarginBlockEnd:Proto.requiredBoolean(76),setHeadIndent:Proto.optionalString(37),unsetHeadIndent:Proto.requiredBoolean(38),setTextIndent:Proto.optionalString(39),unsetTextIndent:Proto.requiredBoolean(40),setStrikethrough:Proto.optionalString(41),unsetStrikethrough:Proto.requiredBoolean(42),setFontKerning:Proto.optionalString(43),unsetFontKerning:Proto.requiredBoolean(44),setFontFeatureLiga:Proto.optionalString(45),unsetFontFeatureLiga:Proto.requiredBoolean(46),setFontFeatureClig:Proto.optionalString(47),unsetFontFeatureClig:Proto.requiredBoolean(48),setFontFeatureCalt:Proto.optionalString(49),unsetFontFeatureCalt:Proto.requiredBoolean(50),setBackgroundColor:Proto.optionalString(51),unsetBackgroundColor:Proto.requiredBoolean(52),setTextTransform:Proto.optionalString(53),unsetTextTransform:Proto.requiredBoolean(54),setBackgroundBorderRadius:Proto.optionalString(55),unsetBackgroundBorderRadius:Proto.requiredBoolean(56),setBackgroundBleed:Proto.optionalString(57),unsetBackgroundBleed:Proto.requiredBoolean(58),setFontSizeModifier:Proto.optionalString(59),unsetFontSizeModifier:Proto.requiredBoolean(60),setVerticalAlign:Proto.optionalString(61),unsetVerticalAlign:Proto.requiredBoolean(62),setSemantics:Proto.optionalString(63),unsetSemantics:Proto.requiredBoolean(64),setListNumberSet:Proto.optionalString(65),unsetListNumberSet:Proto.requiredBoolean(66),setSpacing:Proto.optionalString(67),unsetSpacing:Proto.requiredBoolean(68),setStyle:Proto.optionalString(69),unsetStyle:Proto.requiredBoolean(70),setFillId:Proto.optionalString(71),unsetFillId:Proto.requiredBoolean(72),setKerning:Proto.optionalString(73),unsetKerning:Proto.requiredBoolean(74),setUnused1:Proto.optionalString(77),unsetUnused1:Proto.requiredBoolean(78),setUnused2:Proto.optionalString(79),unsetUnused2:Proto.requiredBoolean(80),setUnused3:Proto.optionalString(81),unsetUnused3:Proto.requiredBoolean(82),setComment:Proto.repeatedString(127),unsetComment:Proto.repeatedString(128),suggestions:Proto.stringObjectMap(129,SuggestionAttributeGradientProto)})));const SuggestionAttributeGradientProto=Proto.createMessage((()=>({setFontFamily:Proto.optionalString(1),unsetFontFamily:Proto.requiredBoolean(2),setBlockFontFamily:Proto.optionalString(3),unsetBlockFontFamily:Proto.requiredBoolean(4),setFontSize:Proto.optionalString(5),unsetFontSize:Proto.requiredBoolean(6),setBlockFontSize:Proto.optionalString(7),unsetBlockFontSize:Proto.requiredBoolean(8),setFontWeight:Proto.optionalString(9),unsetFontWeight:Proto.requiredBoolean(10),setFontStyle:Proto.optionalString(11),unsetFontStyle:Proto.requiredBoolean(12),setColor:Proto.optionalString(13),unsetColor:Proto.requiredBoolean(14),setDecoration:Proto.optionalString(15),unsetDecoration:Proto.requiredBoolean(16),setLink:Proto.optionalString(17),unsetLink:Proto.requiredBoolean(18),setStartUs:Proto.optionalString(19),unsetStartUs:Proto.requiredBoolean(20),setLetterSpacing:Proto.optionalString(21),unsetLetterSpacing:Proto.requiredBoolean(22),setBlockLetterSpacing:Proto.optionalString(23),unsetBlockLetterSpacing:Proto.requiredBoolean(24),setLineHeight:Proto.optionalString(25),unsetLineHeight:Proto.requiredBoolean(26),setDirection:Proto.optionalString(27),unsetDirection:Proto.requiredBoolean(28),setTextAlign:Proto.optionalString(29),unsetTextAlign:Proto.requiredBoolean(30),setListMarker:Proto.optionalString(31),unsetListMarker:Proto.requiredBoolean(32),setListLevel:Proto.optionalString(33),unsetListLevel:Proto.requiredBoolean(34),setMarginInlineStart:Proto.optionalString(35),unsetMarginInlineStart:Proto.requiredBoolean(36),setMarginBlockEnd:Proto.optionalString(75),unsetMarginBlockEnd:Proto.requiredBoolean(76),setHeadIndent:Proto.optionalString(37),unsetHeadIndent:Proto.requiredBoolean(38),setTextIndent:Proto.optionalString(39),unsetTextIndent:Proto.requiredBoolean(40),setStrikethrough:Proto.optionalString(41),unsetStrikethrough:Proto.requiredBoolean(42),setFontKerning:Proto.optionalString(43),unsetFontKerning:Proto.requiredBoolean(44),setFontFeatureLiga:Proto.optionalString(45),unsetFontFeatureLiga:Proto.requiredBoolean(46),setFontFeatureClig:Proto.optionalString(47),unsetFontFeatureClig:Proto.requiredBoolean(48),setFontFeatureCalt:Proto.optionalString(49),unsetFontFeatureCalt:Proto.requiredBoolean(50),setBackgroundColor:Proto.optionalString(51),unsetBackgroundColor:Proto.requiredBoolean(52),setTextTransform:Proto.optionalString(53),unsetTextTransform:Proto.requiredBoolean(54),setBackgroundBorderRadius:Proto.optionalString(55),unsetBackgroundBorderRadius:Proto.requiredBoolean(56),setBackgroundBleed:Proto.optionalString(57),unsetBackgroundBleed:Proto.requiredBoolean(58),setFontSizeModifier:Proto.optionalString(59),unsetFontSizeModifier:Proto.requiredBoolean(60),setVerticalAlign:Proto.optionalString(61),unsetVerticalAlign:Proto.requiredBoolean(62),setSemantics:Proto.optionalString(63),unsetSemantics:Proto.requiredBoolean(64),setListNumberSet:Proto.optionalString(65),unsetListNumberSet:Proto.requiredBoolean(66),setSpacing:Proto.optionalString(67),unsetSpacing:Proto.requiredBoolean(68),setStyle:Proto.optionalString(69),unsetStyle:Proto.requiredBoolean(70),setFillId:Proto.optionalString(71),unsetFillId:Proto.requiredBoolean(72),setKerning:Proto.optionalString(73),unsetKerning:Proto.requiredBoolean(74),setUnused1:Proto.optionalString(77),unsetUnused1:Proto.requiredBoolean(78),setUnused2:Proto.optionalString(79),unsetUnused2:Proto.requiredBoolean(80),setUnused3:Proto.optionalString(81),unsetUnused3:Proto.requiredBoolean(82),setSuggestionType:Proto.optionalString(130),unsetSuggestionType:Proto.requiredBoolean(131)})));const TextAttributesProto=Proto.createMessage((()=>({fontFamily:Proto.optionalString(1),blockFontFamily:Proto.optionalString(2),fontSize:Proto.optionalString(3),blockFontSize:Proto.optionalString(4),fontWeight:Proto.optionalString(5),fontStyle:Proto.optionalString(6),color:Proto.optionalString(7),decoration:Proto.optionalString(8),link:Proto.optionalString(9),startUs:Proto.optionalString(10),letterSpacing:Proto.optionalString(11),blockLetterSpacing:Proto.optionalString(12),lineHeight:Proto.optionalString(13),direction:Proto.optionalString(14),textAlign:Proto.optionalString(15),listMarker:Proto.optionalString(16),listLevel:Proto.optionalString(17),marginInlineStart:Proto.optionalString(18),headIndent:Proto.optionalString(19),textIndent:Proto.optionalString(20),strikethrough:Proto.optionalString(21),fontKerning:Proto.optionalString(22),fontFeatureLiga:Proto.optionalString(23),fontFeatureClig:Proto.optionalString(24),fontFeatureCalt:Proto.optionalString(25),backgroundColor:Proto.optionalString(26),textTransform:Proto.optionalString(27),backgroundBorderRadius:Proto.optionalString(28),backgroundBleed:Proto.optionalString(29),semantics:Proto.optionalString(30),fontSizeModifier:Proto.optionalString(31),verticalAlign:Proto.optionalString(32),listNumberSet:Proto.optionalString(33),spacing:Proto.optionalString(34),style:Proto.optionalString(35),fillId:Proto.optionalString(36),kerning:Proto.optionalString(37),unused1:Proto.optionalString(38),unused2:Proto.optionalString(39),unused3:Proto.optionalString(40)})));const SelectionProto=Proto.createMessage((()=>({from:Proto.requiredInt32(1),to:Proto.optionalInt32(2)})));const TextFlowProto=Proto.createMessage((()=>({lineLengths:Proto.repeatedInt32(1)})));const Richtext2Proto=Proto.createMessage((()=>({doNotUseCharacters:Proto.repeatedObject(1,DoNotUseCharacterStreamItemProto),doNotUseAttributes:Proto.repeatedObject(2,DoNotUseAttributeStreamItemProto),config:Proto.optionalObject(3,TextConfigProto),fills:Proto.stringObjectMap(5,FillProto),flow:Proto.optionalObject(6,TextFlowProto)})));const DoNotUseCharacterStreamItemProtoUnionFields=()=>({});const DoNotUseCharacterStreamItemProto=Proto.createOneof((()=>({type:[1,CharacterRegionProto,2,TombstoneRegionProto]})),DoNotUseCharacterStreamItemProtoUnionFields);const CharacterRegionProto=Proto.createMessage((()=>({...DoNotUseCharacterStreamItemProtoUnionFields(),type:Proto.constantString("A?",1,"CHARACTERS"),characters:Proto.requiredString(1)})));const TombstoneRegionProto=Proto.createMessage((()=>({...DoNotUseCharacterStreamItemProtoUnionFields(),type:Proto.constantString("A?",2,"TOMBSTONES"),tombstones:Proto.requiredInt32(1)})));const DoNotUseAttributeStreamItemProtoUnionFields=()=>({});const DoNotUseAttributeStreamItemProto=Proto.createOneof((()=>({type:[1,ChangeAttributeStreamItemProto,2,RetainAttributeStreamItemProto]})),DoNotUseAttributeStreamItemProtoUnionFields);const ChangeAttributeStreamItemProto=Proto.createMessage((()=>({...DoNotUseAttributeStreamItemProtoUnionFields(),type:Proto.constantString("A?",1,"CHANGE"),attributes:Proto.stringObjectMap(1,AttributeChangeProto)})));const RetainAttributeStreamItemProto=Proto.createMessage((()=>({...DoNotUseAttributeStreamItemProtoUnionFields(),type:Proto.constantString("A?",2,"RETAIN"),length:Proto.requiredInt32(1)})));const AttributeChangeProto=Proto.createMessage((()=>({r:Proto.optionalString(2)})));const MediaRef=Proto.createMessage((()=>({id:Proto.requiredString(1),version:Proto.requiredInt32(2)})));const Fingerprint=Proto.createMessage((()=>({selector:Proto.requiredString(1),class:Proto.optionalString(2),textContent:Proto.optionalString(3)})));const CodeletEditUnionFields=()=>({});const CodeletEdit=Proto.createOneof((()=>({type:[1,CodeletElementEdit]})),CodeletEditUnionFields);const CodeletElementEdit=Proto.createMessage((()=>({...CodeletEditUnionFields(),type:Proto.constantString("A?",1,"ELEMENT_EDIT"),selector:Proto.requiredString(1),operation:Proto.requiredObject(2,ElementEditOperation)})));const ElementEditOperationUnionFields=()=>({});const ElementEditOperation=Proto.createOneof((()=>({type:[1,BackgroundColorEdit,2,TranslationEdit,3,RotationEdit,4,MediaReplaceEdit,5,ScaleEdit,6,RichtextEdit,7,LinkEdit,8,ReorderEdit]})),ElementEditOperationUnionFields);const BackgroundColorEdit=Proto.createMessage((()=>({...ElementEditOperationUnionFields(),type:Proto.constantString("A?",1,"BACKGROUND_COLOR"),color:Proto.requiredString(21)})));const TranslationEdit=Proto.createMessage((()=>({...ElementEditOperationUnionFields(),type:Proto.constantString("A?",2,"TRANSLATION"),translateX:Proto.requiredDouble(22),translateY:Proto.requiredDouble(23)})));const RotationEdit=Proto.createMessage((()=>({...ElementEditOperationUnionFields(),type:Proto.constantString("A?",3,"ROTATION"),rotation:Proto.requiredDouble(24)})));const MediaReplaceEdit=Proto.createMessage((()=>({...ElementEditOperationUnionFields(),type:Proto.constantString("A?",4,"MEDIA_REPLACE"),mediaRef:Proto.requiredObject(25,MediaRef)})));const ScaleEdit=Proto.createMessage((()=>({...ElementEditOperationUnionFields(),type:Proto.constantString("A?",5,"SCALE"),scale:Proto.requiredDouble(26)})));const RichtextEdit=Proto.createMessage((()=>({...ElementEditOperationUnionFields(),type:Proto.constantString("A?",6,"RICHTEXT"),html:Proto.requiredObject(27,Richtext2Proto)})));const LinkEdit=Proto.createMessage((()=>({...ElementEditOperationUnionFields(),type:Proto.constantString("A?",7,"LINK"),href:Proto.optionalString(28)})));const ReorderEdit=Proto.createMessage((()=>({...ElementEditOperationUnionFields(),type:Proto.constantString("A?",8,"REORDER"),order:Proto.requiredDouble(29)})));const FlexDirection={COLUMN:1,COLUMN_REVERSE:2,ROW:3,ROW_REVERSE:4};const FlexDirectionUtil=Proto.createEnumUtil((()=>[1,2,3,4]));const Rect=Proto.createMessage((()=>({top:Proto.requiredDouble(1),left:Proto.requiredDouble(2),width:Proto.requiredDouble(3),height:Proto.requiredDouble(4),rotation:Proto.optionalDouble(5)})));const DomMatrix=Proto.createMessage((()=>({a:Proto.requiredDouble(1),b:Proto.requiredDouble(2),c:Proto.requiredDouble(3),d:Proto.requiredDouble(4),e:Proto.requiredDouble(5),f:Proto.requiredDouble(6)})));const Editable=Proto.createMessage((()=>({selector:Proto.requiredString(1),attribute:Proto.requiredObject(2,EditableAttribute)})));const EditableAttributeUnionFields=()=>({});const EditableAttribute=Proto.createOneof((()=>({type:[1,BackgroundColorEditableAttribute,2,TranslationEditableAttribute,3,RotationEditableAttribute,4,MediaReplaceEditableAttribute,5,ScaleEditableAttribute,6,RichtextEditableAttribute,8,ReorderEditableAttribute]})),EditableAttributeUnionFields);const BackgroundColorEditableAttribute=Proto.createMessage((()=>({...EditableAttributeUnionFields(),type:Proto.constantString("A?",1,"BACKGROUND_COLOR"),current:Proto.requiredObject(21,BackgroundColorEdit)})));const TranslationEditableAttribute=Proto.createMessage((()=>({...EditableAttributeUnionFields(),type:Proto.constantString("A?",2,"TRANSLATION"),matrix:Proto.requiredObject(22,DomMatrix),current:Proto.requiredObject(23,TranslationEdit)})));const RotationEditableAttribute=Proto.createMessage((()=>({...EditableAttributeUnionFields(),type:Proto.constantString("A?",3,"ROTATION"),matrix:Proto.requiredObject(24,DomMatrix),current:Proto.requiredObject(25,RotationEdit)})));const MediaReplaceEditableAttribute=Proto.createMessage((()=>({...EditableAttributeUnionFields(),type:Proto.constantString("A?",4,"MEDIA_REPLACE")})));const ScaleEditableAttribute=Proto.createMessage((()=>({...EditableAttributeUnionFields(),type:Proto.constantString("A?",5,"SCALE"),matrix:Proto.requiredObject(26,DomMatrix),current:Proto.requiredObject(27,ScaleEdit)})));const RichtextEditableAttribute=Proto.createMessage((()=>({...EditableAttributeUnionFields(),type:Proto.constantString("A?",6,"RICHTEXT"),current:Proto.requiredObject(28,RichtextEdit)})));const ReorderEditableAttribute=Proto.createMessage((()=>({...EditableAttributeUnionFields(),type:Proto.constantString("A?",8,"REORDER"),direction:Proto.requiredStringEnum(29,FlexDirectionUtil),order:Proto.requiredInt32(30),ordering:Proto.stringInt32Map(31)})));const ImageFileReference=Proto.createMessage((()=>({url:Proto.requiredString(1),width:Proto.requiredInt32(2),height:Proto.requiredInt32(3)})));const Selection=Proto.createMessage((()=>({editables:Proto.repeatedObject(1,Editable),boundingRect:Proto.requiredObject(2,Rect)})));const SetSelectionRequest=Proto.createMessage((()=>({selection:Proto.requiredObject(1,Selection)})));const SetSelectionResult=Proto.createMessage((()=>({})));const GetMediaRequest=Proto.createMessage((()=>({mediaRef:Proto.requiredObject(1,MediaRef)})));const GetMediaResponse=Proto.createMessage((()=>({images:Proto.repeatedObject(1,ImageFileReference)})));function createEditing2SdkServiceRpcClient(...args){if(args.length===1)return new Editing2SdkServiceRpcClient(args[0]);return new Editing2SdkServiceRpcClient(args[0],args[1])}class Editing2SdkServiceRpcClient{setSelection(request){return this.sandboxRpcService.sendMessage("Editing2Sdk.setSelection",SetSelectionRequest.serialize(request),this.config?.setSelection).then(SetSelectionResult.deserialize)}getMedia(request){return this.sandboxRpcService.sendMessage("Editing2Sdk.getMedia",GetMediaRequest.serialize(request),this.config?.getMedia).then(GetMediaResponse.deserialize)}constructor(sandboxRpcService,config){this.sandboxRpcService=sandboxRpcService;this.config=config}}const InteractionMode={EDIT:1,MIXED:2};const InteractionModeUtil=Proto.createEnumUtil((()=>[1,2]));const SetInteractionModeRequest=Proto.createMessage((()=>({interactionMode:Proto.optionalStringEnum(1,InteractionModeUtil)})));const SetInteractionModeResponse=Proto.createMessage((()=>({})));const RenderEditsRequest=Proto.createMessage((()=>({edits:Proto.repeatedObject(1,CodeletElementEdit)})));const RenderEditsResponse=Proto.createMessage((()=>({})));const ClearSelectionRequest=Proto.createMessage((()=>({})));const ClearSelectionResponse=Proto.createMessage((()=>({})));const Droppable=Proto.createMessage((()=>({selector:Proto.requiredString(1),attribute:Proto.requiredObject(2,DroppableAttribute)})));const DroppableAttributeUnionFields=()=>({});const DroppableAttribute=Proto.createOneof((()=>({type:[1,MediaReplaceDroppableAttribute]})),DroppableAttributeUnionFields);const MediaReplaceDroppableAttribute=Proto.createMessage((()=>({...DroppableAttributeUnionFields(),type:Proto.constantString("A?",1,"MEDIA_REPLACE")})));const DragDropStartRequest=Proto.createMessage((()=>({previewUrl:Proto.optionalString(1),mediaRef:Proto.optionalObject(2,MediaRef)})));const DragDropStartResponse=Proto.createMessage((()=>({})));const DragDropHoverRequest=Proto.createMessage((()=>({xPos:Proto.optionalDouble(1),yPos:Proto.optionalDouble(2),previewUrl:Proto.optionalString(3),mediaRef:Proto.optionalObject(4,MediaRef)})));const DragDropHoverResponse=Proto.createMessage((()=>({nodes:Proto.repeatedObject(1,Droppable)})));const DragDropEndRequest=Proto.createMessage((()=>({dropped:Proto.requiredBoolean(1)})));const DragDropEndResponse=Proto.createMessage((()=>({})));function registerEditing2SdkIframeServiceHost(...args){const sandboxRpcService=args[0];const hostController=args[1];const configuration=args.length===3?args[2]:undefined;const cleanupFns=[sandboxRpcService.registerMessageHandler("Editing2SdkIframe.setInteractionMode",(async request=>SetInteractionModeResponse.serialize(await hostController.setInteractionMode(SetInteractionModeRequest.deserialize(request)))),configuration?.setInteractionMode),sandboxRpcService.registerMessageHandler("Editing2SdkIframe.clearSelection",(async request=>ClearSelectionResponse.serialize(await hostController.clearSelection(ClearSelectionRequest.deserialize(request)))),configuration?.clearSelection),sandboxRpcService.registerMessageHandler("Editing2SdkIframe.renderEdits",(async request=>RenderEditsResponse.serialize(await hostController.renderEdits(RenderEditsRequest.deserialize(request)))),configuration?.renderEdits),sandboxRpcService.registerMessageHandler("Editing2SdkIframe.onDragDropStart",(async request=>DragDropStartResponse.serialize(await hostController.onDragDropStart(DragDropStartRequest.deserialize(request)))),configuration?.onDragDropStart),sandboxRpcService.registerMessageHandler("Editing2SdkIframe.onDragDropHover",(async request=>DragDropHoverResponse.serialize(await hostController.onDragDropHover(DragDropHoverRequest.deserialize(request)))),configuration?.onDragDropHover),sandboxRpcService.registerMessageHandler("Editing2SdkIframe.onDragDropEnd",(async request=>DragDropEndResponse.serialize(await hostController.onDragDropEnd(DragDropEndRequest.deserialize(request)))),configuration?.onDragDropEnd)];return()=>cleanupFns.forEach((fn=>fn()))}const formattedErrorMessage=opts=>{const maybeFullstop=opts.message.endsWith(".")?"":".";return`[${opts.code}]: ${opts.message}${maybeFullstop}`.trim()};class CanvaErrorClass extends Error{constructor(opts){opts.code=appSandboxErrorCodeMapper(opts.code);super(formattedErrorMessage(opts));this.code=opts.code;this.name="CanvaError";this.rawMessage=opts.message;Object.setPrototypeOf(this,CanvaErrorClass.prototype)}}function setAppSandboxErrorCodeMapper(mapper){appSandboxErrorCodeMapper=mapper}let appSandboxErrorCodeMapper=code=>code;class MessageBus{constructor(handler,port,errorService){this.handler=handler;this.port=port;this.errorService=errorService;this.send=message=>{try{this.port.postMessage(message);return Result.Ok()}catch(e){this.errorService.errorException(e);return Result.Err(e)}};this.onMessageError=e=>{this.errorService.errorException(e)};this.onMessage=({data})=>{if(!data){this.errorService.error(new CanvaErrorClass({code:"internal_error",message:`missing data in 'MessageEvent'`}));return}try{this.handler.receive(data)}catch(e){this.errorService.errorException(e)}};this.port.onmessage=this.onMessage;this.port.onmessageerror=this.onMessageError}}function uuidv4(rng){const randomValues=getRandomValues(rng,31);let currentRandomValue=0;return`${1e7}-${1e3}-${4e3}-${8e3}-${1e11}`.replace(/[018]/g,(function(c){const cN=Number(c);return(cN^randomValues[currentRandomValue++]&15>>cN/4).toString(16)}))}const HEX_CHARS="0123456789abcdef";function uuidv7(){const bytes=Uint8Array.from(getRandomValues(undefined,16));const now=Date.now();bytes[0]=Math.trunc(now/1099511627776)&255;bytes[1]=Math.trunc(now/4294967296)&255;bytes[2]=Math.trunc(now/16777216)&255;bytes[3]=Math.trunc(now/65536)&255;bytes[4]=Math.trunc(now/256)&255;bytes[5]=now&255;bytes[6]=112|bytes[6]&15;bytes[8]=128|bytes[8]&63;let hex="";for(let i=0;i<16;i++)hex+=HEX_CHARS[bytes[i]>>>4]+HEX_CHARS[bytes[i]&15];return`${hex.slice(0,8)}-${hex.slice(8,12)}-${hex.slice(12,16)}-${hex.slice(16,20)}-${hex.slice(20)}`}function getRandomValues(rng,amount){if(!rng&&typeof window!=="undefined"&&typeof window.crypto!=="undefined"&&typeof window.crypto.getRandomValues==="function")return window.crypto.getRandomValues(new Uint8Array(amount));const random=rng??Math.random;return Array.from({length:amount},(()=>Math.floor(random()*255)))}const ACK_INTERVAL=9e3;const INITIAL_ACK_TIMEOUT=2e4;const SUBSEQUENT_ACK_TIMEOUT=3e4;class PromiseTimeoutError extends Error{constructor(){super("[internal_error] Comms promise timed out.")}}const REJECT_ON_NEXT_TICK_DELAY_MS=500;class PromiseWithTimeout{reset(newTimeoutMs){if(newTimeoutMs)this.timeoutMs=newTimeoutMs;this.setTimeout()}resolve(value){clearTimeout(this.timeoutId);this.resolveFn(value)}reject(reason){clearTimeout(this.timeoutId);this.rejectFn(reason)}promise(){return this.p}rejectOnNextTick(){this.timeoutId=setTimeout((()=>{this.rejectFn(new PromiseTimeoutError)}),REJECT_ON_NEXT_TICK_DELAY_MS)}setTimeout(){clearTimeout(this.timeoutId);this.timeoutId=setTimeout((()=>{this.rejectOnNextTick()}),Math.max(this.timeoutMs-REJECT_ON_NEXT_TICK_DELAY_MS,REJECT_ON_NEXT_TICK_DELAY_MS))}constructor(timeoutMs){this.timeoutMs=timeoutMs;this.p=new Promise(((resolve,reject)=>{this.resolveFn=resolve;this.rejectFn=reject}));this.setTimeout()}}const RECENT_TIMED_OUT_REQUEST_LIMIT=32;class Client{request(path,payload){const pendingRequests=this.pendingRequests;const recentTimedOutRequests=this.recentTimedOutRequests;const requestPromise=new PromiseWithTimeout(INITIAL_ACK_TIMEOUT);const requestId=this.requestIdGenerator();const resultPromise=awaitResult();const result=this.send(requestId,path,payload);if(!result.ok){this.errorService.errorException(result.error,{errorMessagePrefix:"unable to send request",tags:new Map([["type","request"],["path",path]])});requestPromise.reject(result.error)}return resultPromise;async function awaitResult(){pendingRequests.set(requestId,{path,requestPromise});try{const response=await requestPromise.promise();return Result.Ok(response)}catch(e){if(e instanceof PromiseTimeoutError){recentTimedOutRequests.set(requestId,[path,Date.now()]);if(recentTimedOutRequests.size>RECENT_TIMED_OUT_REQUEST_LIMIT)recentTimedOutRequests.delete(recentTimedOutRequests.keys().next().value);return Result.Err(new CanvaErrorClass({code:"internal_error",message:`Comms promise timed out (${path}).`}))}return Result.Err(e)}finally{pendingRequests.delete(requestId)}}}handleReply(msg){const{requestId,type}=msg;const{path,requestPromise:request}=this.pendingRequests.get(requestId)||{};if(!request){if(type!=="ack"){const[path,timestamp]=this.recentTimedOutRequests.get(requestId)??["not_recently_timed_out",undefined];const extra=timestamp!==undefined?new Map([["time_since_timeout",Date.now()-timestamp]]):undefined;this.errorService.error(`request has already been handled and resolved or was not sent from this client`,{tags:new Map([["type",type],["path",path]]),extra})}return}switch(type){case"response":request.resolve(msg.payload);return;case"ack":request.reset(SUBSEQUENT_ACK_TIMEOUT);return;case"error":this.errorService.addBreadCrumb({level:"info",category:"sandbox_comms",message:"Error response received",data:{["path"]:path??"unknown"}});const{code,message}=msg;request.reject(new CanvaErrorClass({code,message}));return;default:throw new UnreachableError(msg)}}constructor(send,errorService,requestIdGenerator=uuidv4){this.send=send;this.errorService=errorService;this.requestIdGenerator=requestIdGenerator;this.pendingRequests=new Map;this.recentTimedOutRequests=new Map}}const RequestHandlerErrorCodes={internalError:()=>"Something went wrong on our end, if this issue persists please contact us.",noHandlerForPath:path=>`No request handler configured for path: "${path}".`,handlerForPathAlreadyDefined:path=>`Handler for '${path}' is already defined.`};class RequestHandler{addErrorObserver(observer){this.errorObservers.add(observer);return()=>this.errorObservers.delete(observer)}handle(path,handler){if(this.requestHandler.has(path))throw new CanvaErrorClass({code:"internal_error",message:RequestHandlerErrorCodes.handlerForPathAlreadyDefined(path)});this.requestHandler.set(path,handler);return()=>this.requestHandler.delete(path)}async handleRequest(body){const{requestId,path,payload}=body;const handler=this.requestHandler.get(path);if(!handler){const result=this.messenger.sendError(requestId,"internal_error",RequestHandlerErrorCodes.noHandlerForPath(path));if(!result.ok)this.errorService.criticalException(result.error,{errorMessagePrefix:"unable to send error response",tags:new Map([["type","request"],["path",path]])});return}this.messenger.sendAck(requestId);const intervalId=setInterval((()=>this.messenger.sendAck(requestId)),ACK_INTERVAL);let observableError;try{const resPayload=await handler(payload);clearInterval(intervalId);this.messenger.sendResponse(requestId,resPayload)}catch(e){clearInterval(intervalId);let errorCode="internal_error";let errorMessage=RequestHandlerErrorCodes.internalError();if(e instanceof CanvaErrorClass){observableError=e;if(e.code==="internal_error")this.errorService.errorException(e,{errorMessagePrefix:"Internal error in comms handler",tags:new Map([["type","request"],["path",path]])});else{errorCode=e.code;errorMessage=e.rawMessage}}else if(this.reportNonCanvaErrors)this.errorService.errorException(e,{errorMessagePrefix:"Unexpected error type thrown from comms handler",tags:new Map([["type","request"],["path",path]])});else this.devConsole.error(e);const result=this.messenger.sendError(requestId,errorCode,errorMessage);if(!result.ok)this.errorService.criticalException(result.error,{errorMessagePrefix:"unable to send error response",tags:new Map([["type","request"],["path",path]])})}if(observableError==null)return;for(const cb of this.errorObservers)try{cb(observableError)}catch(e){this.errorService.warningException(e,{errorMessagePrefix:"Error executing errorObserver"})}}constructor(messenger,errorService,reportNonCanvaErrors,devConsole=console){this.messenger=messenger;this.errorService=errorService;this.reportNonCanvaErrors=reportNonCanvaErrors;this.devConsole=devConsole;this.requestHandler=new Map;this.errorObservers=new Set}}class SandboxCommsBase{constructor(port,errorService,reportNonCanvaErrors){this.request=(path,payload)=>this.client.request(path,payload);this.handle=(path,handler)=>this.requestHandler.handle(path,handler);this.addErrorObserver=observer=>this.requestHandler.addErrorObserver(observer);const handleMessage=message=>{switch(message.type){case"ack":case"error":case"response":this.client.handleReply(message);return;case"request":this.requestHandler.handleRequest(message);return;default:throw new UnreachableError(message)}};const messenger=new MangleSafeMessageBus(handleMessage,port,errorService.createChild("bus"));this.client=new Client(messenger.sendRequest,errorService.createChild("client"));this.requestHandler=new RequestHandler(messenger,errorService.createChild("requestHandler"),reportNonCanvaErrors)}}class MangleSafeMessageBus{sendResponse(requestId,payload){return this.bus.send({["type"]:"response",["requestId"]:requestId,["payload"]:payload})}sendError(requestId,code,message){return this.bus.send({["type"]:"error",["requestId"]:requestId,["code"]:code,["message"]:message})}sendAck(requestId){return this.bus.send({["type"]:"ack",["requestId"]:requestId})}constructor(handleMessage,port,errorService){this.handleMessage=handleMessage;this.sendRequest=(requestId,path,payload)=>this.bus.send({["type"]:"request",["requestId"]:requestId,["path"]:path,["payload"]:payload});this.onReceive=message=>{switch(message["type"]){case"ack":this.handleMessage({type:"ack",requestId:message["requestId"]});return;case"error":this.handleMessage({type:"error",requestId:message["requestId"],code:message["code"],message:message["message"]});return;case"response":this.handleMessage({type:"response",requestId:message["requestId"],payload:message["payload"]});return;case"request":this.handleMessage({type:"request",requestId:message["requestId"],path:message["path"],payload:message["payload"]});return;default:throw new UnreachableError(message)}};this.bus=new MessageBus({receive:this.onReceive},port,errorService)}}const VerifyError={MISSING_DATA:"missing 'data' field in MessageEvent",MISSING_SOURCE:"'sandboxCommsSource' is missing in MessageEvent data object",INVALID_SOURCE:"invalid source",UNKNOWN_CLIENT_ID:"unknown client id"};function createInitialiseMessage(sandboxCommsSource,clientId){return{["sandboxCommsSource"]:sandboxCommsSource,["clientId"]:clientId}}function verifyMessage(data,expectedSource,expectedClientId){if(!data)return Result.Err("missing 'data' field in MessageEvent");const msg=data;const source=msg["sandboxCommsSource"];if(!source)return Result.Err("'sandboxCommsSource' is missing in MessageEvent data object");if(source!==expectedSource)return Result.Err("invalid source");if(msg["clientId"]!==expectedClientId)return Result.Err("unknown client id");return Result.Ok()}async function connectToParent(errorService,parentOrigin,{parent,addEventListener,removeEventListener}=window,clientId){const portPromise=Promise.withResolvers();const messageHandler=({ports,data})=>{const msg=verifyMessage(data,"parent",clientId);if(!msg.ok){switch(msg.error){case VerifyError.INVALID_SOURCE:errorService.info(msg.error,{errorMessagePrefix:"failed to verify message",extra:new Map([["data.sandboxCommsSource",data?.sandboxCommsSource]])});break;case VerifyError.MISSING_DATA:case VerifyError.MISSING_SOURCE:case VerifyError.UNKNOWN_CLIENT_ID:break;default:throw new UnreachableError(msg.error)}return}if(ports.length!==1){errorService.error("invalid number of ports received from the parent");return}const[port]=ports;portPromise.resolve(port)};addEventListener("message",messageHandler);try{const initMessage=createInitialiseMessage("iframe",clientId);parent.postMessage(initMessage,parentOrigin);const port=await portPromise.promise;return Result.Ok(new SandboxCommsBase(port,errorService.createChild("comms"),false))}catch(e){return Result.Err(e)}finally{removeEventListener("message",messageHandler)}}const LoadMode={BLOCKING:1,BACKGROUND:2};const LoadModeUtil=Proto.createEnumUtil((()=>[0,1]));const payloads_proto_InteractionMode={EDIT:1,MIXED:2};const payloads_proto_InteractionModeUtil=Proto.createEnumUtil((()=>[1,2]));const Dimensions=Proto.createMessage((()=>({width:Proto.requiredInt32(1),height:Proto.requiredInt32(2)})));const ImageSrc=Proto.createMessage((()=>({src:Proto.requiredString(1),width:Proto.requiredInt32(2)})));const RenderableCodeletAttributes=Proto.createMessage((()=>({textContent:Proto.optionalString("textContent",1),background:Proto.optionalString("background",2),backgroundDimensions:Proto.optionalObject("backgroundDimensions",7,Dimensions),backgroundImageSrcs:Proto.repeatedObject("backgroundImageSrcs",12,ImageSrc),color:Proto.optionalString("color",3),font:Proto.optionalObject("font",4,FontMetadata),fontSize:Proto.optionalInt32("fontSize",8),letterSpacing:Proto.optionalDouble("letterSpacing",9),lineHeight:Proto.optionalDouble("lineHeight",10),imageSrc:Proto.optionalString("imageSrc",5),imageSrcs:Proto.repeatedObject("imageSrcs",11,ImageSrc),altText:Proto.optionalString("altText",6)})),{dualDeserializationConfig:DualDeserializationConfig.MINI_PRIMARY_FULL_SECONDARY});const FontAttributes=Proto.createMessage((()=>({src:Proto.requiredString("src",1),weight:Proto.requiredString("weight",2),style:Proto.requiredString("style",3),loadMode:Proto.requiredStringEnum("loadMode",4,LoadModeUtil)})),{dualDeserializationConfig:DualDeserializationConfig.MINI_PRIMARY_FULL_SECONDARY});const FontMetadata=Proto.createMessage((()=>({cssFontFamily:Proto.optionalString("cssFontFamily",1),id:Proto.optionalString("id",2),src:Proto.optionalString("src",3),weight:Proto.requiredString("weight",4),style:Proto.requiredString("style",5),variants:Proto.repeatedObject("variants",6,FontAttributes)})),{dualDeserializationConfig:DualDeserializationConfig.MINI_PRIMARY_FULL_SECONDARY});const SetConfigRequest=Proto.createMessage((()=>({config:Proto.stringObjectMap("config",1,RenderableCodeletAttributes)})),{dualDeserializationConfig:DualDeserializationConfig.MINI_PRIMARY_FULL_SECONDARY});const SetConfigResponse=Proto.createMessage((()=>({})));const SetFeatureFlagsRequest=Proto.createMessage((()=>({enableCodeletSelectionFrame:Proto.optionalBoolean("enableCodeletSelectionFrame",1),enableClampingToPreventWordBreaks:Proto.requiredBoolean("enableClampingToPreventWordBreaks",2),enableEditingOverlays:Proto.optionalBoolean("enableEditingOverlays",3),enableEditingContextMenu:Proto.requiredBoolean("enableEditingContextMenu",4),enableCodelet2LineHeight:Proto.requiredBoolean("enableCodelet2LineHeight",5)})),{dualDeserializationConfig:DualDeserializationConfig.MINI_PRIMARY_FULL_SECONDARY});const SetFeatureFlagsResponse=Proto.createMessage((()=>({})));const InteractionModeRequest=Proto.createMessage((()=>({interactionMode:Proto.optionalStringEnum("interactionMode",1,payloads_proto_InteractionModeUtil)})),{dualDeserializationConfig:DualDeserializationConfig.MINI_PRIMARY_FULL_SECONDARY});const InteractionModeResponse=Proto.createMessage((()=>({})),{dualDeserializationConfig:DualDeserializationConfig.MINI_PRIMARY_FULL_SECONDARY});const RequestSelectionRequest=Proto.createMessage((()=>({entityId:Proto.requiredString("entityId",1)})),{dualDeserializationConfig:DualDeserializationConfig.MINI_PRIMARY_FULL_SECONDARY});const RequestSelectionResponse=Proto.createMessage((()=>({success:Proto.requiredBoolean("success",1)})),{dualDeserializationConfig:DualDeserializationConfig.MINI_PRIMARY_FULL_SECONDARY});const SelectBackgroundRequest=Proto.createMessage((()=>({})),{dualDeserializationConfig:DualDeserializationConfig.MINI_PRIMARY_FULL_SECONDARY});const SelectBackgroundResponse=Proto.createMessage((()=>({success:Proto.requiredBoolean("success",1)})),{dualDeserializationConfig:DualDeserializationConfig.MINI_PRIMARY_FULL_SECONDARY});const HoverBackgroundRequest=Proto.createMessage((()=>({})),{dualDeserializationConfig:DualDeserializationConfig.MINI_PRIMARY_FULL_SECONDARY});const HoverBackgroundResponse=Proto.createMessage((()=>({success:Proto.requiredBoolean("success",1)})),{dualDeserializationConfig:DualDeserializationConfig.MINI_PRIMARY_FULL_SECONDARY});const SelectionRequest=Proto.createMessage((()=>({xPosPct:Proto.requiredDouble("xPosPct",1),yPosPct:Proto.requiredDouble("yPosPct",2)})),{dualDeserializationConfig:DualDeserializationConfig.MINI_PRIMARY_FULL_SECONDARY});const SelectionResponse=Proto.createMessage((()=>({success:Proto.requiredBoolean("success",1)})),{dualDeserializationConfig:DualDeserializationConfig.MINI_PRIMARY_FULL_SECONDARY});const SelectionHoverRequest=Proto.createMessage((()=>({xPosPct:Proto.requiredDouble("xPosPct",1),yPosPct:Proto.requiredDouble("yPosPct",2)})),{dualDeserializationConfig:DualDeserializationConfig.MINI_PRIMARY_FULL_SECONDARY});const SelectionHoverResponse=Proto.createMessage((()=>({})),{dualDeserializationConfig:DualDeserializationConfig.MINI_PRIMARY_FULL_SECONDARY});const ScrollEventStatus={STARTED:1,COMPLETED:2};const ScrollEventStatusUtil=Proto.createEnumUtil((()=>[1,2]));const ScrollEventRequest=Proto.createMessage((()=>({status:Proto.requiredStringEnum("status",1,ScrollEventStatusUtil)})),{dualDeserializationConfig:DualDeserializationConfig.MINI_PRIMARY_FULL_SECONDARY});const InteractionClickRequest=Proto.createMessage((()=>({xPosPct:Proto.requiredDouble("xPosPct",1),yPosPct:Proto.requiredDouble("yPosPct",2)})),{dualDeserializationConfig:DualDeserializationConfig.MINI_PRIMARY_FULL_SECONDARY});const InteractionClickResponse=Proto.createMessage((()=>({})),{dualDeserializationConfig:DualDeserializationConfig.MINI_PRIMARY_FULL_SECONDARY});const ScrollEventResponse=Proto.createMessage((()=>({})),{dualDeserializationConfig:DualDeserializationConfig.MINI_PRIMARY_FULL_SECONDARY});const SelectionChangeRequest=Proto.createMessage((()=>({selection:Proto.optionalObject("selection",1,payloads_proto_Selection)})),{dualDeserializationConfig:DualDeserializationConfig.MINI_PRIMARY_FULL_SECONDARY});const SelectionChangeResponse=Proto.createMessage((()=>({})));const payloads_proto_Selection=Proto.createMessage((()=>({entityId:Proto.requiredString("entityId",1),boundingRect:Proto.requiredObject("boundingRect",2,payloads_proto_Rect),elementLabel:Proto.optionalString("elementLabel",3),permitPointerEvents:Proto.requiredBoolean("permitPointerEvents",4),templatedElements:Proto.repeatedObject("templatedElements",5,payloads_proto_Rect),elementId:Proto.optionalString("elementId",6)})),{dualDeserializationConfig:DualDeserializationConfig.MINI_PRIMARY_FULL_SECONDARY});const payloads_proto_Rect=Proto.createMessage((()=>({top:Proto.requiredInt32("top",1),left:Proto.requiredInt32("left",2),width:Proto.requiredInt32("width",3),height:Proto.requiredInt32("height",4)})),{dualDeserializationConfig:DualDeserializationConfig.MINI_PRIMARY_FULL_SECONDARY});const HoverElementChangedRequest=Proto.createMessage((()=>({rect:Proto.optionalObject("rect",1,payloads_proto_Rect)})),{dualDeserializationConfig:DualDeserializationConfig.MINI_PRIMARY_FULL_SECONDARY});const HoverElementChangedResponse=Proto.createMessage((()=>({})));const TextContentChangedRequest=Proto.createMessage((()=>({entityId:Proto.requiredString("entityId",1),textContent:Proto.requiredString("textContent",2)})),{dualDeserializationConfig:DualDeserializationConfig.MINI_PRIMARY_FULL_SECONDARY});const TextContentChangedResponse=Proto.createMessage((()=>({})));const FocusTextRequest=Proto.createMessage((()=>({entityId:Proto.requiredString("entityId",1)})),{dualDeserializationConfig:DualDeserializationConfig.MINI_PRIMARY_FULL_SECONDARY});const FocusTextResponse=Proto.createMessage((()=>({success:Proto.requiredBoolean("success",1)})),{dualDeserializationConfig:DualDeserializationConfig.MINI_PRIMARY_FULL_SECONDARY});const TextFocusChangedRequest=Proto.createMessage((()=>({entityId:Proto.requiredString("entityId",1),focused:Proto.requiredBoolean("focused",2),textDimensions:Proto.optionalObject("textDimensions",3,payloads_proto_Rect)})),{dualDeserializationConfig:DualDeserializationConfig.MINI_PRIMARY_FULL_SECONDARY});const TextFocusChangedResponse=Proto.createMessage((()=>({})));const DragDropHoverEventRequest=Proto.createMessage((()=>({xPos:Proto.requiredDouble(1),yPos:Proto.requiredDouble(2),previewUrl:Proto.requiredString(3),previewDimensions:Proto.requiredObject(4,Dimensions)})));const DragDropHoverEventResponse=Proto.createMessage((()=>({entityId:Proto.optionalString(1)})));const DragDropEndEventRequest=Proto.createMessage((()=>({dropped:Proto.requiredBoolean(1)})));const DragDropEndEventResponse=Proto.createMessage((()=>({})));const GetEditableRegionsRequest=Proto.createMessage((()=>({})));const GetEditableRegionsResponse=Proto.createMessage((()=>({editableRegions:Proto.repeatedObject(2,payloads_proto_Rect)})));const ShowContextMenuRequest=Proto.createMessage((()=>({entityId:Proto.requiredString(1)})));const ShowContextMenuResponse=Proto.createMessage((()=>({})));const ClearEditModeRequest=Proto.createMessage((()=>({})));const ClearEditModeResponse=Proto.createMessage((()=>({})));function deserializeRequest(message_path,proto,request){if(request===undefined)throw new CanvaErrorClass({code:"internal_error",message:`${message_path}: request cannot be undefined.`});return proto.deserialize(request)}function handleMessageFromHost(comms,message_path,messageArgProto,messageHandler,responseProto){return comms.handle(message_path,(async messageObject=>{const message=deserializeRequest(message_path,messageArgProto,messageObject);const response=await messageHandler(message);if(responseProto)return responseProto.serialize(response)}))}async function runRequest(comms,messagePath,requestProto,request,responseProto){const response=await comms.request(messagePath,requestProto.serialize(request));if(!response.ok){if(response.error instanceof CanvaErrorClass)throw response.error;throw new CanvaErrorClass({code:"internal_error",message:`Something went wrong during request ${messagePath}`})}if(responseProto){if(response.value===undefined)throw new CanvaErrorClass({code:"internal_error",message:`Expected a response from ${messagePath}, but got nothing`});return responseProto.deserialize(response.value)}}const EDITING_CLIENT_ID="canva-code-editing-sdk";const EDITING_CAPABILITIES={serviceName:EDITING_CLIENT_ID,scrolled:"LAYOUT_SHIFT_EVENT",selectionChanged:"SELECTION_CHANGE",hoverElementChanged:"HOVER_ELEMENT_CHANGED",textContentChanged:"TEXT_CONTENT_CHANGED",textFocusChanged:"TEXT_FOCUS_CHANGED",showContextMenu:"SHOW_CONTEXT_MENU",clearEditMode:"CLEAR_EDIT_MODE"};const CODELET_EDITING_CAPABILITIES={serviceName:EDITING_CLIENT_ID,setConfig:"SET_EDITING_CONFIG",requestSelection:"REQUEST_SELECTION",onSelection:"SELECTION",onSelectionHover:"SELECTION_HOVER",onDragDropHover:"DRAG_DROP_HOVER_EVENT",onDragDropEnd:"DRAG_DROP_END_EVENT",setFeatureFlags:"SET_FEATURE_FLAGS",setInteractionMode:"SET_INTERACTION_MODE",onInteractionClick:"INTERACTION_CLICK",selectBackground:"SELECT_BACKGROUND",hoverBackground:"HOVER_BACKGROUND",getEditableRegions:"GET_EDITABLE_REGIONS_REQUEST",focusText:"FOCUS_TEXT"};function setupEditingRequestHandlers(comms,handler){handleMessageFromHost(comms,EDITING_CAPABILITIES.scrolled,ScrollEventRequest,(request=>handler.scrolled(request)),ScrollEventResponse);handleMessageFromHost(comms,EDITING_CAPABILITIES.selectionChanged,SelectionChangeRequest,(request=>handler.selectionChanged(request)),SelectionChangeResponse);handleMessageFromHost(comms,EDITING_CAPABILITIES.hoverElementChanged,HoverElementChangedRequest,(request=>handler.hoverElementChanged(request)),HoverElementChangedResponse);handleMessageFromHost(comms,EDITING_CAPABILITIES.textContentChanged,TextContentChangedRequest,(request=>handler.textContentChanged(request)),TextContentChangedResponse);handleMessageFromHost(comms,EDITING_CAPABILITIES.textFocusChanged,TextFocusChangedRequest,(request=>handler.textFocusChanged(request)),TextFocusChangedResponse);handleMessageFromHost(comms,EDITING_CAPABILITIES.showContextMenu,ShowContextMenuRequest,(request=>handler.showContextMenu?.(request)),ShowContextMenuResponse);handleMessageFromHost(comms,EDITING_CAPABILITIES.clearEditMode,ClearEditModeRequest,(request=>handler.clearEditMode?.(request)),ClearEditModeResponse)}function setupSandboxedEditingRequestHandlers(comms,handler){handleMessageFromHost(comms,CODELET_EDITING_CAPABILITIES.setConfig,SetConfigRequest,(request=>handler.setConfig(request)),SetConfigResponse);handleMessageFromHost(comms,CODELET_EDITING_CAPABILITIES.requestSelection,RequestSelectionRequest,(request=>handler.requestSelection(request)),RequestSelectionResponse);handleMessageFromHost(comms,CODELET_EDITING_CAPABILITIES.onSelection,SelectionRequest,(request=>handler.onSelection(request)),SelectionResponse);handleMessageFromHost(comms,CODELET_EDITING_CAPABILITIES.onSelectionHover,SelectionHoverRequest,(request=>handler.onSelectionHover(request)),SelectionHoverResponse);handleMessageFromHost(comms,CODELET_EDITING_CAPABILITIES.onDragDropHover,DragDropHoverEventRequest,(request=>handler.onDragDropHover(request)),DragDropHoverEventResponse);handleMessageFromHost(comms,CODELET_EDITING_CAPABILITIES.onDragDropEnd,DragDropEndEventRequest,(request=>handler.onDragDropEnd(request)),DragDropEndEventResponse);handleMessageFromHost(comms,CODELET_EDITING_CAPABILITIES.setFeatureFlags,SetFeatureFlagsRequest,(request=>handler.setFeatureFlags(request)),SetFeatureFlagsResponse);handleMessageFromHost(comms,CODELET_EDITING_CAPABILITIES.setInteractionMode,InteractionModeRequest,(async request=>await(handler.setInteractionMode?.(request))??new InteractionModeResponse),InteractionModeResponse);handleMessageFromHost(comms,"INTERACTION_CLICK",InteractionClickRequest,(request=>handler.onInteractionClick?.(request)),InteractionClickResponse);handleMessageFromHost(comms,"SELECT_BACKGROUND",SelectBackgroundRequest,(request=>handler.selectBackground?.(request)),SelectBackgroundResponse);handleMessageFromHost(comms,"HOVER_BACKGROUND",HoverBackgroundRequest,(request=>handler.hoverBackground?.(request)),HoverBackgroundResponse);handleMessageFromHost(comms,"GET_EDITABLE_REGIONS_REQUEST",GetEditableRegionsRequest,(request=>handler.getEditableRegions?.(request)),GetEditableRegionsResponse);handleMessageFromHost(comms,CODELET_EDITING_CAPABILITIES.focusText,FocusTextRequest,(request=>handler.focusText(request)),FocusTextResponse)}class HostRpcEditingSdkClient{scrolled(req){return this.hostRpc.exec(this.capabilities.serviceName,this.capabilities.scrolled,ScrollEventRequest.serialize(req)).then(ScrollEventResponse.deserialize)}selectionChanged(req){return this.hostRpc.exec(this.capabilities.serviceName,this.capabilities.selectionChanged,SelectionChangeRequest.serialize(req)).then(SelectionChangeResponse.deserialize)}hoverElementChanged(req){return this.hostRpc.exec(this.capabilities.serviceName,this.capabilities.hoverElementChanged,HoverElementChangedRequest.serialize(req)).then(HoverElementChangedResponse.deserialize)}textContentChanged(req){return this.hostRpc.exec(this.capabilities.serviceName,this.capabilities.textContentChanged,TextContentChangedRequest.serialize(req)).then(TextContentChangedResponse.deserialize)}textFocusChanged(req){return this.hostRpc.exec(this.capabilities.serviceName,this.capabilities.textFocusChanged,TextFocusChangedRequest.serialize(req)).then(TextFocusChangedResponse.deserialize)}showContextMenu(req){return this.hostRpc.exec(this.capabilities.serviceName,this.capabilities.showContextMenu,ShowContextMenuRequest.serialize(req)).then(ShowContextMenuResponse.deserialize)}clearEditMode(req){return this.hostRpc.exec(this.capabilities.serviceName,this.capabilities.clearEditMode,ClearEditModeRequest.serialize(req)).then(ClearEditModeResponse.deserialize)}constructor(hostRpc,capabilities){this.hostRpc=hostRpc;this.capabilities=capabilities}}class EditingSdkClient extends HostRpcEditingSdkClient{constructor(comms){super({exec:async(serviceName,methodName,data)=>{Preconditions.checkState(serviceName===EDITING_CAPABILITIES.serviceName);const res=await comms.request(methodName,data);return unwrapResult(res,methodName)},requestChannel:undefined},EDITING_CAPABILITIES)}}function unwrapResult(result,messagePath){if(!result.ok)throw new Error(`Encountered an error while sending ${messagePath} request: ${result.error}`);if(result.value==null)throw new Error(`${messagePath}: Result cannot be empty`);return result.value}const SYSTEM_LOG_MARKER=Symbol("canvaSystemLog");class ConsoleErrorService{log(method,...args){console[method](SYSTEM_LOG_MARKER,`[CLIENT (${this.context})]`,...args)}report(method,severity,...args){const[error,extra]=args;this.beforeReportHandlers.forEach((handler=>handler(severity,error,extra)));this.log(method,...args)}createChild(name){const child=new ConsoleErrorService(`${this.context}:${name}`);child.beforeReportHandlers=this.beforeReportHandlers;return child}withOfflineStatus(){}setContext(context){this.log("debug","context set",context)}setTag(key,value){this.log("debug","tag set",key,value)}addBeforeSendHandler(){}addBeforeReportHandler(handler){this.beforeReportHandlers.push(handler)}setFilters(){}setSensitiveStrings(sensitiveStrings){}addBreadCrumb(breadCrumb){this.log("debug","breadcrumb added",breadCrumb)}debug(error,extra){this.report("debug","debug",error,extra)}info(...args){this.report("info","info",...args)}warn(...args){this.report("warn","warning",...args)}warning(error,extra){this.report("warn","warning",error,extra)}warningException(error,extra){this.report("warn","warning",error,extra)}error(error,extra){this.report("error","error",error,extra)}errorException(error,extra){this.report("error","error",error,extra)}critical(error,extra){this.report("error","fatal",error,extra)}criticalException(error,extra){this.report("error","fatal",error,extra)}constructor(context){this.context=context;this.beforeReportHandlers=[]}}function listMarkerStyleSheet(){const sheet=new CSSStyleSheet;sheet.replaceSync?.(`\n li::marker {\n color: var(--canva-color, inherit);\n }\n`);return sheet}function addAdoptedStyleSheets(){if(document.adoptedStyleSheets==null)return;document.adoptedStyleSheets=[...document.adoptedStyleSheets,listMarkerStyleSheet()]}class RpcCodeletImageResolver{getMedia(ref){const result=this.cache.get(this.toKey(ref));return result}loadMedia(ref){const key=this.toKey(ref);const loadPromise=this.loadCache.get(key);if(loadPromise!=null)return loadPromise;if(this.cache.has(key))return Promise.resolve(this.cache.get(key));const processed=this.resolveAndCacheMedia(key,ref).finally((()=>{this.loadCache.delete(key)}));this.loadCache.set(key,processed);this.previewCache.delete(key);return processed}getPreviewUrl(ref){const media=this.getMedia(ref);return media?media.url:this.previewCache.get(this.toKey(ref))}setPreviewUrl(ref,url){this.previewCache.set(this.toKey(ref),url)}toKey(ref){return`${ref.id}:${ref.version}`}async resolveAndCacheMedia(key,ref){const result=await this.editingService.getMedia(new GetMediaRequest({mediaRef:ref}));if(result.images.length===0)return undefined;const image=result.images[0];this.cache.set(key,image);return image}constructor(editingService){this.editingService=editingService;this.loadCache=new Map;this.cache=new Map;this.previewCache=new Map}}const DATA_FINGERPRINT_ID="data-cf-id";class Fingerprinting{observe(){document.querySelectorAll("*").forEach((e=>this.maybeFingerPrint(e)));this.mutationObserver.observe(document.body,{childList:true,subtree:true,attributes:true,characterData:true,attributeFilter:["id","class"]})}dispose(){this.mutationObserver.disconnect()}maybeFingerPrint(element){if(uniqueIdentifier(element)!=null||element.parentElement==null)return;const ancestors=[element.parentElement,element];while(ancestors[0]!=null&&uniqueIdentifier(ancestors[0],false)==null){if(ancestors[0].parentElement==null)return;ancestors.unshift(ancestors[0].parentElement)}const ancestorSelector=ancestors.map((a=>uniqueIdentifier(a,false)??a.tagName));const className=element.className;const textContent=textOnlyContent(element,50);if(!className&&!textContent)return;const fingerprint=new Fingerprint({selector:ancestorSelector.join(">"),class:className,textContent});const fingerprintBase64=btoa(JSON.stringify(Fingerprint.serialize(fingerprint)));if(this.fingerprints.has(fingerprintBase64)){document.querySelectorAll(`[${DATA_FINGERPRINT_ID}="${fingerprintBase64}"]`).forEach((clash=>{clash.removeAttribute(DATA_FINGERPRINT_ID)}));return}this.fingerprints.add(fingerprintBase64);element.setAttribute("data-cf-id",fingerprintBase64)}constructor(){this.fingerprints=new Set;this.mutationObserver=new MutationObserver((mutations=>this.onDomMutation(mutations)));this.onDomMutation=mutations=>{for(const mutation of mutations)switch(mutation.type){case"attributes":case"characterData":if(!(mutation.target instanceof Element))continue;this.maybeFingerPrint(mutation.target);break;case"childList":for(const node of mutation.addedNodes){if(!(node instanceof Element))continue;this.maybeFingerPrint(node);node.querySelectorAll("*").forEach((e=>this.maybeFingerPrint(e)))}break;default:throw new UnreachableError(mutation.type)}}}}function textOnlyContent(element,maxLength){if(element.firstElementChild!=null)return undefined;let result="";for(const node of element.childNodes){if(node.nodeType!==Node.TEXT_NODE)return undefined;result+=node.textContent;if(result.trim().length>=maxLength)break}const bytes=(new TextEncoder).encode(result.trim().slice(0,maxLength).trim());return String.fromCharCode(...bytes)}function queryAllSelectableElements(element){return element.querySelectorAll(`[id], [${DATA_FINGERPRINT_ID}]`)}function uniqueIdentifier(element,includeFingerprint=true){if(element===document.body)return"body";if(element.id)return`#${element.id}`;if(includeFingerprint&&element.hasAttribute(DATA_FINGERPRINT_ID))return`[${DATA_FINGERPRINT_ID}='${element.getAttribute(DATA_FINGERPRINT_ID)}']`;return undefined}const PAGE_ROOT_TEMPLATE_ID="__page-root";const LEGACY_PAGE_ROOT_TEMPLATE_ID="background";function getPageRootTemplateId(config){return config.has(PAGE_ROOT_TEMPLATE_ID)?PAGE_ROOT_TEMPLATE_ID:LEGACY_PAGE_ROOT_TEMPLATE_ID}function isBackground(element){return element.selector==="body"}function isPageRootElement(templateId,config){if(templateId===PAGE_ROOT_TEMPLATE_ID)return true;if(templateId===LEGACY_PAGE_ROOT_TEMPLATE_ID)return!config.has(PAGE_ROOT_TEMPLATE_ID);return false}class BackgroundColorEditApplicator{apply(edit){Preconditions.checkState(edit.type==="BACKGROUND_COLOR");const color=edit.color;const isGradient=color.startsWith("linear-gradient")||color.startsWith("radial-gradient");if(this.rule!=null){this.rule.dispose();this.rule=undefined}try{const commonStyles=isBackground({selector:this.selector})?{["background-size"]:"100vw 100vh"}:{};this.rule=this.styles.insert({[this.selector]:isGradient?{...commonStyles,["background-image"]:color,["background-color"]:"unset"}:{...commonStyles,["background-image"]:"unset",["background-color"]:color}})}catch{}}dispose(){if(this.rule==null)return;this.rule.dispose();this.rule=undefined}constructor(selector,styles){this.selector=selector;this.styles=styles}}class EditApplicatorCache{apply(edit){const serialized=JSON.stringify(ElementEditOperation.serialize(edit));if(this.serializedEdit!=null&&this.serializedEdit===serialized)return;this.applicator.apply(edit);this.serializedEdit=serialized}dispose(){this.applicator.dispose();this.serializedEdit=undefined}constructor(applicator){this.applicator=applicator}}class LinkEditApplicator{apply(_edit){}dispose(){}constructor(selector){this.selector=selector}}const PLACEHOLDER_CONTENT="linear-gradient(#a9a9a9, #a9a9a9)";class MediaReplaceEditApplicator{apply(edit){Preconditions.checkState(edit.type==="MEDIA_REPLACE");this.applyMediaReplace(edit.mediaRef)}dispose(){this.disposed=true;this.dragAndDrop.clearPreview(this.selector);if(this.rule==null)return;this.rule.dispose();this.rule=undefined}async applyMediaReplace(mediaRef){if(mediaRef==null){this.setContent(PLACEHOLDER_CONTENT);return}const cachedMedia=this.imageResolver.getMedia(mediaRef);if(cachedMedia!=null){this.setContent(`url('${cachedMedia.url}')`);return}const previewUrl=this.imageResolver.getPreviewUrl(mediaRef);this.setContent(previewUrl!=null?`url('${previewUrl}')`:PLACEHOLDER_CONTENT);const media=await this.imageResolver.loadMedia(mediaRef);if(this.disposed||media==null)return;this.setContent(`url('${media.url}')`)}setContent(content){if(this.disposed)return;try{const newRule=this.styles.insert({[this.selector]:{content}});this.rule?.dispose();this.rule=newRule}catch{}}constructor(selector,styles,imageResolver,dragAndDrop){this.selector=selector;this.styles=styles;this.imageResolver=imageResolver;this.dragAndDrop=dragAndDrop;this.disposed=false}}class ReorderEditApplicator{apply(edit){Preconditions.checkState(edit.type==="REORDER");try{const rule=this.styles.insert({[this.selector]:{order:edit.order.toString()}});this.rule?.dispose();this.rule=rule}catch{}}dispose(){this.rule?.dispose();this.rule=undefined}constructor(selector,styles){this.selector=selector;this.styles=styles}}const AttrKey={FONT_WEIGHT:"font-weight",FONT_STYLE:"font-style",COLOR:"color",DECORATION:"decoration",STRIKETHROUGH:"strikethrough",LINK:"link",FONT_FAMILY:"font-family",FONT_SIZE:"font-size",LEADING:"leading",DIRECTION:"direction",TRACKING:"tracking",TEXT_TRANSFORM:"text-transform",TEXT_ALIGN:"text-align",LIST_MARKER:"list-marker",LIST_LEVEL:"list-level",SEMANTICS:"semantics"};const RICHTEXT_SOFT_BREAK="\u2028";const NAMED_WEIGHT_TO_NUMERIC={thin:100,extralight:200,light:300,normal:400,medium:500,semibold:600,bold:700,ultrabold:800,heavy:900};function richtextEscapeHtmlForCodelet(s){return s.replace(/&/g,"&").replace(//g,">").replace(/"/g,""")}function text2FontWeightToCssNumber(weight){const fromNamed=NAMED_WEIGHT_TO_NUMERIC[weight];if(fromNamed!=null)return fromNamed;if(/^\d{1,3}$/.test(weight)){const n=parseInt(weight,10);if(n>=1&&n<=1e3)return n}return undefined}function richtextAttrsToInlineStyle(as){const chunks=[];const deco=[];if(as[AttrKey.DECORATION]==="underline")deco.push("underline");if(as[AttrKey.STRIKETHROUGH]==="strikethrough")deco.push("line-through");if(deco.length>0)chunks.push(`text-decoration:${deco.join(" ")}`);else if(as[AttrKey.DECORATION]==="none"&&as[AttrKey.STRIKETHROUGH]==="none")chunks.push("text-decoration:none");const color=as[AttrKey.COLOR];if(color!=null&&color!==""){const cssColor=color==="transparent"||color.startsWith("linear-gradient(")||color.startsWith("radial-gradient(")?color:color.startsWith("#")?color:`#${color}`;chunks.push(`color:${cssColor}`)}const w=as[AttrKey.FONT_WEIGHT];if(w!=null&&w!=="bold"&&w!=="normal"){const wNum=text2FontWeightToCssNumber(w);if(wNum!=null)chunks.push(`font-weight:${wNum}`)}return chunks.length>0?chunks.join(";"):undefined}function richtextBlockAttrsToInlineStyle(as){const chunks=[];const align=as[AttrKey.TEXT_ALIGN];if(align!=null)chunks.push(`text-align:${align}`);const dir=as[AttrKey.DIRECTION];if(dir==="rtl"||dir==="ltr")chunks.push(`direction:${dir}`);const transform=as[AttrKey.TEXT_TRANSFORM];if(transform==="uppercase"||transform==="lowercase"||transform==="capitalize")chunks.push(`text-transform:${transform}`);const leading=as[AttrKey.LEADING];if(leading!=null&&leading!=="1400"){const n=parseFloat(leading)/1e3;if(Number.isFinite(n))chunks.push(`line-height:${n}`)}const tracking=as[AttrKey.TRACKING];if(tracking!=null&&tracking!=="0"){const n=parseFloat(tracking)/1e3;if(Number.isFinite(n)&&n!==0)chunks.push(`letter-spacing:${n}em`)}const fontSize=as[AttrKey.FONT_SIZE];if(fontSize!=null&&fontSize!=="16"){const n=parseFloat(fontSize);if(Number.isFinite(n))chunks.push(`font-size:${n}px`)}const fontFamily=as[AttrKey.FONT_FAMILY];if(typeof fontFamily==="string"&&fontFamily!=="")chunks.push(`font-family:'${fontFamily}'`);return chunks.length>0?chunks.join(";"):undefined}function wrapRichtextParagraph(inner,blockAttrs){const style=richtextBlockAttrsToInlineStyle(blockAttrs);const content=inner===""?"
":inner;const tag=richtextSemanticsToTag(blockAttrs[AttrKey.SEMANTICS]);return style!=null?`<${tag} style="${style}">${content}`:`<${tag}>${content}`}function richtextSemanticsToTag(semantics){switch(semantics){case"p":return"p";case"h1":case"h2":case"h3":case"h4":case"h5":case"h6":return semantics;case"blockquote":return"blockquote";default:return"div"}}function richtextIsListItem(blockAttrs){const marker=blockAttrs[AttrKey.LIST_MARKER];return marker!=null&&marker!=="none"}function richtextListContainerForMarker(marker){switch(marker){case"decimal":case"lower-alpha":case"lower-roman":return{tag:"OL",listStyleType:marker};case"circle":case"square":case"disc":return{tag:"UL",listStyleType:marker};default:return{tag:"UL",listStyleType:"disc"}}}function wrapRichtextListItem(inner,blockAttrs){const style=richtextBlockAttrsToInlineStyle(blockAttrs);const content=inner===""?"
":inner;return style!=null?`
  • ${content}`:`
  • ${content}`}function richtextListItemLevel(blockAttrs){const raw=blockAttrs[AttrKey.LIST_LEVEL];if(raw!=null){const n=parseInt(raw,10);if(Number.isFinite(n)&&n>=1)return n}return 1}function assembleRichtextBlocks(paragraphs){const out=[];const stack=[];let openLiLevel=null;const closeList=()=>{const top=stack.pop();if(openLiLevel===top.level){out.push("
  • ");const parentLevel=top.level-1;openLiLevel=parentLevel>=1&&stack.some((entry=>entry.level===parentLevel))?parentLevel:null}out.push(``)};const closeListsWhile=predicate=>{while(stack.length>0&&predicate(stack[stack.length-1]))closeList()};for(const para of paragraphs){if(!richtextIsListItem(para.blockAttrs)){closeListsWhile((()=>true));out.push(wrapRichtextParagraph(para.inner,para.blockAttrs));continue}const marker=String(para.blockAttrs[AttrKey.LIST_MARKER]);const{tag:rawTag,listStyleType}=richtextListContainerForMarker(marker);const tag=rawTag.toLowerCase();const level=richtextListItemLevel(para.blockAttrs);closeListsWhile((top=>top.level>level));if(openLiLevel!=null&&openLiLevel>=level){out.push("");openLiLevel=null}closeListsWhile((top=>top.level===level&&(top.tag!==tag||top.listStyleType!==listStyleType)));while(stack.length===0||stack[stack.length-1].level`);stack.push({tag,listStyleType,level:nextLevel})}out.push(wrapRichtextListItem(para.inner,para.blockAttrs));openLiLevel=level}closeListsWhile((()=>true));return out.join("")}function wrapRichtextInlineSegmentRun(text,as){const inner=richtextEscapeHtmlForCodelet(text);const style=richtextAttrsToInlineStyle(as);const isBold=as[AttrKey.FONT_WEIGHT]==="bold";const isItalic=as[AttrKey.FONT_STYLE]==="italic";const link=as[AttrKey.LINK];let html=style!=null?`${inner}`:inner;if(isItalic)html=`${html}`;if(isBold)html=`${html}`;if(typeof link==="string"&&link!=="")html=`${html}`;return html}function wrapRichtextInlineSegment(text,as){return text.split(RICHTEXT_SOFT_BREAK).map((part=>wrapRichtextInlineSegmentRun(part,as))).join("
    ")}function*iterRichtextProtoChunks(rt){const characterItems=rt.doNotUseCharacters;const attributeItems=rt.doNotUseAttributes;const charQueue=[];for(const item of characterItems)switch(item.type){case"CHARACTERS":if(item.characters.length>0)charQueue.push({text:item.characters});break;case"TOMBSTONES":if(item.tombstones>0)charQueue.push({text:"\0".repeat(item.tombstones)});break;default:throw new UnreachableError(item)}const currentAttrs={};let charIdx=0;let charOffset=0;const consumeChars=function*(n){let remaining=n;while(remaining>0&&charIdx0)yield{text:liveOnly,attrs:{...currentAttrs}}}else if(slice.length>0)yield{text:slice,attrs:{...currentAttrs}};charOffset+=take;remaining-=take;if(charOffset>=chunk.text.length){charIdx++;charOffset=0}}};for(const item of attributeItems)switch(item.type){case"CHANGE":for(const[k,change]of item.attributes)if(change.r===undefined)delete currentAttrs[k];else currentAttrs[k]=change.r;break;case"RETAIN":yield*consumeChars(item.length);break;default:throw new UnreachableError(item)}}function richtextSingleParagraphInnerHtml(inner,blockAttrs){const content=inner===""?"
    ":inner;const style=richtextBlockAttrsToInlineStyle(blockAttrs);if(style==null)return content;return`${content}`}function collectRichtextParagraphs(rt){const paragraphs=[];let currentInline=[];let lastSeenAttrs={};for(const chunk of iterRichtextProtoChunks(rt)){lastSeenAttrs=chunk.attrs;const segments=chunk.text.split("\n");for(let i=0;i0)currentInline.push(wrapRichtextInlineSegment(seg,chunk.attrs));if(i0)paragraphs.push({inner:currentInline.join(""),blockAttrs:lastSeenAttrs});return paragraphs}function richtext2ToHtmlString(rt){const paragraphs=collectRichtextParagraphs(rt);if(paragraphs.length===1&&!richtextIsListItem(paragraphs[0].blockAttrs))return richtextSingleParagraphInnerHtml(paragraphs[0].inner,paragraphs[0].blockAttrs);return assembleRichtextBlocks(paragraphs)}class RichtextEditApplicator{apply(edit){Preconditions.checkState(edit.type==="RICHTEXT");const target=document.querySelector(this.selector);if(target==null)return;target.innerHTML=richtext2ToHtmlString(edit.html)}dispose(){}constructor(selector){this.selector=selector}}class RotationEditApplicator{apply(edit){Preconditions.checkState(edit.type==="ROTATION");try{const newRule=this.styles.insert({[this.selector]:{rotate:`${edit.rotation}deg`}});this.rule?.dispose();this.rule=newRule}catch{}}dispose(){this.rule?.dispose();this.rule=undefined}constructor(selector,styles){this.selector=selector;this.styles=styles}}class ScaleEditApplicator{apply(edit){Preconditions.checkState(edit.type==="SCALE");try{const newRule=this.styles.insert({[this.selector]:{scale:edit.scale.toString()}});this.rule?.dispose();this.rule=newRule}catch{}}dispose(){this.rule?.dispose();this.rule=undefined}constructor(selector,styles){this.selector=selector;this.styles=styles}}class TranslationEditApplicator{apply(edit){Preconditions.checkState(edit.type==="TRANSLATION");try{const newRule=this.styles.insert({[this.selector]:{translate:`${edit.translateX}px ${edit.translateY}px`}});this.rule?.dispose();this.rule=newRule}catch{}}dispose(){this.rule?.dispose();this.rule=undefined}constructor(selector,styles){this.selector=selector;this.styles=styles}}class CssRule{get cssText(){const declarations=Object.entries(this.styles).map((([prop,value])=>value?`${prop}: ${value} !important;`:"")).join(" ");return`${this.selector} { ${declarations} }`}constructor(selector,styles){this.selector=selector;this.styles=styles}}class CssRuleSet{insert(rule){const ruleIndex=this.sheet.insertRule(rule.cssText,this.sheet.cssRules.length);this.rules.push([...this.sheet.cssRules][ruleIndex])}dispose(){this.rules.forEach((rule=>{const ruleIndex=[...this.sheet.cssRules].indexOf(rule);this.sheet.deleteRule(ruleIndex)}));this.rules=[]}constructor(sheet){this.sheet=sheet;this.rules=[]}}class CssStyles{dispose(){if(document.adoptedStyleSheets!=null)document.adoptedStyleSheets=document.adoptedStyleSheets.filter((sheet=>sheet!==this.sheet))}insert(rules){const ruleSet=new CssRuleSet(this.sheet);for(const selector in rules){const styles=rules[selector];if(styles==null)continue;const cssRule=new CssRule(selector,styles);ruleSet.insert(cssRule)}return ruleSet}constructor(){this.sheet=new CSSStyleSheet;if(document.adoptedStyleSheets!=null)document.adoptedStyleSheets=[...document.adoptedStyleSheets,this.sheet]}}class DragAndDrop2{showPreview(selector,previewUrl){if(this.activeSelector===selector&&this.activePreviewUrl===previewUrl)return;this.clearPreview();try{this.activeRule=this.styles.insert({[selector]:{content:`url('${previewUrl}')`}});this.activeSelector=selector;this.activePreviewUrl=previewUrl}catch{}}getPreviewUrl(selector){return this.activeSelector===selector?this.activePreviewUrl:undefined}clearPreview(selector){if(selector!=null&&this.activeSelector!==selector)return;this.activeRule?.dispose();this.activeSelector=undefined;this.activePreviewUrl=undefined;this.activeRule=undefined}constructor(styles){this.styles=styles}}class Renderer{registerDragPreview(mediaRef,previewUrl){this.imageResolver.setPreviewUrl(mediaRef,previewUrl)}showDragPreview(selector,previewUrl){this.dragAndDrop.showPreview(selector,previewUrl)}clearDragPreview(){this.dragAndDrop.clearPreview()}applyAll(edits){const keys=new Set;edits.forEach((edit=>{const key=`${edit.selector}:${edit.operation.type}`;keys.add(key);if(!this.appliedEdits.has(key))this.appliedEdits.set(key,new EditApplicatorCache(this.mapEdit(edit)));this.appliedEdits.get(key)?.apply(edit.operation)}));const deletes=[...this.appliedEdits.keys()].filter((x=>!keys.has(x)));deletes.forEach((key=>{this.appliedEdits.get(key)?.dispose();this.appliedEdits.delete(key)}))}dispose(){const edits=[...this.appliedEdits.entries()];edits.forEach((([key,edit])=>{this.appliedEdits.delete(key);edit.dispose()}));this.styles.dispose()}mapEdit(edit){switch(edit.type){case"ELEMENT_EDIT":switch(edit.operation.type){case"BACKGROUND_COLOR":return new BackgroundColorEditApplicator(edit.selector,this.styles);case"TRANSLATION":return new TranslationEditApplicator(edit.selector,this.styles);case"ROTATION":return new RotationEditApplicator(edit.selector,this.styles);case"SCALE":return new ScaleEditApplicator(edit.selector,this.styles);case"MEDIA_REPLACE":return new MediaReplaceEditApplicator(edit.selector,this.styles,this.imageResolver,this.dragAndDrop);case"RICHTEXT":return new RichtextEditApplicator(edit.selector);case"LINK":return new LinkEditApplicator(edit.selector);case"REORDER":return new ReorderEditApplicator(edit.selector,this.styles);default:throw new UnreachableError(edit.operation)}default:throw new UnreachableError(edit.type)}}constructor(imageResolver){this.imageResolver=imageResolver;this.appliedEdits=new Map;this.styles=new CssStyles;this.dragAndDrop=new DragAndDrop2(this.styles)}}function exists(t){return t!=null}function getBounds(element){if(element===document.body)return{top:0,left:0,width:element.scrollWidth,height:element.scrollHeight,rotation:undefined};const boundingRect=element.getBoundingClientRect();const matrices=getElementMatrices(element);const rotation=getElementRotation(matrices);const radians=rotation*(Math.PI/180);const cos=Math.abs(Math.cos(radians));const sin=Math.abs(Math.sin(radians));const layoutW=element.offsetWidth;const layoutH=element.offsetHeight;const expectedBoundingW=layoutW*cos+layoutH*sin;const expectedBoundingH=layoutW*sin+layoutH*cos;const scaleX=boundingRect.width/expectedBoundingW;const scaleY=boundingRect.height/expectedBoundingH;const cx=boundingRect.left+boundingRect.width/2;const cy=boundingRect.top+boundingRect.height/2;return{top:cy-layoutH*scaleY/2,left:cx-layoutW*scaleX/2,width:layoutW*scaleX,height:layoutH*scaleY,rotation}}function getElementRotation(matrices){const matrix=matrices.reduce(((acc,m)=>acc.multiply(m)),new DOMMatrix);return Math.atan2(matrix.b,matrix.a)*(180/Math.PI)}function getElementScale(matrices){const matrix=matrices.reduce(((acc,m)=>acc.multiply(m)),new DOMMatrix);return Math.sqrt(matrix.a**2+matrix.b**2)}function getElementMatrices(element){const matrices=[];let el=element;while(el&&el!==document.documentElement){matrices.push(getElementMatrix(el));el=el.parentElement}return matrices}function getElementMatrix(element){const style=window.getComputedStyle(element);const transform=new DOMMatrix(style.transform);const rotate=style.rotate??"none";const parts=rotate.trim().split(/\s+/);const is2DRotation=rotate!=="none"&&parts.length===1;const rotation=new DOMMatrix(is2DRotation?`rotate(${rotate})`:"");const scale=style.scale??"";const s=new DOMMatrix(scale&&scale!=="none"?`scale(${parseFloat(scale)})`:"");return rotation.multiply(s).multiply(transform)}const GradientType={LINEAR:"linear",RADIAL:"radial"};const NAMED_COLOR_MAP={["aliceblue"]:"#f0f8ff",["antiquewhite"]:"#faebd7",["aqua"]:"#00ffff",["aquamarine"]:"#7fffd4",["azure"]:"#f0ffff",["beige"]:"#f5f5dc",["bisque"]:"#ffe4c4",["black"]:"#000000",["blanchedalmond"]:"#ffebcd",["blue"]:"#0000ff",["blueviolet"]:"#8a2be2",["brown"]:"#a52a2a",["burlywood"]:"#deb887",["cadetblue"]:"#5f9ea0",["chartreuse"]:"#7fff00",["chocolate"]:"#d2691e",["coral"]:"#ff7f50",["cornflowerblue"]:"#6495ed",["cornsilk"]:"#fff8dc",["crimson"]:"#dc143c",["cyan"]:"#00ffff",["darkblue"]:"#00008b",["darkcyan"]:"#008b8b",["darkgoldenrod"]:"#b8860b",["darkgray"]:"#a9a9a9",["darkgreen"]:"#006400",["darkgrey"]:"#a9a9a9",["darkkhaki"]:"#bdb76b",["darkmagenta"]:"#8b008b",["darkolivegreen"]:"#556b2f",["darkorange"]:"#ff8c00",["darkorchid"]:"#9932cc",["darkred"]:"#8b0000",["darksalmon"]:"#e9967a",["darkseagreen"]:"#8fbc8f",["darkslateblue"]:"#483d8b",["darkslategray"]:"#2f4f4f",["darkslategrey"]:"#2f4f4f",["darkturquoise"]:"#00ced1",["darkviolet"]:"#9400d3",["deeppink"]:"#ff1493",["deepskyblue"]:"#00bfff",["dimgray"]:"#696969",["dimgrey"]:"#696969",["dodgerblue"]:"#1e90ff",["firebrick"]:"#b22222",["floralwhite"]:"#fffaf0",["forestgreen"]:"#228b22",["fuchsia"]:"#ff00ff",["gainsboro"]:"#dcdcdc",["ghostwhite"]:"#f8f8ff",["gold"]:"#ffd700",["goldenrod"]:"#daa520",["gray"]:"#808080",["green"]:"#008000",["greenyellow"]:"#adff2f",["grey"]:"#808080",["honeydew"]:"#f0fff0",["hotpink"]:"#ff69b4",["indianred"]:"#cd5c5c",["indigo"]:"#4b0082",["ivory"]:"#fffff0",["khaki"]:"#f0e68c",["lavender"]:"#e6e6fa",["lavenderblush"]:"#fff0f5",["lawngreen"]:"#7cfc00",["lemonchiffon"]:"#fffacd",["lightblue"]:"#add8e6",["lightcoral"]:"#f08080",["lightcyan"]:"#e0ffff",["lightgoldenrodyellow"]:"#fafad2",["lightgray"]:"#d3d3d3",["lightgreen"]:"#90ee90",["lightgrey"]:"#d3d3d3",["lightpink"]:"#ffb6c1",["lightsalmon"]:"#ffa07a",["lightseagreen"]:"#20b2aa",["lightskyblue"]:"#87cefa",["lightslategray"]:"#778899",["lightslategrey"]:"#778899",["lightsteelblue"]:"#b0c4de",["lightyellow"]:"#ffffe0",["lime"]:"#00ff00",["limegreen"]:"#32cd32",["linen"]:"#faf0e6",["magenta"]:"#ff00ff",["maroon"]:"#800000",["mediumaquamarine"]:"#66cdaa",["mediumblue"]:"#0000cd",["mediumorchid"]:"#ba55d3",["mediumpurple"]:"#9370db",["mediumseagreen"]:"#3cb371",["mediumslateblue"]:"#7b68ee",["mediumspringgreen"]:"#00fa9a",["mediumturquoise"]:"#48d1cc",["mediumvioletred"]:"#c71585",["midnightblue"]:"#191970",["mintcream"]:"#f5fffa",["mistyrose"]:"#ffe4e1",["moccasin"]:"#ffe4b5",["navajowhite"]:"#ffdead",["navy"]:"#000080",["oldlace"]:"#fdf5e6",["olive"]:"#808000",["olivedrab"]:"#6b8e23",["orange"]:"#ffa500",["orangered"]:"#ff4500",["orchid"]:"#da70d6",["palegoldenrod"]:"#eee8aa",["palegreen"]:"#98fb98",["paleturquoise"]:"#afeeee",["palevioletred"]:"#db7093",["papayawhip"]:"#ffefd5",["peachpuff"]:"#ffdab9",["peru"]:"#cd853f",["pink"]:"#ffc0cb",["plum"]:"#dda0dd",["powderblue"]:"#b0e0e6",["purple"]:"#800080",["rebeccapurple"]:"#663399",["red"]:"#ff0000",["rosybrown"]:"#bc8f8f",["royalblue"]:"#4169e1",["saddlebrown"]:"#8b4513",["salmon"]:"#fa8072",["sandybrown"]:"#f4a460",["seagreen"]:"#2e8b57",["seashell"]:"#fff5ee",["sienna"]:"#a0522d",["silver"]:"#c0c0c0",["skyblue"]:"#87ceeb",["slateblue"]:"#6a5acd",["slategray"]:"#708090",["slategrey"]:"#708090",["snow"]:"#fffafa",["springgreen"]:"#00ff7f",["steelblue"]:"#4682b4",["tan"]:"#d2b48c",["teal"]:"#008080",["thistle"]:"#d8bfd8",["tomato"]:"#ff6347",["turquoise"]:"#40e0d0",["violet"]:"#ee82ee",["wheat"]:"#f5deb3",["white"]:"#ffffff",["whitesmoke"]:"#f5f5f5",["yellow"]:"#ffff00",["yellowgreen"]:"#9acd32"};function normalizeSingleColorString(color){if(color in NAMED_COLOR_MAP)return{color:NAMED_COLOR_MAP[color],transparency:0};if(color==="transparent")return{color:"#000000",transparency:1};const[_,hex]=color.match(/^#?([a-fA-F0-9]{3,8})$/)??["",""];switch(hex.length){case 3:return{color:`#${hex.charAt(0).repeat(2)}${hex.charAt(1).repeat(2)}${hex.charAt(2).repeat(2)}`.toLowerCase(),transparency:0};case 6:return{color:`#${hex}`.toLowerCase(),transparency:0};case 8:{const alpha=parseInt(hex.substring(6,8),16);return{color:`#${hex.substring(0,6)}`.toLowerCase(),transparency:1-alpha/255}}default:break}const[__,r_,g_,b_,a_]=color.match(/^rgba?\(\s*(\d{1,3}%?)\s*,\s*(\d{1,3}%?)\s*,\s*(\d{1,3}%?)\s*(?:,\s*([\d.]+)?%?\s*)?\)$/)??["","","",""];const r=parseInt(r_,10);const g=parseInt(g_,10);const b=parseInt(b_,10);const parsedA=parseFloat(a_);const a=a_!==undefined&&a_!==""&&!Number.isNaN(parsedA)?parsedA:1;if(r>=0&&r<=255&&g>=0&&g<=255&&b>=0&&b<=255)return{color:`#${r.toString(16).padStart(2,"0")}${g.toString(16).padStart(2,"0")}${b.toString(16).padStart(2,"0")}`,transparency:1-a};return undefined}function parseCssAngle(angleString){switch(angleString){case"to right":return 0;case"to bottom right":case"to right bottom":return 45;case"to bottom":return 90;case"to bottom left":case"to left bottom":return 135;case"to left":return 180;case"to top left":case"to left top":return 225;case"to top":return 270;case"to top right":case"to right top":return 315;default:break}const match=angleString.match(/^([-+]?[\d.]+)(deg|rad|grad|turn)?$/);if(!match)return 0;const[,valueStr,unit="deg"]=match;const value=parseFloat(valueStr);if(isNaN(value))return 0;switch(unit){case"deg":return value;case"rad":return value*180/Math.PI;case"grad":return value*.9;case"turn":return value*360;default:return 0}}function normalizeAngle(degrees){const n=(degrees%360+360)%360;return n>180?n-360:n}function splitGradientStops(str){const parts=[];let current="";let depth=0;for(const char of str){if(char==="("){depth++;current+=char}else if(char===")"){depth--;if(depth<0)throw new Error("Malformed gradient string: unmatched closing parenthesis");current+=char}else if(char===","&&depth===0){parts.push(current);current=""}else current+=char}if(current)parts.push(current);return parts}function trimTrailingStop(color){return color.replace(/\s+[\d.]+%?\s*$/,"").trim()}function stringToGradient(color){const[_,linearGradient]=color.match(/^linear-gradient\((.*)\)$/)??["",""];if(linearGradient){const parts=splitGradientStops(linearGradient);if(parts.length===0)return undefined;const hasAngle=parts.length>0&&!normalizeSingleColorString(trimTrailingStop(parts[0]));const rotation=hasAngle?normalizeAngle(parseCssAngle(parts[0])):0;const colorParts=hasAngle?parts.slice(1):parts;const colorStops=colorParts.map((stop=>normalizeSingleColorString(trimTrailingStop(stop.trim())))).filter((colorStop=>colorStop!==undefined));const stopCount=colorStops.length;if(stopCount<2)return undefined;return{type:GradientType.LINEAR,stops:colorStops.map((({color:stopColor,transparency},i)=>({color:stopColor,transparency,position:stopCount>1?i/(stopCount-1):0}))),rotation}}const[__,radialGradient]=color.match(/^radial-gradient\((.*)\)$/)??["",""];if(radialGradient){const parts=splitGradientStops(radialGradient);if(parts.length===0)return undefined;const hasRadialPosition=parts.length>0&&!normalizeSingleColorString(trimTrailingStop(parts[0]));const colorParts=hasRadialPosition?parts.slice(1):parts;const colorStops=colorParts.map((stop=>normalizeSingleColorString(trimTrailingStop(stop.trim())))).filter((colorStop=>colorStop!==undefined));const stopCount=colorStops.length;if(stopCount<2)return undefined;return{type:GradientType.RADIAL,stops:colorStops.map((({color:stopColor,transparency},i)=>({color:stopColor,transparency,position:stopCount>1?i/(stopCount-1):0}))),center:{top:.5,left:.5}}}return undefined}function normalizeCssColorValue(color){const trimmed=color.trim();if(trimmed.toLowerCase()==="transparent")return"transparent";const normalizedSingleColorString=normalizeSingleColorString(trimmed.toLowerCase());if(normalizedSingleColorString)return normalizedSingleColorString.color;if(stringToGradient(trimmed))return trimmed;return undefined}const html_to_codelet_edit_mapper_AttrKey={FONT_WEIGHT:"font-weight",FONT_STYLE:"font-style",COLOR:"color",DECORATION:"decoration",STRIKETHROUGH:"strikethrough",LINK:"link",FONT_FAMILY:"font-family",FONT_SIZE:"font-size",LEADING:"leading",DIRECTION:"direction",TRACKING:"tracking",TEXT_TRANSFORM:"text-transform",TEXT_ALIGN:"text-align",LIST_MARKER:"list-marker",LIST_LEVEL:"list-level",SEMANTICS:"semantics"};const fontWeightNames=["normal","thin","extralight","light","medium","semibold","bold","ultrabold","heavy"];const listMarkers=["none","disc","circle","square","decimal","lower-alpha","lower-roman"];const html_to_codelet_edit_mapper_RICHTEXT_SOFT_BREAK="\u2028";const fontFamilyRegex=/^Y[A-Za-z0-9_-]{10},\d+$/;function splitCssFontList(value){const out=[];const pattern=/\s*(?:'([^']*)'|"([^"]*)"|([^,]+?))\s*(?:,|$)/g;let m;while((m=pattern.exec(value))!=null){const v=(m[1]??m[2]??m[3]??"").trim();if(v!=="")out.push(v);if(m.index===pattern.lastIndex)pattern.lastIndex++}return out}function richtextTagToSemantics(tagName){switch(tagName.toUpperCase()){case"P":return"p";case"H1":return"h1";case"H2":return"h2";case"H3":return"h3";case"H4":return"h4";case"H5":return"h5";case"H6":return"h6";case"BLOCKQUOTE":return"blockquote";default:return undefined}}function richtextTagToInlineAttrs(tagName){switch(tagName.toUpperCase()){case"B":case"STRONG":return{[html_to_codelet_edit_mapper_AttrKey.FONT_WEIGHT]:"bold"};case"I":case"EM":return{[html_to_codelet_edit_mapper_AttrKey.FONT_STYLE]:"italic"};case"U":return{[html_to_codelet_edit_mapper_AttrKey.DECORATION]:"underline"};case"S":case"DEL":return{[html_to_codelet_edit_mapper_AttrKey.STRIKETHROUGH]:"strikethrough"};default:return{}}}function mergeAttrs(base,extra){return{...base,...extra}}const HTML_VOID_TAG_NAMES=new Set(["AREA","BASE","BR","COL","EMBED","HR","IMG","INPUT","LINK","META","PARAM","SOURCE","TRACK","WBR"]);function parseHtmlOpeningTagAttributes(fullTag){const trimmed=fullTag.trim();const closeIdx=trimmed.endsWith("/>")?trimmed.length-2:trimmed.endsWith(">")?trimmed.length-1:trimmed.length;if(!trimmed.startsWith("<")||closeIdx<=1)return{};const inner=trimmed.slice(1,closeIdx);let pos=0;while(pos/]+))/g;let m;while((m=attrPattern.exec(attrSection))!=null)attrs[m[1].toLowerCase()]=(m[2]??m[3]??m[4]??"").trim();return attrs}function richtextElementToBlockAttrs(node){const attrs=node.attrs;if(attrs==null)return{};const style=(()=>{for(const[k,v]of Object.entries(attrs)){if(k.toLowerCase()==="style")return v}return undefined})();if(style==null||style==="")return{};const block={};const alignMatch=style.match(/(?:^|;)\s*text-align\s*:\s*([^;]+)/i);const alignRaw=alignMatch?.[1]?.trim().toLowerCase();if(alignRaw==="start"||alignRaw==="center"||alignRaw==="end"||alignRaw==="justify")block[html_to_codelet_edit_mapper_AttrKey.TEXT_ALIGN]=alignRaw;else if(alignRaw==="left")block[html_to_codelet_edit_mapper_AttrKey.TEXT_ALIGN]="start";else if(alignRaw==="right")block[html_to_codelet_edit_mapper_AttrKey.TEXT_ALIGN]="end";const dirMatch=style.match(/(?:^|;)\s*direction\s*:\s*([^;]+)/i);const dirRaw=dirMatch?.[1]?.trim().toLowerCase();if(dirRaw==="ltr"||dirRaw==="rtl")block[html_to_codelet_edit_mapper_AttrKey.DIRECTION]=dirRaw;const transformMatch=style.match(/(?:^|;)\s*text-transform\s*:\s*([^;]+)/i);const transformRaw=transformMatch?.[1]?.trim().toLowerCase();if(transformRaw==="none"||transformRaw==="uppercase"||transformRaw==="lowercase"||transformRaw==="capitalize")block[html_to_codelet_edit_mapper_AttrKey.TEXT_TRANSFORM]=transformRaw;const lineHeightMatch=style.match(/(?:^|;)\s*line-height\s*:\s*([^;]+)/i);const lineHeightRaw=lineHeightMatch?.[1]?.trim().toLowerCase();if(lineHeightRaw!=null){const pct=lineHeightRaw.match(/^([\d.]+)\s*%$/);const unitless=lineHeightRaw.match(/^[\d.]+$/);if(pct!=null){const n=parseFloat(pct[1]);if(Number.isFinite(n)&&n>0)block[html_to_codelet_edit_mapper_AttrKey.LEADING]=`${Math.round(n*10)}`}else if(unitless!=null){const n=parseFloat(lineHeightRaw);if(Number.isFinite(n)&&n>0)block[html_to_codelet_edit_mapper_AttrKey.LEADING]=`${Math.round(n*1e3)}`}}const trackingMatch=style.match(/(?:^|;)\s*letter-spacing\s*:\s*([^;]+)/i);const trackingRaw=trackingMatch?.[1]?.trim().toLowerCase();if(trackingRaw!=null){if(trackingRaw==="normal"||trackingRaw==="0"||trackingRaw==="0px")block[html_to_codelet_edit_mapper_AttrKey.TRACKING]="0";else{const em=trackingRaw.match(/^(-?[\d.]+)\s*em$/);const unitless=trackingRaw.match(/^(-?[\d.]+)$/);const raw=em?.[1]??unitless?.[1];if(raw!=null){const n=parseFloat(raw);if(Number.isFinite(n))block[html_to_codelet_edit_mapper_AttrKey.TRACKING]=`${Math.round(n*1e3)}`}}}const fontSizeMatch=style.match(/(?:^|;)\s*font-size\s*:\s*([^;]+)/i);const fontSizeRaw=fontSizeMatch?.[1]?.trim().toLowerCase();if(fontSizeRaw!=null){const px=fontSizeRaw.match(/^([\d.]+)\s*px$/);const unitless=fontSizeRaw.match(/^([\d.]+)$/);const raw=px?.[1]??unitless?.[1];if(raw!=null){const n=parseFloat(raw);if(Number.isFinite(n)&&n>0)block[html_to_codelet_edit_mapper_AttrKey.FONT_SIZE]=`${Math.round(n)}`}}const fontFamilyMatch=style.match(/(?:^|;)\s*font-family\s*:\s*([^;]+)/i);const fontFamilyRaw=fontFamilyMatch?.[1]?.trim();if(fontFamilyRaw!=null&&fontFamilyRaw!==""){const candidates=splitCssFontList(fontFamilyRaw);const canvaRef=candidates.find((c=>fontFamilyRegex.test(c)));if(canvaRef!=null)block[html_to_codelet_edit_mapper_AttrKey.FONT_FAMILY]=canvaRef}return block}function richtextElementToInlineAttrs(node){const tag=node.tagName;const out={...richtextTagToInlineAttrs(tag)};const attrs=node.attrs;if(attrs==null)return out;const getAttr=name=>{const direct=attrs[name];if(direct!==undefined)return direct;const lower=name.toLowerCase();for(const[k,val]of Object.entries(attrs)){if(k.toLowerCase()===lower)return val}return undefined};if(tag==="FONT"){const colorRaw=getAttr("color");if(colorRaw!=null&&colorRaw!==""){const normalized=normalizeCssColorValue(colorRaw.trim());if(normalized!=null)out[html_to_codelet_edit_mapper_AttrKey.COLOR]=normalized}}if(tag==="A"){const href=getAttr("href");if(href!=null&&href!=="")out[html_to_codelet_edit_mapper_AttrKey.LINK]=href.trim()}const style=getAttr("style");if(style!=null&&style!==""){const colorMatch=style.match(/(?:^|;)\s*color\s*:\s*([^;]+)/i);const colorRaw=colorMatch?.[1]?.trim();if(colorRaw!=null&&colorRaw!==""){const normalized=normalizeCssColorValue(colorRaw);if(normalized!=null)out[html_to_codelet_edit_mapper_AttrKey.COLOR]=normalized}const inlineStyleAttrs=parseInlineFontStyleAttrs(style);Object.assign(out,inlineStyleAttrs)}return out}function parseInlineFontStyleAttrs(style){const out={};const fontWeightMatch=style.match(/(?:^|;)\s*font-weight\s*:\s*([^;]+)/i);const fontWeightRaw=fontWeightMatch?.[1]?.trim().toLowerCase();if(fontWeightRaw!=null){const named=fontWeightNames.find((w=>w===fontWeightRaw));if(named!=null)out[html_to_codelet_edit_mapper_AttrKey.FONT_WEIGHT]=named;else if(/^\d{1,4}$/.test(fontWeightRaw)){const n=parseInt(fontWeightRaw,10);const namedFromNumeric=numericWeightToNamed(n);if(namedFromNumeric!=null)out[html_to_codelet_edit_mapper_AttrKey.FONT_WEIGHT]=namedFromNumeric}}const fontStyleMatch=style.match(/(?:^|;)\s*font-style\s*:\s*([^;]+)/i);const fontStyleRaw=fontStyleMatch?.[1]?.trim().toLowerCase();if(fontStyleRaw==="italic"||fontStyleRaw==="oblique")out[html_to_codelet_edit_mapper_AttrKey.FONT_STYLE]="italic";else if(fontStyleRaw==="normal")out[html_to_codelet_edit_mapper_AttrKey.FONT_STYLE]="normal";const decoMatch=style.match(/(?:^|;)\s*text-decoration(?:-line)?\s*:\s*([^;]+)/i);const decoRaw=decoMatch?.[1]?.trim().toLowerCase();if(decoRaw!=null){if(decoRaw.includes("underline"))out[html_to_codelet_edit_mapper_AttrKey.DECORATION]="underline";if(decoRaw.includes("line-through"))out[html_to_codelet_edit_mapper_AttrKey.STRIKETHROUGH]="strikethrough"}return out}function numericWeightToNamed(n){if(!Number.isFinite(n)||n<1)return undefined;if(n<150)return"thin";if(n<250)return"extralight";if(n<350)return"light";if(n<450)return"normal";if(n<550)return"medium";if(n<650)return"semibold";if(n<750)return"bold";if(n<850)return"ultrabold";return"heavy"}function decodeHtmlCharacterReferences(text){return text.replace(/&(?:#(x[0-9a-fA-F]+|[0-9]+)|([a-zA-Z][a-zA-Z0-9]*));/g,((full,numeric,named)=>{if(numeric!==undefined){const code=numeric.startsWith("x")||numeric.startsWith("X")?parseInt(numeric.slice(1),16):parseInt(numeric,10);if(!Number.isFinite(code)||code<0)return full;try{return String.fromCodePoint(code)}catch{return full}}if(named!==undefined){const n=named.toLowerCase();if(n==="amp")return"&";if(n==="lt")return"<";if(n==="gt")return">";if(n==="quot")return'"';if(n==="apos")return"'";if(n==="nbsp")return" "}return full}))}function scanTagCloseBracket(html,start){let i=start+1;let quote=null;while(i")return i+1;i++}return html.length}function scanMarkupToken(html,start){if(start>=html.length||html[start]!=="<")return null;if(html.startsWith("\x3c!--",start)){const endComment=html.indexOf("--\x3e",start+4);return{end:endComment>=0?endComment+3:html.length,tagName:"",isClosing:false,selfClosing:true}}if(html[start+1]==="!")return{end:scanTagCloseBracket(html,start),tagName:"",isClosing:false,selfClosing:true};if(html[start+1]==="?"){const gt=html.indexOf(">",start);return{end:gt>=0?gt+1:html.length,tagName:"",isClosing:false,selfClosing:true}}let i=start+1;let isClosing=false;if(html[i]==="/"){isClosing=true;i++}while(i$/.test(raw));return{end,tagName,isClosing,selfClosing}}function parseProtoHtmlToFakeBody(html){const body={kind:"element",tagName:"BODY",children:[]};const stack=[body];let i=0;const appendTextToOpenElement=raw=>{if(raw==="")return;const decoded=decodeHtmlCharacterReferences(raw);if(decoded==="")return;const parent=stack[stack.length-1];Preconditions.checkState(parent.kind==="element");parent.children.push({kind:"text",text:decoded})};while(ii)appendTextToOpenElement(html.slice(i,lt));const tok=scanMarkupToken(html,lt);if(tok==null){appendTextToOpenElement(html.slice(lt,lt+1));i=lt+1;continue}if(tok.tagName===""){i=tok.end;continue}i=tok.end;if(tok.isClosing){while(stack.length>1){const top=stack[stack.length-1];if(top.kind==="element"&&top.tagName===tok.tagName){stack.pop();break}stack.pop()}continue}if(tok.selfClosing){if(tok.tagName==="BR")appendTextToOpenElement(html_to_codelet_edit_mapper_RICHTEXT_SOFT_BREAK);else if(tok.tagName==="P")appendTextToOpenElement("\n");continue}const rawTag=html.slice(lt,tok.end);const parsedAttrs=parseHtmlOpeningTagAttributes(rawTag);const el={kind:"element",tagName:tok.tagName,children:[],...Object.keys(parsedAttrs).length>0?{attrs:parsedAttrs}:{}};const parent=stack[stack.length-1];Preconditions.checkState(parent.kind==="element");parent.children.push(el);stack.push(el)}return body}function richtextListMarkerForListElement(node){const styleAttr=node.attrs==null?undefined:Object.entries(node.attrs).find((([k])=>k.toLowerCase()==="style"))?.[1];const styleMatch=styleAttr?.match(/(?:^|;)\s*list-style-type\s*:\s*([^;]+)/i);const raw=styleMatch?.[1]?.trim().toLowerCase();if(raw!=null)for(const candidate of listMarkers){if(candidate===raw)return candidate}return node.tagName==="OL"?"decimal":"disc"}function richtextIsBlockContainerTag(tagName){return richtextTagToSemantics(tagName)!=null||tagName==="P"||tagName==="DIV"}function richtextChildIsBlockContainer(child){return child.kind==="element"&&richtextIsBlockContainerTag(child.tagName)}function richtextFlattenStyleOnlySpans(children){return children.flatMap((child=>{if(child.kind==="element"&&child.tagName==="SPAN"&&child.children.length>0&&child.children.every((c=>c.kind==="text")))return child.children;return[child]}))}function richtextCollectTextOnlyBlockContent(node,inherited,merged,out,outerBlockAttrs){const blockChildren=node.children.filter(richtextChildIsBlockContainer);if(blockChildren.length>0)return false;const inlineChildren=richtextFlattenStyleOnlySpans(node.children);if(inlineChildren.length===0||!inlineChildren.every((c=>c.kind==="text")))return false;const combined=inlineChildren.map((c=>c.kind==="text"?c.text:"")).join("");const trimmed=combined.trim();if(trimmed.length===0){out.push({attrs:{...inherited,...outerBlockAttrs},text:"\n"});return true}if(trimmed===combined)return false;out.push({attrs:{...merged},text:trimmed});out.push({attrs:{...inherited,...outerBlockAttrs},text:"\n"});return true}function richtextCollectSegmentsFromFakeTree(node,inherited,out,listCtx){if(node.kind==="text"){if(node.text.length>0)out.push({attrs:{...inherited},text:node.text});return}const tag=node.tagName;if(tag==="BR"){out.push({attrs:{...inherited},text:html_to_codelet_edit_mapper_RICHTEXT_SOFT_BREAK});return}const merged=mergeAttrs(inherited,richtextElementToInlineAttrs(node));if(tag==="UL"||tag==="OL"){const nextCtx={marker:richtextListMarkerForListElement(node),level:(listCtx?.level??0)+1};for(const child of node.children)richtextCollectSegmentsFromFakeTree(child,inherited,out,nextCtx);return}if(tag==="LI"){const block=richtextElementToBlockAttrs(node);const listBlock=listCtx!=null?{[html_to_codelet_edit_mapper_AttrKey.LIST_MARKER]:listCtx.marker,[html_to_codelet_edit_mapper_AttrKey.LIST_LEVEL]:String(listCtx.level)}:{};const liAttrs={...inherited,...block,...listBlock};let liBreakPushed=false;for(const child of node.children){const isNestedList=child.kind==="element"&&(child.tagName==="UL"||child.tagName==="OL");if(isNestedList&&!liBreakPushed){out.push({attrs:liAttrs,text:"\n"});liBreakPushed=true}richtextCollectSegmentsFromFakeTree(child,merged,out,listCtx)}if(!liBreakPushed)out.push({attrs:liAttrs,text:"\n"});return}const semantics=richtextTagToSemantics(tag);if(richtextIsBlockContainerTag(tag)){const block=richtextElementToBlockAttrs(node);const semanticsAttr=semantics!=null?{[html_to_codelet_edit_mapper_AttrKey.SEMANTICS]:semantics}:{};const outerBlockAttrs={...block,...semanticsAttr};const blockChildren=node.children.filter(richtextChildIsBlockContainer);if(richtextCollectTextOnlyBlockContent(node,inherited,merged,out,outerBlockAttrs))return;if(blockChildren.length===node.children.length&&node.children.length>0){const inheritedForBlocks=mergeAttrs(merged,outerBlockAttrs);if(blockChildren.length===1){richtextCollectSegmentsFromFakeTree(blockChildren[0],inheritedForBlocks,out,listCtx);return}for(const child of node.children)richtextCollectSegmentsFromFakeTree(child,inheritedForBlocks,out,listCtx);return}for(const child of node.children)richtextCollectSegmentsFromFakeTree(child,merged,out,listCtx);out.push({attrs:{...inherited,...outerBlockAttrs},text:"\n"});return}if(tag==="BODY"||tag==="HTML"||tag==="SECTION"||tag==="ARTICLE"){for(const child of node.children)richtextCollectSegmentsFromFakeTree(child,inherited,out,listCtx);return}if(tag==="SPAN"){for(const child of node.children)richtextCollectSegmentsFromFakeTree(child,merged,out,listCtx);return}for(const child of node.children)richtextCollectSegmentsFromFakeTree(child,merged,out,listCtx)}function richtextEnsureTrailingParagraphNewline(segments){const joined=segments.map((s=>s.text)).join("");if(joined.length===0||!joined.endsWith("\n"))segments.push({attrs:{},text:"\n"})}function wrapWithComputedStyles(element){const tag=blockWrapperTagFor(element);const style=inlineStylesFromComputed(getComputedStyle(element));const safeStyle=style.replace(/"/g,"'");const inner=normalizeInnerHtmlForRichtext(element,unwrapRedundantInnerBlock(element.innerHTML,tag));return`<${tag} style="${safeStyle}">${inner}`}function normalizeInnerHtmlForRichtext(element,innerHTML){const inner=unwrapRedundantStyleSpan(innerHTML);if(element.childElementCount===0&&!/<[a-z]/i.test(inner))return inner.trim();return inner}function unwrapRedundantStyleSpan(innerHTML){const trimmed=innerHTML.trim();if(trimmed==="")return innerHTML;const match=trimmed.match(/^]*)?>([\s\S]*)<\/span>$/i);if(match==null)return innerHTML;const attrs=match[1]??"";if(!/\bstyle\s*=/.test(attrs))return innerHTML;return match[2]??innerHTML}function unwrapRedundantInnerBlock(innerHTML,tag){const trimmed=innerHTML.trim();if(trimmed==="")return innerHTML;const pattern=new RegExp(`^<${tag}(\\s[^>]*)?>([\\s\\S]*)<\\/${tag}>$`,"i");const match=trimmed.match(pattern);return match?.[2]??innerHTML}function blockWrapperTagFor(element){switch(element.tagName.toUpperCase()){case"P":case"H1":case"H2":case"H3":case"H4":case"H5":case"H6":case"BLOCKQUOTE":case"DIV":return element.tagName.toLowerCase();default:return"p"}}function inlineStylesFromComputed(s){return[`font-family: ${s.fontFamily}`,`font-size: ${s.fontSize}`,`font-weight: ${s.fontWeight}`,`font-style: ${s.fontStyle}`,`color: ${s.color}`,`text-align: ${s.textAlign}`,`text-transform: ${s.textTransform}`,`direction: ${s.direction}`,`line-height: ${s.lineHeight}`,`letter-spacing: ${s.letterSpacing}`,`text-decoration: ${s.textDecorationLine||s.textDecoration}`].join("; ")}function htmlStringToRichtext2(htmlOrElement){const html=typeof htmlOrElement==="string"?htmlOrElement:htmlOrElement.innerHTML.trim()===""?"":wrapWithComputedStyles(htmlOrElement);if(html.trim()==="")return undefined;const segments=collectSegments(html.trim());return buildRichtext2Proto(segments)}function collectSegments(html){const body=parseProtoHtmlToFakeBody(html);const segments=[];richtextCollectSegmentsFromFakeTree(body,{},segments);richtextEnsureTrailingParagraphNewline(segments);return segments}function buildRichtext2Proto(segments){const characters=[];const attributes=[];let prevAttrs={};for(const seg of segments){if(seg.text.length===0)continue;const delta=diffAttrsToProto(prevAttrs,seg.attrs);if(delta.size>0)attributes.push(new ChangeAttributeStreamItemProto({attributes:delta}));characters.push(new CharacterRegionProto({characters:seg.text}));attributes.push(new RetainAttributeStreamItemProto({length:seg.text.length}));prevAttrs=seg.attrs}return new Richtext2Proto({doNotUseCharacters:characters,doNotUseAttributes:attributes})}function diffAttrsToProto(prev,curr){const out=new Map;for(const[k,v]of Object.entries(curr))if(prev[k]!==v)out.set(k,{r:v});for(const k of Object.keys(prev))if(!(k in curr))out.set(k,{r:undefined});return out}const BLOCK_TAGS=new Set(["ADDRESS","BLOCKQUOTE","BODY","CENTER","DD","DIR","DIV","DL","DT","FIELDSET","FORM","H1","H2","H3","H4","H5","H6","HR","HTML","ISINDEX","LI","MENU","NOFRAMES","NOSCRIPT","OL","P","PRE","TABLE","TBODY","TD","TFOOT","TH","THEAD","TR","UL"]);const ALLOWED_INLINE_TAGS=new Set(["A","B","BR","DEL","EM","FONT","I","S","SPAN","STRONG","U"]);const TEXT_BLOCK_TAGS=new Set(["P","H1","H2","H3","H4","H5","H6","BLOCKQUOTE","LI"]);const NON_TEXT_ELEMENT_TAGS=new Set(["AUDIO","CANVAS","EMBED","IFRAME","IMG","INPUT","OBJECT","SELECT","SVG","TEXTAREA","VIDEO"]);function isRichtextEditableContainer(element){if(element===document.body||element===document.documentElement)return false;if(NON_TEXT_ELEMENT_TAGS.has(element.tagName.toUpperCase()))return false;if(!elementHasVisibleText(element))return false;if(countMeaningfulDirectTextNodes(element)>1)return false;if(hasMixedDirectTextAndElementChildren(element)&&!TEXT_BLOCK_TAGS.has(element.tagName.toUpperCase()))return false;if(hasDirectBlockChild(element))return false;if(!areDirectElementChildrenAllowed(element))return false;if(countDirectTextBearingElementChildren(element)>1)return false;return true}function elementHasVisibleText(element){const inner=element.innerText;if(inner!=null&&inner.trim().length>0)return true;return(element.textContent??"").trim().length>0}function countMeaningfulDirectTextNodes(element){let count=0;for(const node of element.childNodes)if(node.nodeType===Node.TEXT_NODE&&(node.textContent??"").trim().length>0)count++;return count}function hasMixedDirectTextAndElementChildren(element){return countMeaningfulDirectTextNodes(element)>0&&element.children.length>0}function hasDirectBlockChild(element){for(const child of element.children){if(BLOCK_TAGS.has(child.tagName.toUpperCase()))return true}return false}function areDirectElementChildrenAllowed(element){for(const child of element.children){if(!(child instanceof HTMLElement))return false;if(!ALLOWED_INLINE_TAGS.has(child.tagName.toUpperCase()))return false;if(hasBlockGrandchild(child))return false}return true}function hasBlockGrandchild(element){for(const grandchild of element.children){if(BLOCK_TAGS.has(grandchild.tagName.toUpperCase()))return true}return false}function countDirectTextBearingElementChildren(element){let count=0;for(const child of element.children){if(!(child instanceof HTMLElement))continue;if(elementHasVisibleText(child))count++}return count}function backgroundColor({backgroundColor,backgroundImage}){if(backgroundImage.startsWith("linear-gradient")||backgroundImage.startsWith("radial-gradient"))return new BackgroundColorEditableAttribute({current:new BackgroundColorEdit({color:backgroundImage})});const match=backgroundColor.match(/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([\d.]+))?\s*\)$/);if(!match)return undefined;const[,r,g,b,a]=match;const toHex=n=>n.toString(16).padStart(2,"0");const alpha=a!=null?Math.round(parseFloat(a)*255):255;const hex=`#${toHex(Number(r))}${toHex(Number(g))}${toHex(Number(b))}${toHex(alpha)}`;if(hex==="#00000000")return undefined;return new BackgroundColorEditableAttribute({current:new BackgroundColorEdit({color:hex})})}function*transforms(element,{display,position,translate,rotate,scale},enableFreeformTransition){if(element===document.body)return undefined;if(enableFreeformTransition?display==="inline"||display==="contents":position!=="absolute")return undefined;const bounds=element.getBoundingClientRect();const parentMatrices=element.parentElement?getElementMatrices(element.parentElement):[];const parentRotation=getElementRotation(parentMatrices);const parentScale=getElementScale(parentMatrices);const translation=parseTranslate(translate);const matrix=(new DOMMatrix).translate(bounds.left,bounds.top).rotate(parentRotation).scale(parentScale);yield new TranslationEditableAttribute({matrix:matrix.translate(-translation.translateX,-translation.translateY).inverse(),current:translation});yield new RotationEditableAttribute({matrix:matrix.inverse(),current:parseRotate(rotate)});yield new ScaleEditableAttribute({matrix:matrix.inverse(),current:parseScale(scale)})}function parseTranslate(translate){if(!translate||translate==="none")return new TranslationEdit({translateX:0,translateY:0});const parts=translate.split(" ");const tx=parseFloat(parts[0]??"0");const ty=parseFloat(parts[1]??"0");return new TranslationEdit({translateX:tx,translateY:ty})}function parseRotate(rotate){if(!rotate||rotate==="none")return new RotationEdit({rotation:0});const parts=rotate.trim().split(/\s+/);const is2DRotation=rotate!=="none"&&parts.length===1;const matrix=new DOMMatrix(is2DRotation?`rotate(${rotate})`:"");const rotation=Math.atan2(matrix.b,matrix.a)*(180/Math.PI);return new RotationEdit({rotation})}function parseScale(scale){if(!scale||scale==="none")return new ScaleEdit({scale:1});return new ScaleEdit({scale:parseFloat(scale)})}function mediaReplaceable(element){if(!(element instanceof HTMLImageElement))return undefined;return new MediaReplaceEditableAttribute}function richtext(element){if(!isRichtextEditableContainer(element))return undefined;const parsed=htmlStringToRichtext2(element);if(parsed==null)return undefined;return new RichtextEditableAttribute({current:new RichtextEdit({html:parsed})})}function reorder(element,styles){if(element.parentElement==null)return;const parentStyles=getComputedStyle(element.parentElement);if(parentStyles.display!=="flex")return;const order=Math.trunc(parseFloat(styles.order));const ordering=[...element.parentElement.children].reduce(((acc,child,index)=>{const id=uniqueIdentifier(child);if(!id)return acc;return acc.set(id,child===element?order:Math.trunc(parseFloat(getComputedStyle(child).order)))}),new Map);if(ordering.size!==element.parentElement.children.length)return;let direction;switch(parentStyles.flexDirection){case"column":direction=FlexDirection.COLUMN;break;case"column-reverse":direction=FlexDirection.COLUMN_REVERSE;break;case"row":direction=FlexDirection.ROW;break;case"row-reverse":direction=FlexDirection.ROW_REVERSE;break;default:throw new Error("Unrecognized flexDirection")}return new ReorderEditableAttribute({direction,order,ordering})}function editableAttributesForElement(element,flags={enableFreeformTransition:true}){const styles=getComputedStyle(element);return[backgroundColor(styles),...transforms(element,styles,flags.enableFreeformTransition),mediaReplaceable(element),richtext(element),reorder(element,styles)].filter(exists)}class LayoutShiftObserver{initResizeObserver(){if(this.resizeObserver!=null)return;if(globalThis.ResizeObserver!=null){this.resizeObserver=new globalThis.ResizeObserver((entries=>{if(entries.length===0||this.observedElements.length===0)return;this.observedElements.forEach((onLayoutShift=>onLayoutShift()))}));this.resizeObserver.observe(document.documentElement,{box:"border-box"})}}dispose(){this.resizeObserver?.disconnect();this.resizeObserver=undefined}observeElement(element,onLayoutShift){this.observedElements.push(onLayoutShift);this.initResizeObserver();this.resizeObserver?.observe(element,{box:"border-box"});return()=>{this.resizeObserver?.unobserve(element);this.observedElements=this.observedElements.filter((c=>c!==onLayoutShift));if(this.observedElements.length===0)this.dispose()}}constructor(){this.observedElements=[]}}class Backgrounds{set backgroundColor(value){if(value==null)this._backgroundColor=undefined;else if(value==="transparent"&&this.element.tagName.toLowerCase()==="body")this._backgroundColor=undefined;else if(value.startsWith("linear-gradient")||value.startsWith("radial-gradient"))this._backgroundColor=value;else this._backgroundColor=`linear-gradient(${value}, ${value})`;this.syncBackgroundAttributes()}set backgroundImage(value){this._backgroundImage=value;this.syncBackgroundAttributes()}get backgroundImageSrc(){return this._backgroundImage?.url}set image(value){this._image=value;this.syncBackgroundAttributes()}get imageSrc(){return this._image}set textColor(value){if(value==null)this._textColor=undefined;else if(value.startsWith("linear-gradient")||value.startsWith("radial-gradient"))this._textColor=value;else this._textColor=`linear-gradient(${value}, ${value})`;this.syncBackgroundAttributes()}syncBackgroundAttributes(){const backgroundImage=[this._textColor,this._image?`url(${this._image})`:undefined,this._backgroundImage?`url(${this._backgroundImage.url})`:undefined,this._backgroundColor].filter(exists);const backgroundClip=[this._textColor?"text":undefined,this._image?"border-box":undefined,this._backgroundImage?"border-box":undefined,this._backgroundColor?"border-box":undefined].filter(exists);this.element.style.setProperty("background-image",backgroundImage.join(", "),"important");this.element.style.setProperty("background-clip",backgroundClip.join(", "),"important");if(this.element.tagName.toLowerCase()==="body"){this.disposeCoverPageBackground?.();if(this._backgroundImage)this.disposeCoverPageBackground=coverPageBackground(Preconditions.checkExists(this._backgroundImage.dimensions,"Dimensions were not provided for background image"));else{this.element.style.backgroundPosition="";this.element.style.setProperty("background-size","100vw 100vh","important")}}else if(this._backgroundImage!=null||this._image!=null){this.element.style.setProperty("background-position","center","important");this.element.style.setProperty("background-size","cover","important")}}constructor(element){this.element=element}}function coverPageBackground(dimensions){const onResize=()=>{const windowAspectRatio=window.innerWidth/window.innerHeight;const imageAspectRatio=dimensions.width/dimensions.height;const windowWiderThanImage=windowAspectRatio>imageAspectRatio;if(windowWiderThanImage){const vw=`${100/imageAspectRatio}vw`;document.body.style.setProperty("background-size",`100vw ${vw}`,"important");document.body.style.setProperty("background-position-y",`calc((100vh - ${vw}) / 2)`,"important");document.body.style.backgroundPositionX=""}else{const vh=`${100*imageAspectRatio}vh`;document.body.style.setProperty("background-size",`${vh} 100vh`,"important");document.body.style.setProperty("background-position-x",`calc((100vw - ${vh}) / 2)`,"important");document.body.style.backgroundPositionY=""}};onResize();window.addEventListener("resize",onResize);return()=>{window.removeEventListener("resize",onResize);document.body.style.backgroundSize=""}}const backgrounds=new WeakMap;const fillResizeObservers=new WeakMap;const TITLE_FONT_SIZE=2.5;const FONT_SIZE_ATTRIBUTE="data-canva-font-size";const elementUpdater={textContent:(e,v,f)=>{if(e instanceof HTMLInputElement)e.placeholder=v;else if(TextEditor.canCreateTextEditor(e)){e.style.setProperty("white-space","pre-wrap","important");e.style.setProperty("overflow-wrap",f?.enableClampingToPreventWordBreaks?"normal":"anywhere","important");if(!f?.enableCodelet2LineHeight)e.style.setProperty("line-height","normal","important");e.textContent=v;if(e.textContent==="")e.innerHTML="
    ";else e.innerHTML=e.innerHTML.replaceAll(/(\p{Extended_Pictographic}+)/gu,'$1')}},fill:(element,fullConfig)=>{fillResizeObservers.get(element)?.disconnect();fillResizeObservers.delete(element);const background=getBackgrounds(element);const imageCandidates=getImageCandidates(fullConfig.imageSrc,fullConfig.imageSrcs);const backgroundCandidates=getBackgroundCandidates(fullConfig.background,fullConfig.backgroundImageSrcs);const apply=()=>element instanceof HTMLImageElement?applyFillToImageElement(element,fullConfig,background,imageCandidates,backgroundCandidates):applyFillToOtherElement(element,fullConfig,background,imageCandidates,backgroundCandidates);if(imageCandidates.length>1||backgroundCandidates.length>1){const resizeObserver=new ResizeObserver((()=>{if(!element.isConnected){fillResizeObservers.get(element)?.disconnect();fillResizeObservers.delete(element);return}apply()}));resizeObserver.observe(element);fillResizeObservers.set(element,resizeObserver)}return apply()},color:(e,v)=>{const valueSupportedByColorAttr=CSS.supports("color",v);const elmentDoesNotSupportGradientText=e instanceof HTMLInputElement||e instanceof HTMLSelectElement;const[fallbackColor]=v.match(/#([0-9a-fA-F]{6})/)??["#000000ff"];const background=backgrounds.get(e)??backgrounds.set(e,new Backgrounds(e)).get(e);if(valueSupportedByColorAttr||elmentDoesNotSupportGradientText){const color=valueSupportedByColorAttr?v:fallbackColor;e.style.setProperty("color",color,"important");e.style.setProperty("--canva-color",color);e.style.setProperty("caret-color",color,"important");background.textColor=undefined;return}background.textColor=v;e.style.setProperty("--canva-color",fallbackColor);e.style.setProperty("caret-color",fallbackColor,"important");e.style.setProperty("color","transparent","important")},font:(e,v,f)=>{const{id,cssFontFamily,src,weight,style,variants}=v;const blockingPromises=[];if(id!=null&&variants!=null&&variants.length>0)for(const variant of variants){const promise=loadFontFace(id,variant);if(variant.loadMode===LoadMode.BLOCKING)blockingPromises.push(promise)}else if(id!=null&&src!=null&&weight!=null&&style!=null)blockingPromises.push(loadFontFace(id,{src,weight,style}));if(cssFontFamily!=null)e.style.setProperty("font-family",cssFontFamily,"important");if(weight!=null)e.style.setProperty("font-weight",weight,"important");if(style!=null)e.style.setProperty("font-style",style,"important");return blockingPromises.length>0?Promise.all(blockingPromises):undefined},fontSize(e,v,f){const rem=v/16;e.setAttribute(FONT_SIZE_ATTRIBUTE,`${rem}rem`);e.style.setProperty("font-size",`${rem}rem`,"important")},letterSpacing:(e,v)=>{e.style.setProperty("letter-spacing",`${v}rem`,"important")},lineHeight:(e,v,f)=>{if(!f?.enableCodelet2LineHeight)return;e.style.setProperty("line-height",String(v),"important")}};function clampFontSize(e){if(e instanceof HTMLInputElement)return;const fontSize=e.getAttribute(FONT_SIZE_ATTRIBUTE);if(!fontSize?.endsWith("rem"))return;const rem=parseFloat(fontSize);if(remavailableWidth){const scaled=rem*availableWidth/textWidth;const floored=Math.floor(scaled*100)/100;e.style.setProperty("font-size",`${floored}rem`,"important")}}function applyFillToImageElement(element,fullConfig,background,imageCandidates,backgroundCandidates){const resourcePromises=[];element.alt=fullConfig.altText??"";background.image=undefined;if(fullConfig.imageSrc==null)element.removeAttribute("src");const currentImageSrc=element.getAttribute("src")!=null?element.src:undefined;if(imageCandidates.length>0){const nextSrc=selectBestImageCandidateSrc(imageCandidates,getRequiredWidthPx(element,undefined),currentImageSrc);if(nextSrc!==currentImageSrc){const loadPromise=whenLoaded(element);element.src=nextSrc;resourcePromises.push(loadPromise)}}if(backgroundCandidates.length>0){const currentBackgroundSrc=background.backgroundImageSrc;const nextBackgroundSrc=selectBestImageCandidateSrc(backgroundCandidates,getRequiredWidthPx(element,fullConfig.backgroundDimensions),currentBackgroundSrc);if(nextBackgroundSrc!==currentBackgroundSrc){const img=new Image;const loadPromise=whenLoaded(img);img.src=nextBackgroundSrc;resourcePromises.push(loadPromise)}background.backgroundColor=undefined;background.backgroundImage={url:nextBackgroundSrc,dimensions:fullConfig.backgroundDimensions};background.image=undefined;return Promise.all(resourcePromises).then((()=>undefined))}background.backgroundColor=fullConfig.background;background.backgroundImage=undefined;background.image=undefined;return Promise.all(resourcePromises).then((()=>undefined))}function applyFillToOtherElement(element,fullConfig,background,imageCandidates,backgroundCandidates){if(imageCandidates.length>0){const currentImageSrc=background.imageSrc;const nextImageSrc=selectBestImageCandidateSrc(imageCandidates,getRequiredWidthPx(element,undefined),currentImageSrc);background.backgroundColor=undefined;background.backgroundImage=undefined;background.image=nextImageSrc;if(nextImageSrc===currentImageSrc)return undefined;const img=new Image;const loadPromise=whenLoaded(img);img.src=nextImageSrc;return loadPromise}if(backgroundCandidates.length>0){const currentBackgroundSrc=background.backgroundImageSrc;const nextBackgroundSrc=selectBestImageCandidateSrc(backgroundCandidates,getRequiredWidthPx(element,fullConfig.backgroundDimensions),currentBackgroundSrc);let resourcePromise;if(nextBackgroundSrc!==currentBackgroundSrc){const img=new Image;resourcePromise=whenLoaded(img);img.src=nextBackgroundSrc}background.backgroundColor=undefined;background.backgroundImage={url:nextBackgroundSrc,dimensions:fullConfig.backgroundDimensions};background.image=undefined;return resourcePromise}background.backgroundColor=fullConfig.background;background.backgroundImage=undefined;background.image=undefined;return undefined}function getBackgrounds(element){const existing=backgrounds.get(element);if(existing!=null)return existing;const background=new Backgrounds(element);backgrounds.set(element,background);return background}function getImageCandidates(fallbackSrc,imageSrcs){const responsiveCandidates=[...imageSrcs??[]].sort(((a,b)=>a.width-b.width)).map((({src,width})=>({src,width})));if(responsiveCandidates.length>0)return responsiveCandidates;return fallbackSrc!=null?[{src:fallbackSrc,width:undefined}]:[]}function getBackgroundCandidates(background,backgroundImageSrcs){if(background==null||!isImageBackground(background))return[];return getImageCandidates(unwrapCssUrl(background),backgroundImageSrcs)}function selectBestImageCandidateSrc(candidates,targetWidthPx,currentSrc){if(candidates.length===1)return candidates[0].src;const currentCandidate=candidates.find((candidate=>candidate.src===currentSrc));if(currentCandidate?.width!=null&¤tCandidate.width>=targetWidthPx)return currentCandidate.src;return candidates.find((candidate=>candidate.width!=null&&candidate.width>=targetWidthPx))?.src??candidates[candidates.length-1].src}function getRequiredWidthPx(element,backgroundDimensions){const dpr=window.devicePixelRatio||1;const rect=element.tagName.toLowerCase()==="body"?{width:window.innerWidth,height:window.innerHeight}:element.getBoundingClientRect();if(backgroundDimensions!=null&&rect.width>0&&rect.height>0){const widthScale=rect.width/backgroundDimensions.width;const heightScale=rect.height/backgroundDimensions.height;return Math.ceil(backgroundDimensions.width*Math.max(widthScale,heightScale)*dpr)}return Math.ceil(Math.max(rect.width,rect.height,element.clientWidth,element.clientHeight)*dpr)}function isImageBackground(value){return value.startsWith("url(")&&value.endsWith(")")}function unwrapCssUrl(value){return value.substring(4,value.length-1)}function whenLoaded(element){return new Promise(((resolve,reject)=>{const onLoad=()=>{resolve();element.removeEventListener("load",onLoad);element.removeEventListener("error",onError)};const onError=event=>{const error=event.error instanceof Error?event.error:new Error(event.message);reject(error);element.removeEventListener("load",onLoad);element.removeEventListener("error",onError)};element.addEventListener("load",onLoad);element.addEventListener("error",onError)}))}function loadFontFace(fontFamily,{src,weight,style}){const existingFontFace=Array.from(document.fonts.values()).find((existing=>existing.family===fontFamily&&existing.style===style&&existing.weight===weight));if(existingFontFace==null){const fontFace=new FontFace(fontFamily,`url(${src})`,{weight,style});document.fonts.add(fontFace);return fontFace.load()}return existingFontFace.load()}const TEXT_EDITING_STYLES_ID="canvaTextEditingStyles";const TEXT_UPDATED_EVENT_NAME="textUpdated";const Z_INDEX_MAX=2147483647;class TextEditor extends HTMLElement{get targetElement(){return Preconditions.checkExists(this._targetElement)}get targetText(){if(this.targetElement instanceof HTMLInputElement)return this.targetElement.placeholder;return this.targetElement.textContent}get contentEditableElement(){return Preconditions.checkExists(this._contentEditableElement)}get persistChanges(){return Preconditions.checkExists(this._persistChanges)}get onFinishTextEditing(){return Preconditions.checkExists(this._onFinishTextEditing)}static canCreateTextEditor(element){if(customElements.get("canva-text-editor")==null)return false;if(!(element instanceof HTMLElement))return false;if(element instanceof HTMLInputElement)return true;const children=[...element.childNodes];if(children.length===1&&children[0].nodeName.toLowerCase()==="br")return true;return children.every((e=>TextEditor.isPlainText(e)))}static isPlainText(e){if(e.nodeType===Node.TEXT_NODE)return true;if(e.childNodes.length!==1)return false;if(e.nodeName.toLowerCase()!=="canva-span")return false;return TextEditor.isPlainText(e.childNodes[0])}static createTextEditor(element,entityId,editingSdk,onFinishTextEditing,sendTextFocusChanged,persistChanges){const textEditor=document.createElement("canva-text-editor");Preconditions.checkState(textEditor instanceof TextEditor,"The element is not a TextEditor");textEditor._targetElement=element;textEditor._entityId=entityId;textEditor._editingSdk=editingSdk;textEditor._persistChanges=persistChanges;textEditor._onFinishTextEditing=onFinishTextEditing;textEditor._sendTextFocusChanged=sendTextFocusChanged;textEditor.attachShadow({mode:"open"});textEditor.addEventListener("textUpdated",persistChanges);return textEditor}static getEditorIfActive(element){const editor=document.querySelector("canva-text-editor");return editor?.targetElement===element?editor:undefined}focusTextEditor(){if(this.contentEditableElement.textContent.length>0){this.focus();return}this.focusTextRange()}focusTextRange(){this.contentEditableElement.focus();const range=document.createRange();range.selectNodeContents(this.contentEditableElement);const selection=window.getSelection();selection?.removeAllRanges();selection?.addRange(range)}async finishEditing(){this.removeEventListener("textUpdated",this.persistChanges);this.onTextContentChange();this.onFinishTextEditing()}syncConfig(){const contentEditableElement=this.contentEditableElement;const styles=this.getComputedStyle(this.targetElement);const targetStyles=this.targetElement.style;const getStyle=extract=>{const style=extract(targetStyles);return style?style:extract(styles)};contentEditableElement.style.color="transparent";contentEditableElement.style.caretColor=getStyle((d=>d.caretColor));contentEditableElement.style.fontFamily=getStyle((d=>d.fontFamily));contentEditableElement.style.fontSize=getStyle((d=>d.fontSize));contentEditableElement.style.fontWeight=getStyle((d=>d.fontWeight));contentEditableElement.style.fontStyle=getStyle((d=>d.fontStyle));contentEditableElement.style.textAlign=getStyle((d=>d.textAlign));contentEditableElement.style.lineHeight=getStyle((d=>d.lineHeight));contentEditableElement.style.letterSpacing=getStyle((d=>d.letterSpacing));contentEditableElement.style.textTransform=getStyle((d=>d.textTransform));this._disposeLayoutObserver?.();this._disposeLayoutObserver=this.syncLayoutWithTargetElement()}connectedCallback(){const shadowRoot=Preconditions.checkExists(this.shadowRoot);this.style.position="absolute";this.style.inset="0";this.style.zIndex=Z_INDEX_MAX.toString();const contentEditableElement=document.createElement("canva-text-editor-editable");contentEditableElement.contentEditable="plaintext-only";contentEditableElement.style.outline="none";contentEditableElement.style.cursor="text";contentEditableElement.style.whiteSpace="pre-wrap";contentEditableElement.style.display="block";const textContent=this.targetText===""?document.createElement("br"):document.createTextNode(this.targetText);contentEditableElement.appendChild(textContent);this._contentEditableElement=contentEditableElement;this.syncConfig();if(this.targetElement instanceof HTMLInputElement)this.targetElement.value="";this.addEventListener("click",this.onUnderlayClick);this.addEventListener("input",this.onTextContentChange);this.addEventListener("keydown",this.stopKeyEventPropagating);this.addEventListener("keypress",this.stopKeyEventPropagating);this.addEventListener("keyup",this.stopKeyEventPropagating);contentEditableElement.addEventListener("click",this.onEditorClicked);contentEditableElement.addEventListener("focus",this.onTextEditingFocused);contentEditableElement.addEventListener("blur",this.onTextEditingBlurred);this.wrapper=document.createElement("div");this.wrapper.style.position="absolute";this.wrapper.append(contentEditableElement);shadowRoot.appendChild(this.wrapper);this._disposeLayoutObserver=this.syncLayoutWithTargetElement()}getComputedStyle(target){if(target instanceof HTMLElement)return window.getComputedStyle(target,"::placeholder");return window.getComputedStyle(target)}disconnectedCallback(){this.wrapper=undefined;this._disposeLayoutObserver?.();document.getElementById(TEXT_EDITING_STYLES_ID)?.remove();this.removeEventListener("click",this.onUnderlayClick);this.removeEventListener("input",this.onTextContentChange);this.removeEventListener("keydown",this.stopKeyEventPropagating);this.removeEventListener("keypress",this.stopKeyEventPropagating);this.removeEventListener("keyup",this.stopKeyEventPropagating);this._contentEditableElement?.removeEventListener("click",this.onEditorClicked);this._contentEditableElement?.removeEventListener("focus",this.onTextEditingFocused);this._contentEditableElement?.removeEventListener("blur",this.onTextEditingBlurred)}syncLayoutWithTargetElement(){if(this.wrapper==null)return;const position=this.updateEditorPosition();if(position==null)return;this.wrapper.style.transform="";const{top:offsetTop,left:offsetLeft}=this.getTextNodeRect(this.contentEditableElement);this.wrapper.style.transform=`translate(${position.left-offsetLeft}px, ${position.top-offsetTop}px)`;return(new LayoutShiftObserver).observeElement(this.targetElement,this.updateEditorPosition)}getTextNodeRect(target){const range=document.createRange();if(target instanceof HTMLInputElement){range.selectNode(target);const inputElementRect=range.getBoundingClientRect();const{paddingTop,paddingLeft}=window.getComputedStyle(target);return{width:inputElementRect.width,height:inputElementRect.height,top:inputElementRect.top+parseFloat(paddingTop)+(inputElementRect.height-this.targetElement.clientHeight)/2,left:inputElementRect.left+parseFloat(paddingLeft)+(inputElementRect.width-this.targetElement.clientWidth)/2}}range.selectNodeContents(target);return range.getBoundingClientRect()}constructor(...args){super(...args),this.updateEditorPosition=()=>{if(this.wrapper==null)return;const{top,left,width,height}=this.getTextNodeRect(this.targetElement);this.wrapper.style.top=`${top+window.scrollY}px`;this.wrapper.style.left=`${left+window.scrollX}px`;this.wrapper.style.width=`${Math.max(1,width)}px`;this.wrapper.style.height=`${height}px`;return{top,left}},this.onEditorClicked=e=>{e.stopPropagation()},this.onUnderlayClick=e=>{this.maybeSetTextCaret(e.clientX,e.clientY)},this.maybeSetTextCaret=(clientX,clientY)=>{if(document.caretPositionFromPoint==null)return;const elements=document.elementsFromPoint(clientX,clientY);if(!elements.includes(this.targetElement,1))return;const editorRect=this.contentEditableElement.getBoundingClientRect();const x=Math.min(editorRect.right-1,Math.max(editorRect.left+1,clientX));const y=Math.min(editorRect.bottom-1,Math.max(editorRect.top+1,clientY));const position=document.caretPositionFromPoint(x,y,{shadowRoots:this.shadowRoot!=null?[this.shadowRoot]:undefined});if(position==null)return;const range=document.createRange();range.setStart(position.offsetNode,position.offset);range.collapse(true);const selection=window.getSelection();selection?.removeAllRanges();selection?.addRange(range)},this.stopKeyEventPropagating=e=>{e.stopPropagation()},this.onTextEditingFocused=()=>{this.onTextEditingFocusChanged(true)},this.onTextEditingBlurred=()=>{this.onTextEditingFocusChanged(false)},this.onTextEditingFocusChanged=focused=>{if(this._sendTextFocusChanged!=null&&this._entityId!=null)this._sendTextFocusChanged(this._entityId,focused,this.getTextNodeRect(this.contentEditableElement))},this.onTextContentChange=()=>{const textContent=this.contentEditableElement.textContent;elementUpdater.textContent(this.targetElement,textContent,this._editingSdk?.flags);clampFontSize(this.targetElement);this.syncConfig();const event=new CustomEvent(TEXT_UPDATED_EVENT_NAME,{detail:{textContent}});this.dispatchEvent(event)}}}const focusableElements=["input:not([disabled]):not([type=hidden])","select:not([disabled])","textarea:not([disabled])","button:not([disabled])","a[href]","area[href]","summary","iframe","object","embed","audio[controls]","video[controls]","[contenteditable]","[tabindex]","[autofocus]","[onclick]"];const contentElements=["span","img"];const FOCUSABLE_SELECTOR=focusableElements.join(",");const CONTENT_SELECTOR=contentElements.join(",");const interactionEvents=new Set(["click","dblclick","mousedown","mouseover","touchstart","touchend","pointerdown","dragstart","drag","dragenter"]);const handlerRegistry=new WeakMap;const originalAddEventListener=EventTarget.prototype.addEventListener;EventTarget.prototype.addEventListener=function(type,listener,options){if(interactionEvents.has(type)&&this instanceof HTMLElement){const registry=(handlerRegistry.has(this)?handlerRegistry:handlerRegistry.set(this,new Map)).get(this);const listeners=(registry.has(type)?registry:registry.set(type,new Set)).get(type);listeners.add(listener)}originalAddEventListener.call(this,type,listener,options)};const originalRemoveEventListener=EventTarget.prototype.removeEventListener;EventTarget.prototype.removeEventListener=function(type,listener,options){if(interactionEvents.has(type)&&this instanceof HTMLElement){const registry=handlerRegistry.get(this);const listeners=registry?.get(type);listeners?.delete(listener);if(listeners?.size===0)registry?.delete(type);if(registry?.size===0)handlerRegistry.delete(this)}originalRemoveEventListener.call(this,type,listener,options)};function isInteractive(element){if(element instanceof TextEditor)return false;const interactive=element.matches(FOCUSABLE_SELECTOR)||(handlerRegistry.get(element)?.size??0)>0;if(interactive)return true;for(const event of interactionEvents){if(element[`on${event}`]!=null)return true}return element.parentElement!=null&&element.matches(CONTENT_SELECTOR)?isInteractive(element.parentElement):false}const overlay_Z_INDEX_MAX=2147483647;class Overlay extends HTMLElement{get overlay(){return Preconditions.checkExists(this._overlay)}connectedCallback(){if(this._shadowRoot!=null)return;this._shadowRoot=this.attachShadow({mode:"open"});this.style.position="fixed";this.style.zIndex=overlay_Z_INDEX_MAX.toString();this.style.pointerEvents="none";const overlay=document.createElement("div");overlay.style.position="fixed";overlay.style.pointerEvents="none";overlay.style.inset="0";this._shadowRoot.appendChild(overlay);this._overlay=overlay}}function appendToDocument(element){if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",(()=>{document.body.append(element)}));else document.body.append(element)}class ElementOverlay extends Overlay{static createElementOverlay(){const elementOverlay=document.createElement("canva-element-overlay");Preconditions.checkState(elementOverlay instanceof ElementOverlay,"The selected element is not a ElementOverlay");return elementOverlay}setSelectableElementFrames(selectableElementFrames){this.clearSelectableElementFrames();this.selectableElementFrames=selectableElementFrames.map(createFlashingHighlightFrame);this.selectableElementFrames.forEach((frame=>this.overlay?.appendChild(frame)))}clearSelectableElementFrames(){this.selectableElementFrames.forEach((frame=>frame.remove()));this.selectableElementFrames=[]}setTemplateElementFrames(templateElementFrames){this.clearTemplateElementFrames();this.templateElementFrames=templateElementFrames.map(createDashedHighlightFrame);this.templateElementFrames.forEach((frame=>this.overlay?.appendChild(frame)))}clearTemplateElementFrames(){this.templateElementFrames.forEach((frame=>frame.remove()));this.templateElementFrames=[]}clearAllElementFrames(){this.clearTemplateElementFrames();this.clearSelectableElementFrames();this.selectableElementFrames=[];this.templateElementFrames=[]}disconnectedCallback(){this.clearAllElementFrames()}constructor(...args){super(...args),this.templateElementFrames=[],this.selectableElementFrames=[]}}function createDashedHighlightFrame(rect){const borderWidth=2;const borderOutset=borderWidth/-2;const borderShadowWidth=1;const borderShadowColor="#394C6026";const dashedBorderColor1="#FFFFFF";const dashedBorderColor2="#35475A33";const borderImageLength=6;const rectElement=document.createElement("div");rectElement.style.position="absolute";rectElement.style.top=`${rect.top+borderOutset}px`;rectElement.style.left=`${rect.left+borderOutset}px`;rectElement.style.width=`${rect.width-borderOutset*2}px`;rectElement.style.height=`${rect.height-borderOutset*2}px`;rectElement.style.border="0 none";rectElement.style.backgroundImage=[`linear-gradient(to right, ${dashedBorderColor1} 60%, ${dashedBorderColor2} 60%)`,`linear-gradient(to bottom, ${dashedBorderColor1} 60%, ${dashedBorderColor2} 60%)`,`linear-gradient(to right, ${dashedBorderColor1} 60%, ${dashedBorderColor2} 60%)`,`linear-gradient(to bottom, ${dashedBorderColor1} 60%, ${dashedBorderColor2} 60%)`,`linear-gradient(to right, ${borderShadowColor}, ${borderShadowColor})`,`linear-gradient(to bottom, ${borderShadowColor}, ${borderShadowColor})`,`linear-gradient(to right, ${borderShadowColor}, ${borderShadowColor})`,`linear-gradient(to bottom, ${borderShadowColor}, ${borderShadowColor})`].join(", ");rectElement.style.backgroundPosition=["top","right","bottom","left",`center ${borderWidth}px`,`calc(100% - ${borderWidth}px) center`,`center calc(100% - ${borderWidth}px)`,`${borderWidth}px center`].join(", ");rectElement.style.backgroundSize=[`${borderImageLength}px ${borderWidth}px`,`${borderWidth}px ${borderImageLength}px`,`${borderImageLength}px ${borderWidth}px`,`${borderWidth}px ${borderImageLength}px`,`calc(100% - ${borderWidth*2+borderShadowWidth*2}px) ${borderShadowWidth}px`,`${borderShadowWidth}px calc(100% - ${borderWidth*2}px)`,`calc(100% - ${borderWidth*2+borderShadowWidth*2}px) ${borderShadowWidth}px`,`${borderShadowWidth}px calc(100% - ${borderWidth*2}px)`].join(", ");rectElement.style.backgroundRepeat="repeat-x, repeat-y, repeat-x, repeat-y, no-repeat, no-repeat, no-repeat, no-repeat";rectElement.style.boxShadow=`0 0 0 1px ${borderShadowColor}`;return rectElement}function createFlashingHighlightFrame(rect){const borderWidth=2;const borderOutset=borderWidth/-2;const rectElement=document.createElement("div");rectElement.style.position="absolute";rectElement.style.top=`${rect.top+borderOutset}px`;rectElement.style.left=`${rect.left+borderOutset}px`;rectElement.style.width=`${rect.width-borderOutset*2}px`;rectElement.style.height=`${rect.height-borderOutset*2}px`;rectElement.style.rotate=`${rect.rotation??0}deg`;rectElement.style.pointerEvents="none";rectElement.style.boxSizing="border-box";rectElement.style.border=`${borderWidth}px solid #7630D7`;rectElement.animate([{opacity:0},{opacity:1},{opacity:.5},{opacity:1},{opacity:0}],{duration:2e3,easing:"ease-out",fill:"forwards"});return rectElement}class InteractionBlockOverlay extends Overlay{static createInteractionBlockOverlay(){const interactionBlockOverlay=document.createElement("canva-interaction-block-overlay");Preconditions.checkState(interactionBlockOverlay instanceof InteractionBlockOverlay,"The selected element is not a InteractionBlockOverlay");return interactionBlockOverlay}connectedCallback(){super.connectedCallback();this.style.pointerEvents="auto";this.overlay.style.pointerEvents="auto"}}class RequestAnimationFrameLoop{onStarted(fn){this.startedCallback=fn;return this}onFrame(fn){this.eachCallback=fn;return this}onStopped(fn){this.stoppedCallback=fn;return this}start(){if(this.rafId!=null)return this;if(this.startedCallback)this.startedCallback(this.ctx,this);const tick=ts=>{if(this.rafId==null)return;if(this.eachCallback)this.eachCallback(this.ctx,this,ts);if(this.rafId!=null)this.rafId=requestAnimationFrame(tick)};this.rafId=requestAnimationFrame(tick);return this}stop(recreateObservers=true){if(this.rafId==null)return this;cancelAnimationFrame(this.rafId);this.rafId=null;if(recreateObservers&&this.stoppedCallback)this.stoppedCallback(this.ctx,this);return this}get running(){return this.rafId!=null}constructor(ctx){this.ctx=ctx;this.rafId=null;this.startedCallback=null;this.eachCallback=null;this.stoppedCallback=null;this.ctx=ctx}}const normalizeTo1=n=>Math.abs(1-n)<.005||n<.5?1:n;const THRESHOLDS=Array.from({length:101},((_,i)=>i*.01));const CAGE_INTERSECTION_MIN=.1;const CAGE_INTERSECTION_MAX=3;let cageViewportWidth=window.innerWidth;let cageViewportHeight=window.innerHeight;let cageScaleFactor=1;class PositionObserver{static unobserveAll(ctx){const{observers,target}=ctx;observers.top?.unobserve(target);observers.right?.unobserve(target);observers.bottom?.unobserve(target);observers.left?.unobserve(target)}static positionChanging(ctx,loop){const{target,rect,owner}=ctx;const r=target.getBoundingClientRect();const unchanged=r.left===rect.left&&r.top===rect.top&&r.right===rect.right&&r.bottom===rect.bottom;if(unchanged)loop.stop();else{rect.left=r.left;rect.top=r.top;rect.right=r.right;rect.bottom=r.bottom;owner.callback(target,r)}}static createObserver(ctx){const{target,rect,observers,recreationList,observerCallback}=ctx;const vw=cageViewportWidth;const vh=cageViewportHeight;const{top,right,bottom,left}=rect;if(recreationList.has("top")){observers.top?.unobserve(target);observers.top=new IntersectionObserver(((entries,observer)=>observerCallback.call(observer,entries)),{root:document,threshold:THRESHOLDS,rootMargin:`-1px 0px ${-Math.min(vh-top-2,vh-2)}px 0px`})}if(recreationList.has("right")){observers.right?.unobserve(target);observers.right=new IntersectionObserver(((entries,observer)=>observerCallback.call(observer,entries)),{root:document,threshold:THRESHOLDS,rootMargin:`0px 0px 0px ${-Math.min(right-2,vw-1)}px`})}if(recreationList.has("bottom")){observers.bottom?.unobserve(target);observers.bottom=new IntersectionObserver(((entries,observer)=>observerCallback.call(observer,entries)),{root:document,threshold:THRESHOLDS,rootMargin:`${-Math.min(bottom-2,vh-1)}px 0px 0px 0px`})}if(recreationList.has("left")){observers.left?.unobserve(target);observers.left=new IntersectionObserver(((entries,observer)=>observerCallback.call(observer,entries)),{root:document,threshold:THRESHOLDS,rootMargin:`0px ${-Math.min(vw-left-2,vw-2)}px 0px -1px`})}recreationList.clear();observers.top?.observe(target);observers.right?.observe(target);observers.bottom?.observe(target);observers.left?.observe(target)}buildObserverCallback(target,observers,recreationList){const positionObserver=this;const rafLoops=this.rafLoops;return function(entries){const last=entries[entries.length-1];const{top:targetTop,right:targetRight,bottom:targetBottom,left:targetLeft}=last.boundingClientRect;const topRec=this===observers.top?entries:observers.top?.takeRecords()??[];const rightRec=this===observers.right?entries:observers.right?.takeRecords()??[];const bottomRec=this===observers.bottom?entries:observers.bottom?.takeRecords()??[];const leftRec=this===observers.left?entries:observers.left?.takeRecords()??[];if(topRec.length){const entry=topRec[topRec.length-1];const rootBounds=entry.rootBounds;if(rootBounds!=null){const{top:scaleFactor,bottom:rootBottom,width:rootWidth}=rootBounds;const normalizedScaleFactor=normalizeTo1(scaleFactor);cageScaleFactor=normalizedScaleFactor;cageViewportWidth=rootWidth/normalizedScaleFactor;const intersectionHeight=rootBottom/normalizedScaleFactor-targetTop;if(!(CAGE_INTERSECTION_MIN=0)recreationList.add("top")}}if(rightRec.length){const entry=rightRec[rightRec.length-1];const rootBounds=entry.rootBounds;if(rootBounds!=null){const{right:rootRight,left:rootLeft,height:rootHeight}=rootBounds;const scaleFactor=cageScaleFactor;cageViewportHeight=rootHeight/scaleFactor;cageViewportWidth=rootRight/scaleFactor;const intersectionWidth=targetRight-rootLeft/scaleFactor;if(!(CAGE_INTERSECTION_MIN=0)recreationList.add("left")}}if(!target.offsetParent){positionObserver.callback(target,last.boundingClientRect);return}if(recreationList.size){positionObserver.callback(target,last.boundingClientRect);rafLoops.get(target)?.start()}}}observe(target){if(this.observers.has(target))return;cageViewportWidth=window.innerWidth;cageViewportHeight=window.innerHeight;const observers={top:null,right:null,bottom:null,left:null};const recreationList=new Set(["top","right","bottom","left"]);const targetRect=target.getBoundingClientRect();const observerCallback=this.buildObserverCallback(target,observers,recreationList);const rafCtx={target,observers,rect:{top:targetRect.top,right:targetRect.right,bottom:targetRect.bottom,left:targetRect.left},owner:this,recreationList,observerCallback};const rafLoop=new RequestAnimationFrameLoop(rafCtx).onStarted(PositionObserver.unobserveAll).onFrame(PositionObserver.positionChanging).onStopped(PositionObserver.createObserver);PositionObserver.createObserver(rafCtx);this.observers.set(target,observers);this.rafLoops.set(target,rafLoop)}unobserve(target){if(!this.observers.has(target))return;const rafLoop=Preconditions.checkExists(this.rafLoops.get(target));rafLoop.stop(false);const sideObservers=Preconditions.checkExists(this.observers.get(target));sideObservers.top?.unobserve(target);sideObservers.right?.unobserve(target);sideObservers.bottom?.unobserve(target);sideObservers.left?.unobserve(target);this.observers.delete(target);this.rafLoops.delete(target)}disconnect(){const targets=Array.from(this.observers.keys());for(const target of targets)this.unobserve(target)}getTargets(){return this.observers.keys()}constructor(callback){this.callback=callback;this.observers=new Map;this.rafLoops=new Map}}const CONTAINERIZED_ATTRIBUTES=new Set(["ROTATION","SCALE","TRANSLATION","REORDER"]);class Selection2{dispose(){document.removeEventListener("click",this.onClick,true);this.positionObserver.disconnect();this.currentSelectionStyles?.dispose();this.currentSelectionStyles=undefined;this.richtextHiddenStyles?.dispose();this.richtextHiddenStyles=undefined;this.interactionBlockOverlay?.remove();this.elementOverlay?.remove();this.styles.dispose()}set interactionMode(value){if(this.mode===value)return;this.mode=value;this.updateOverlays()}updateOverlays(){switch(this.mode){case undefined:this.clearSelection();this.interactionBlockOverlay?.remove();this.elementOverlay&&this.elementOverlay.clearSelectableElementFrames();break;case InteractionMode.EDIT:this.interactionBlockOverlay&&appendToDocument(this.interactionBlockOverlay);this.elementOverlay&&this.elementOverlay.setSelectableElementFrames(this.getAllSelectableElements().map((e=>e.boundingClientRect)));break;case InteractionMode.MIXED:this.interactionBlockOverlay?.remove();this.elementOverlay&&this.elementOverlay.clearSelectableElementFrames();break;default:throw new UnreachableError(this.mode)}}clearSelection(){this.currentSelectedElements.forEach((e=>this.positionObserver.unobserve(e)));this.currentSelectionStyles?.dispose();this.currentSelectionStyles=undefined;this.currentSelectedElements=[];this.currentSelection="";this.currentRichtextSelectors=[];this.updateRichtextHiding()}updateRichtextHiding(){this.richtextHiddenStyles?.dispose();this.richtextHiddenStyles=undefined;if(this.currentRichtextSelectors.length===0)return;const rules=this.currentRichtextSelectors.reduce(((acc,selector)=>{acc[selector]={visibility:"hidden"};return acc}),{});this.richtextHiddenStyles=this.styles.insert(rules)}maybeRecomputeSelection(edits){const currentSelectors=edits.map((e=>e.selector));const previousSelectors=this.appliedEdits.map((e=>e.selector));const selectors=[...new Set([...currentSelectors,...previousSelectors]).values()].join(", ");this.appliedEdits=edits;if(!selectors)return;if(this.currentSelectedElements.some((e=>e.matches(selectors))))this.recomputeSelection()}recomputeSelection(){const nodes=this.currentSelectedElements.map((e=>this.asMaybeSelectable(e))).filter((e=>e!=null&&this.isSelectable(e)));nodes.length>0&&this.maybeSetSelection(nodes)}selectBackground(elements){const background=Preconditions.checkExists(elements.find((element=>element.selector==="body")));Preconditions.checkState(this.isSelectable(background),"Background should be selectable");this.maybeSetSelection([background])}maybeSetSelection(selectableNodes){const nodes=reduceSelection(selectableNodes);if(nodes.length===0)return;const selection=new SetSelectionRequest({selection:new Selection({boundingRect:new Rect(nodes[0].boundingClientRect),editables:nodes.flatMap((node=>node.attributes.map((attribute=>new Editable({selector:node.selector,attribute})))))})});const selectionState=JSON.stringify(selection);if(this.currentSelection===selectionState)return;this.currentSelectionStyles?.dispose();this.currentSelectedElements.forEach((e=>this.positionObserver.unobserve(e)));this.editingService.setSelection(selection);this.currentSelectedElements=nodes.map((n=>n.element));const disableTransitions=nodes.reduce(((acc,n)=>({...acc,[n.selector]:{transition:"none"}})),{});this.currentSelectionStyles=this.styles.insert(disableTransitions);this.currentSelection=selectionState;this.currentRichtextSelectors=nodes.filter((n=>n.attributes.some((a=>a.type==="RICHTEXT")))).map((n=>n.selector));this.updateRichtextHiding();this.currentSelectedElements.forEach((e=>this.positionObserver.observe(e)))}getSelectablesFromPoint(clientX,clientY){const elements=document.elementsFromPoint(clientX,clientY);return elements.map((element=>this.asMaybeSelectable(element))).filter(exists).filter(this.isSelectable)}getInteractablesFromPoint(clientX,clientY){const elements=document.elementsFromPoint(clientX,clientY);return elements.map((element=>this.asMaybeSelectable(element))).filter(exists)}getAllSelectableElements(){return[...queryAllSelectableElements(document)].map((e=>this.asMaybeSelectable(e))).filter((e=>e!=null&&this.isSelectable(e)))}isSelectable(maybeSelectable){return maybeSelectable.selector!=null&&maybeSelectable.attributes.length>0}asMaybeSelectable(element){if(!(element instanceof HTMLElement))return undefined;const selector=uniqueIdentifier(element);const interactive=isInteractive(element);if(selector==null&&!interactive)return undefined;return{selector,interactive,element,boundingClientRect:getBounds(element),attributes:selector?editableAttributesForElement(element):[]}}constructor(interactionMode,editingService){this.editingService=editingService;this.mode=undefined;this.interactionBlockOverlay=undefined;this.elementOverlay=undefined;this.currentSelection="";this.currentRichtextSelectors=[];this.currentSelectedElements=[];this.appliedEdits=[];this.styles=new CssStyles;this.onClick=ev=>{switch(this.mode){case undefined:return;case InteractionMode.MIXED:{const elements=this.getInteractablesFromPoint(ev.clientX,ev.clientY);if(elements.length===0)return;const first=elements[0];if(first.interactive){this.selectBackground(elements);return}const selectables=elements.filter(this.isSelectable);this.maybeSetSelection(selectables);break}case InteractionMode.EDIT:{const selectables=this.getSelectablesFromPoint(ev.clientX,ev.clientY);this.maybeSetSelection(selectables);break}default:throw new UnreachableError(this.mode)}};this.mode=interactionMode;this.interactionBlockOverlay=InteractionBlockOverlay.createInteractionBlockOverlay();this.elementOverlay=ElementOverlay.createElementOverlay();appendToDocument(this.elementOverlay);this.updateOverlays();document.addEventListener("click",this.onClick,true);this.positionObserver=new PositionObserver((()=>this.recomputeSelection()))}}function reduceSelection(nodes){if(nodes.length===0)return nodes;const isContainerized=n=>n.attributes.some((a=>CONTAINERIZED_ATTRIBUTES.has(a.type)));const[first,...remaining]=nodes;let selection=[first];const containerizedSet=new Set;if(isContainerized(first))containerizedSet.add(first.element);for(const node of remaining){if(!areEqual(first.boundingClientRect,node.boundingClientRect))break;selection.push(node);if(isContainerized(node))containerizedSet.add(node.element)}if(containerizedSet.size>0)selection=selection.reduceRight(((acc,node)=>{if(!isContainerized(node)){acc.push(node);return acc}let current=node.element.parentElement;while(current){if(containerizedSet.has(current)){const attributes=node.attributes.filter((a=>!CONTAINERIZED_ATTRIBUTES.has(a.type)));if(attributes.length>0)acc.push({...node,attributes});return acc}current=current.parentElement}acc.push(node);return acc}),[]).reverse();return selection}function areEqual(a,b){return a.left===b.left&&a.top===b.top&&a.width===b.width&&a.height===b.height&&a.rotation===b.rotation}class Editing2Sdk{init(){this.fingerprinting.observe()}async setInteractionMode(request){if(this.selection==null)this.selection=new Selection2(request.interactionMode,this.editingService);else this.selection.interactionMode=request.interactionMode;return new SetInteractionModeResponse}async clearSelection(request){this.selection?.clearSelection();return new ClearSelectionResponse}async renderEdits(request){this.renderer.applyAll(request.edits);this.selection?.maybeRecomputeSelection(request.edits);return new RenderEditsResponse}async onDragDropStart(request){if(request.mediaRef!=null&&request.previewUrl!=null)this.renderer.registerDragPreview(request.mediaRef,request.previewUrl);return new DragDropStartResponse}async onDragDropHover(request){const selectables=this.selection?.getSelectablesFromPoint(request.xPos??0,request.yPos??0);const nodes=selectables?.flatMap((node=>node.attributes.filter((attribute=>attribute.type==="MEDIA_REPLACE")).map((()=>new Droppable({selector:node.selector,attribute:new MediaReplaceDroppableAttribute})))));const node=nodes?.[0];if(node!=null&&request.previewUrl!=null)this.renderer.showDragPreview(node.selector,request.previewUrl);else this.renderer.clearDragPreview();return new DragDropHoverResponse({nodes})}async onDragDropEnd(request){if(!request.dropped)this.renderer.clearDragPreview();return new DragDropEndResponse}constructor(editingService,errorService){this.editingService=editingService;this.errorService=errorService;const imageResolver=new RpcCodeletImageResolver(editingService);this.renderer=new Renderer(imageResolver);this.fingerprinting=new Fingerprinting}}const DEFAULT_DELAY=50;function debounce(func,delayOrOptions=DEFAULT_DELAY,options={}){let delay;if(typeof delayOrOptions==="object"){options=delayOrOptions;delay=DEFAULT_DELAY}else delay=delayOrOptions;const{leading}=options;let callTimeoutId;let delayed;let firstCallResetTimeoutId;let isFirstCall=true;return function(...args){if(!delayed)delayed=Promise.withResolvers();const{promise,resolve}=delayed;const runFunc=()=>{resolve(func.apply(this,args));delayed=undefined};if(leading&&isFirstCall)runFunc();else{clearTimeout(callTimeoutId);callTimeoutId=setTimeout(runFunc,delay)}if(leading){isFirstCall=false;clearTimeout(firstCallResetTimeoutId);firstCallResetTimeoutId=setTimeout((()=>isFirstCall=true),delay)}return promise}}const renderableCodeletAttributeDefaults={textContent:undefined,background:undefined,backgroundDimensions:undefined,backgroundImageSrcs:[],color:undefined,font:undefined,fontSize:undefined,letterSpacing:undefined,lineHeight:undefined,imageSrc:undefined,imageSrcs:[],altText:undefined};class RenderableCodeletAttributesVisitorImpl{}class RenderableCodeletAttributesVisitor extends RenderableCodeletAttributesVisitorImpl{visit(config){this.visitTextContent(config.textContent);this.visitBackground(config.background,config.backgroundDimensions);this.visitBackgroundImageSrcs(config.backgroundImageSrcs);this.visitColor(config.color);this.visitFont(config.font);this.visitFontSize(config.fontSize);this.visitLetterSpacing(config.letterSpacing);this.visitLineHeight(config.lineHeight);this.visitImageSrc(config.imageSrc);this.visitImageSrcs(config.imageSrcs);this.visitAltText(config.altText)}}class RenderableCodeletAttributesMapper extends RenderableCodeletAttributesVisitorImpl{map(config,initialValue){let value=initialValue;value=this.visitTextContent(config.textContent,value);value=this.visitBackground(config.background,config.backgroundDimensions,value);value=this.visitBackgroundImageSrcs(config.backgroundImageSrcs,value);value=this.visitColor(config.color,value);value=this.visitFont(config.font,value);value=this.visitFontSize(config.fontSize,value);value=this.visitLetterSpacing(config.letterSpacing,value);value=this.visitLineHeight(config.lineHeight,value);value=this.visitImageSrc(config.imageSrc,value);value=this.visitImageSrcs(config.imageSrcs,value);value=this.visitAltText(config.altText,value);return value}}class FontMetadataVisitorImpl{}class FontMetadataMapper extends FontMetadataVisitorImpl{map(config,initialValue){let value=initialValue;value=this.visitCssFontFamily(config.cssFontFamily,value);value=this.visitId(config.id,value);value=this.visitSrc(config.src,value);value=this.visitWeight(config.weight,value);value=this.visitStyle(config.style,value);value=this.visitVariants(config.variants,value);return value}}class ScrollObserver{initialize(){if(this.scrollHandler!=null)return;const debouncedScrollEnd=debounce((async()=>{if(this.scrolling){this.scrolling=false;this.onScrollCompleted()}}));this.scrollHandler=()=>{if(!this.scrolling){this.scrolling=true;this.onScrollStarted()}debouncedScrollEnd()};window.addEventListener("scroll",this.scrollHandler,{passive:true})}dispose(){if(this.scrollHandler!=null){window.removeEventListener("scroll",this.scrollHandler);this.scrollHandler=undefined}}constructor(callbacks){this.scrolling=false;this.onScrollStarted=callbacks.onScrollStarted;this.onScrollCompleted=callbacks.onScrollCompleted}}const DATA_TEMPLATE_ID="data-template-id";class DragAndDrop{getDragTargetFromPoint(clientX,clientY){const elements=document.elementsFromPoint(clientX,clientY);return elements.find((e=>{const templateId=e.getAttribute(DATA_TEMPLATE_ID);const config=templateId?this.editingSdk.config.get(templateId):undefined;return templateId!=null&&isPageRootElement(templateId,this.editingSdk.config)||config?.imageSrc!=null}))}showPreview(entity,entityId,previewUrl,dimensions){if(this.activePreview?.entityId===entityId)return;this.dispose();const original=Preconditions.checkExists(this.editingSdk.config.get(entityId));if(isPageRootElement(entityId,this.editingSdk.config)){const previewConfig=new RenderableCodeletAttributes({...original,background:`url(${previewUrl})`,backgroundDimensions:dimensions,backgroundImageSrcs:[]});elementUpdater.fill(entity,previewConfig);this.activePreview={entityId,dispose:()=>{elementUpdater.fill(entity,this.editingSdk.config.get(entityId)??original)}}}else{const previewConfig=new RenderableCodeletAttributes({...original,imageSrc:previewUrl,imageSrcs:[]});elementUpdater.fill(entity,previewConfig);this.activePreview={entityId,dispose:()=>{elementUpdater.fill(entity,this.editingSdk.config.get(entityId)??original)}}}}clearPreview(){this.dispose()}dispose(){this.activePreview?.dispose();this.activePreview=undefined}constructor(editingSdk){this.editingSdk=editingSdk}}class IdGenerator{next(){return`${this.prefix}${this.idCount++}`}constructor(prefix="__id"){this.prefix=prefix;this.idCount=0}}const selection_DATA_TEMPLATE_ID="data-template-id";const CANVA_CLASS_PREFIX="canva-";class selection_Selection{initOverlays(){this.interactionBlockOverlay=InteractionBlockOverlay.createInteractionBlockOverlay();this.elementOverlay=ElementOverlay.createElementOverlay();appendToDocument(this.elementOverlay)}handleInteractionModeChanged(interactionMode){this.interactionMode=interactionMode;switch(interactionMode){case undefined:this.clearSelection();this.interactionBlockOverlay?.remove();this.elementOverlay&&this.elementOverlay.clearSelectableElementFrames();break;case payloads_proto_InteractionMode.MIXED:this.interactionBlockOverlay?.remove();this.elementOverlay&&this.elementOverlay.clearSelectableElementFrames();break;case payloads_proto_InteractionMode.EDIT:this.interactionBlockOverlay&&appendToDocument(this.interactionBlockOverlay);this.elementOverlay&&this.elementOverlay.setSelectableElementFrames(this.getAllSelectableElements().map((e=>{const r=getElementBoundingRect(e,this.editingSdk.config);return{top:r.top,left:r.left,width:r.width,height:r.height,rotation:0}})));break;default:throw new UnreachableError(interactionMode)}}observe(){const onMouseMove=ev=>{const element=this.getInteractableFromPoint(ev.clientX,ev.clientY);if(element==null){this.clearHover();return}switch(this.interactionMode){case payloads_proto_InteractionMode.MIXED:!isInteractive(element)?this.setHoveredElement(element):this.clearHover();break;case payloads_proto_InteractionMode.EDIT:this.setHoveredElement(element);break;case undefined:break;default:throw new UnreachableError(this.interactionMode)}};const throttledOnMouseMove=throttle((ev=>onMouseMove(ev)),20);const onMouseLeave=ev=>{throttledOnMouseMove.cancel();onMouseMove(ev)};const onClick=ev=>{switch(this.interactionMode){case payloads_proto_InteractionMode.MIXED:{const element=this.getInteractableFromPoint(ev.clientX,ev.clientY);if(element==null||this.isSelected(element))return;!isInteractive(element)?this.selectElement(element):this.maybeSelectBackground();break}case payloads_proto_InteractionMode.EDIT:const element=this.getSelectableFromPoint(ev.clientX,ev.clientY);const templateId=element?.getAttribute(selection_DATA_TEMPLATE_ID);if(templateId==null||isPageRootElement(templateId,this.editingSdk.config))this.editingSdk.sendClearEditMode();if(element==null||this.isSelected(element))return;this.selectElement(element);break;case undefined:break;default:throw new UnreachableError(this.interactionMode)}};const onContextMenu=ev=>{if(!this.editingSdk.flags.enableEditingContextMenu)return;if(this.interactionMode==null)return;const element=this.getSelectableFromPoint(ev.clientX,ev.clientY);if(element&&TextEditor.getEditorIfActive(element))return;const templateId=element?.getAttribute(selection_DATA_TEMPLATE_ID);if(templateId==null){this.interactionMode===payloads_proto_InteractionMode.EDIT&&ev.preventDefault();return}this.editingSdk.sendShowContextMenu(templateId);ev.preventDefault()};document.addEventListener("contextmenu",onContextMenu);document.addEventListener("mousemove",throttledOnMouseMove);document.addEventListener("mouseleave",onMouseLeave);document.addEventListener("click",onClick,true);return()=>{document.removeEventListener("contextmenu",onContextMenu);document.removeEventListener("mousemove",throttledOnMouseMove);document.removeEventListener("mouseleave",onMouseLeave);document.removeEventListener("click",onClick,true)}}getSelectableFromPoint(clientX,clientY){const elements=document.elementsFromPoint(clientX,clientY);return elements.find((e=>this.isSelectable(e)))}getInteractableFromPoint(clientX,clientY){const elements=document.elementsFromPoint(clientX,clientY);return elements.find((e=>this.isSelectable(e)||isInteractive(e)))}isSelectable(element){const templateId=element.getAttribute(selection_DATA_TEMPLATE_ID);return templateId&&this.editingSdk.config.has(templateId)}isSelected(element){return element===this.selectedElement}selectElement(element){if(this.hoverElement===element)this.clearHover();this.resetSelectionState();this.unobserveSelectedElement=this.layoutShiftObserver.observeElement(element,(()=>{this.updateCurrentSelection(element)}));this.selectedElement=element;this.maybeEditText(element);this.maybeSetTemplatedElements(element);this.sendSelectionChange(element)}updateCurrentSelection(element){if(this.selectedElement!==element)return;this.maybeSetTemplatedElements(element);this.sendSelectionChange(element)}maybeSelectBackground(){const backgroundId=getPageRootTemplateId(this.editingSdk.config);const element=document.querySelector(`[${selection_DATA_TEMPLATE_ID}="${backgroundId}"]`);if(element==null)return false;this.selectElement(element);return true}maybeSetTemplatedElements(element){if(this.elementOverlay==null)return;const templateId=element.getAttribute(selection_DATA_TEMPLATE_ID);if(templateId==null)return;const templateElements=getElementsForTemplateId(templateId).filter((e=>e!==element));const templatedElementRects=templateElements.map((e=>getElementBoundingRect(e,this.editingSdk.config)));this.elementOverlay.setTemplateElementFrames(templatedElementRects)}setHoveredElement(element){if(element===this.hoverElement)return;this.unobserveHoverElement?.();if(element==null||element===this.selectedElement){this.editingSdk.sendHoverElementChanged(undefined);this.hoverElement=undefined;return}const updateHoverElement=()=>{const elementRect=getElementBoundingRect(element,this.editingSdk.config);this.editingSdk.sendHoverElementChanged(elementRect)};const unobserveHoverElement=this.layoutShiftObserver.observeElement(element,updateHoverElement);this.hoverElement=element;this.unobserveHoverElement=unobserveHoverElement;updateHoverElement()}clearSelection(){this.resetSelectionState();this.editingSdk.sendSelectionChangeCompleted(undefined)}resetSelectionState(){this.finishTextEditing();this.unobserveHoverElement?.();this.unobserveHoverElement=undefined;this.unobserveSelectedElement?.();this.unobserveSelectedElement=undefined;this.elementOverlay&&this.elementOverlay.clearAllElementFrames();this.selectedElement=undefined}clearHover(){this.unobserveHoverElement?.();this.unobserveHoverElement=undefined;this.editingSdk.sendHoverElementChanged(undefined);this.hoverElement=undefined}onScrollStarted(){this.elementOverlay&&this.elementOverlay.clearAllElementFrames()}onScrollCompleted(){this.selectedElement&&this.updateCurrentSelection(this.selectedElement)}maybeEditText(element){const templateId=element.getAttribute(selection_DATA_TEMPLATE_ID);if(templateId==null)return;const capabilities=this.editingSdk.config.get(templateId);const expectedTextContent=capabilities?.textContent;if(expectedTextContent==null)return;if(!TextEditor.canCreateTextEditor(element))return;const persistChanges=async e=>{const{detail:{textContent}}=e;await this.editingSdk.sendTextChanged(templateId,textContent)};const onFinishTextEditing=()=>{if(this.editingSdk.flags.enableClampingToPreventWordBreaks)clampFontSize(element)};this.textEditor=TextEditor.createTextEditor(element,templateId,this.editingSdk,onFinishTextEditing,((entityId,focused,textDimensions)=>this.editingSdk.sendTextFocusChanged(entityId,focused,textDimensions)),persistChanges);document.body.appendChild(this.textEditor);this.textEditor.focusTextEditor()}finishTextEditing(){this.textEditor?.finishEditing();this.textEditor?.remove();this.textEditor=undefined}focusTextSelection(){this.textEditor?.focusTextRange()}getAllSelectableElements(visibleOnly=false){return[...document.querySelectorAll(`[${selection_DATA_TEMPLATE_ID}]`)].filter((element=>{const elementId=element.getAttribute(selection_DATA_TEMPLATE_ID);if(!elementId||isPageRootElement(elementId,this.editingSdk.config))return false;if(visibleOnly&&element.checkVisibility!=null){const isVisible=element.checkVisibility({contentVisibilityAuto:true,opacityProperty:true,visibilityProperty:true});if(!isVisible)return false}return this.editingSdk.config.has(elementId)}))}async sendSelectionChange(element){const elementId=element.getAttribute(selection_DATA_TEMPLATE_ID);if(elementId==null)return;const{config}=this.editingSdk;const templateElements=getElementsForTemplateId(elementId).filter((e=>e!==element));const templatedElementRects=templateElements.map((e=>getElementBoundingRect(e,config)));const boundingRect=getElementBoundingRect(element,config);await this.editingSdk.sendSelectionChangeCompleted({entityId:elementId,boundingRect,permitPointerEvents:TextEditor.getEditorIfActive(element)!=null,templatedElements:templatedElementRects,elementLabel:getElementLabel(element,elementId,config),elementId:getElementInstanceId(element)})}constructor(editingSdk){this.editingSdk=editingSdk;this.textEditor=undefined;this.layoutShiftObserver=new LayoutShiftObserver;this.interactionMode=undefined;this.interactionBlockOverlay=undefined;this.elementOverlay=undefined;this.observe();this.initOverlays()}}const elementInstanceIds=new WeakMap;const elementInstanceIdGenerator=new IdGenerator("codelet-inner-element-");function getElementInstanceId(element){let id=elementInstanceIds.get(element);if(id==null){id=elementInstanceIdGenerator.next();elementInstanceIds.set(element,id)}return id}function getElementLabel(element,elementId,config){if(isPageRootElement(elementId,config))return elementId;for(const cls of element.classList){if(cls.startsWith(CANVA_CLASS_PREFIX))return cls.slice(CANVA_CLASS_PREFIX.length)}return element.tagName.toLowerCase()}function getElementsForTemplateId(id){return Array.from(document.querySelectorAll(`[${selection_DATA_TEMPLATE_ID}="${id}"]`))}function getElementBoundingRect(element,config){const boundingRect=element.getBoundingClientRect();const elementId=element.getAttribute(selection_DATA_TEMPLATE_ID)||undefined;if(elementId!=null&&isPageRootElement(elementId,config))return{top:boundingRect.top,left:boundingRect.left,width:element.scrollWidth,height:element.scrollHeight};return boundingRect}function throttle(func,delayMs=10){let latestArgs;let timeoutId;function executeFunc(){func(...latestArgs??[]);timeoutId=latestArgs=undefined}function throttled(...args){latestArgs=args;if(!timeoutId)timeoutId=setTimeout(executeFunc,delayMs)}throttled.cancel=()=>{clearTimeout(timeoutId);timeoutId=latestArgs=undefined};return throttled}const editing_sdk_impl_DATA_TEMPLATE_ID="data-template-id";class EditingSdk{get flags(){return{enableEditingContextMenu:!!this.enableEditingContextMenu,enableClampingToPreventWordBreaks:!!this.enableClampingToPreventWordBreaks,enableCodelet2LineHeight:!!this.enableCodelet2LineHeight}}async setupCommsClient(){const CodeletEditingSdkService={setConfig:async request=>{this.errorService.info("Received handleSetConfig");await this.handleSetConfig(request.config);return new SetConfigResponse},requestSelection:async request=>{this.errorService.info(`Received handleRequestSelection, selecting entity: ${request.entityId}`);const element=document.querySelector(`[${editing_sdk_impl_DATA_TEMPLATE_ID}="${request.entityId}"]`);element?this.selection.selectElement(element):this.selection.clearSelection();return new RequestSelectionResponse({success:element!=null})},onSelection:async request=>{this.errorService.info("Received handleSelection");const element=this.handleSelection(request.xPosPct,request.yPosPct);const entityId=element?.getAttribute(editing_sdk_impl_DATA_TEMPLATE_ID)??undefined;const success=entityId!=null&&!isPageRootElement(entityId,this.config);return new SelectionResponse({success})},onSelectionHover:async request=>{this.errorService.info("Received handleSelectionHover");this.handleSelectionHover(request.xPosPct,request.yPosPct);return new SelectionHoverResponse},onDragDropHover:async request=>{const dropTarget=this.dragAndDrop.getDragTargetFromPoint(request.xPos,request.yPos);const entityId=dropTarget?.getAttribute(editing_sdk_impl_DATA_TEMPLATE_ID)??undefined;const isColorOnlyRoot=entityId!=null&&isPageRootElement(entityId,this.config)&&this.config.get(entityId)?.backgroundDimensions==null;if(dropTarget!=null&&entityId!=null&&!isColorOnlyRoot)this.dragAndDrop.showPreview(dropTarget,entityId,request.previewUrl,request.previewDimensions);else this.dragAndDrop.clearPreview();return new DragDropHoverEventResponse({entityId:isColorOnlyRoot?undefined:entityId})},onDragDropEnd:async request=>{request.dropped?setTimeout((()=>this.dragAndDrop.clearPreview()),2e3):this.dragAndDrop.clearPreview();return new DragDropEndEventResponse},setFeatureFlags:async request=>{this.errorService.info("Received setFeatureFlags");this.enableClampingToPreventWordBreaks=request.enableClampingToPreventWordBreaks;this.enableEditingContextMenu=request.enableEditingContextMenu;this.enableCodelet2LineHeight=request.enableCodelet2LineHeight;return new SetFeatureFlagsResponse},setInteractionMode:async request=>{this.errorService.info(`Received setInteractionMode: ${request.interactionMode}`);this.selection.handleInteractionModeChanged(request.interactionMode);return new InteractionModeResponse},onInteractionClick:async request=>{this.errorService.info("Received handleInteractionClick");this.handleInteractionClick(request.xPosPct,request.yPosPct);return new InteractionClickResponse},selectBackground:async request=>{const backgroundId=getPageRootTemplateId(this.config);this.errorService.info(`Received handleRequestBackgroundSelection, selecting entity: ${backgroundId}`);const success=this.selection.maybeSelectBackground();if(!success)this.selection.clearSelection();return new SelectBackgroundResponse({success})},hoverBackground:async request=>{const backgroundId=getPageRootTemplateId(this.config);this.errorService.info(`Received handleRequestBackgroundHover, selecting entity: ${backgroundId}`);const element=document.querySelector(`[${editing_sdk_impl_DATA_TEMPLATE_ID}="${backgroundId}"]`);element?this.selection.setHoveredElement(element):this.selection.clearHover();return new HoverBackgroundResponse({success:element!=null})},focusText:async request=>{this.errorService.info(`Received handleFocusText, focusing entity: ${request.entityId}`);const element=document.querySelector(`[${editing_sdk_impl_DATA_TEMPLATE_ID}="${request.entityId}"]`);if(element!=null&&this.selection.isSelected(element)){this.selection.focusTextSelection();return new FocusTextResponse({success:true})}return new FocusTextResponse({success:false})},getEditableRegions:async request=>{const elements=this.selection.getAllSelectableElements(true);return new GetEditableRegionsResponse({editableRegions:elements.map((e=>{const rect=e.getBoundingClientRect();return new payloads_proto_Rect({top:rect.top,left:rect.left,width:rect.width,height:rect.height})}))})}};this.errorService.info("Successfully connected to parent");this.commsClient=this.createEditingClientComms(this.comms,CodeletEditingSdkService)}async handleSetConfig(config){await Promise.all(Array.from(config.entries()).map((async([k,c])=>{const entityConfig=this.config.get(k);const diff=(new class extends RenderableCodeletAttributesMapper{visitTextContent(value,acc){return{...acc,textContent:entityConfig?.textContent!==value?value:undefined}}visitBackground(background,backgroundDimensions,acc){return{...acc,...backgroundChanged(entityConfig,c)?{background,backgroundDimensions}:{}}}visitBackgroundImageSrcs(value,acc){return{...acc,backgroundImageSrcs:value??[]}}visitColor(value,acc){return{...acc,color:entityConfig?.color!==value?value:undefined}}visitFont(value,acc){const didChangeMapper=new class extends FontMetadataMapper{visitCssFontFamily(value,acc){return acc||entityConfig?.font?.cssFontFamily!==value}visitId(value,acc){return acc||entityConfig?.font?.id!==value}visitSrc(value,acc){return acc||entityConfig?.font?.src!==value}visitWeight(value,acc){return acc||entityConfig?.font?.weight!==value}visitStyle(value,acc){return acc||entityConfig?.font?.style!==value}visitVariants(value,acc){return acc||!areFontVariantsEqual(entityConfig?.font?.variants,value)}};const didChange=value!=null?didChangeMapper.map(value,false):true;return{...acc,font:didChange?value:undefined}}visitFontSize(value,acc){return{...acc,fontSize:entityConfig?.fontSize!==value?value:undefined}}visitLetterSpacing(value,acc){return{...acc,letterSpacing:entityConfig?.letterSpacing!==value?value:undefined}}visitLineHeight(value,acc){return{...acc,lineHeight:entityConfig?.lineHeight!==value?value:undefined}}visitImageSrc(value,acc){return{...acc,imageSrc:entityConfig?.imageSrc!==value?value:undefined}}visitImageSrcs(value,acc){return{...acc,imageSrcs:value??[]}}visitAltText(value,acc){return{...acc,altText:entityConfig?.altText!==value?value:undefined}}}).map(c,{...renderableCodeletAttributeDefaults});this.config.set(k,c);await this.renderEntity(k,diff,entityConfig,c)})))}async renderEntity(entityId,attr,previousConfig,fullConfig){const flags=this.flags;const elements=document.querySelectorAll(`[${editing_sdk_impl_DATA_TEMPLATE_ID}="${entityId}"]`);const resourcePromises=[];const didFillChange=fillChanged(previousConfig,fullConfig);elements.forEach((e=>{if(e==null||!(e instanceof HTMLElement))return;let textSizeAltered=false;if(didFillChange){const promise=elementUpdater.fill(e,fullConfig);if(promise!=null)resourcePromises.push(promise)}(new class extends RenderableCodeletAttributesVisitor{visitTextContent(value){if(value==null||TextEditor.getEditorIfActive(e)!=null)return;elementUpdater.textContent(e,value,flags);textSizeAltered=true}visitBackground(){}visitBackgroundImageSrcs(){}visitColor(value){value&&elementUpdater.color(e,value)}visitFont(value){if(value==null)return;const promise=elementUpdater.font(e,value,flags);textSizeAltered=true;if(promise!=null){resourcePromises.push(promise);if(flags.enableClampingToPreventWordBreaks)promise.then((()=>clampFontSize(e)))}}visitFontSize(value){if(value==null)return;elementUpdater.fontSize(e,value,flags);textSizeAltered=true}visitLetterSpacing(value){if(value==null)return;elementUpdater.letterSpacing(e,value);TextEditor.getEditorIfActive(e)?.syncConfig()}visitLineHeight(value){if(value==null)return;elementUpdater.lineHeight(e,value,flags);TextEditor.getEditorIfActive(e)?.syncConfig()}visitImageSrc(){}visitImageSrcs(){}visitAltText(){}}).visit(attr);if(textSizeAltered){clampFontSize(e);TextEditor.getEditorIfActive(e)?.syncConfig()}}));await Promise.all(resourcePromises)}async applyAttributesToElement(element,attr){const flags=this.flags;const resourcePromises=[];if(hasFill(attr)){const promise=elementUpdater.fill(element,attr);if(promise!=null)resourcePromises.push(promise)}(new class extends RenderableCodeletAttributesVisitor{visitTextContent(value){value&&elementUpdater.textContent(element,value,flags)}visitBackground(){}visitBackgroundImageSrcs(_value){}visitColor(value){value&&elementUpdater.color(element,value)}visitFont(value){if(value==null)return;const promise=elementUpdater.font(element,value,flags);if(promise!=null)resourcePromises.push(promise)}visitFontSize(value){value&&elementUpdater.fontSize(element,value,flags)}visitLetterSpacing(value){value!=null&&elementUpdater.letterSpacing(element,value)}visitLineHeight(value){value!=null&&elementUpdater.lineHeight(element,value,flags)}visitImageSrc(){}visitImageSrcs(_value){}visitAltText(){}}).visit(attr);await Promise.all(resourcePromises)}setupDOMObserver(){const observer=new MutationObserver((mutations=>{for(const mutation of mutations)if(mutation.type==="childList"){for(const node of mutation.addedNodes)if(node instanceof Element)this.applyConfigToNewElement(node)}}));observer.observe(document.documentElement,{childList:true,subtree:true});let previousWidth=window.innerWidth;window.addEventListener("resize",(()=>{if(previousWidth===window.innerWidth)return;previousWidth=window.innerWidth;this.debouncedWindowResize()}));this.scrollObserver.initialize()}async applyConfigToNewElement(element){const elementsToUpdate=[];if(element.getAttribute(editing_sdk_impl_DATA_TEMPLATE_ID)!=null)elementsToUpdate.push(element);elementsToUpdate.push(...element.querySelectorAll(`[${editing_sdk_impl_DATA_TEMPLATE_ID}]`));await Promise.all(elementsToUpdate.map((async element=>{if(!(element instanceof HTMLElement))return;const templateId=element.getAttribute(editing_sdk_impl_DATA_TEMPLATE_ID);if(templateId==null)return;const entityConfig=this.config.get(templateId);if(entityConfig==null)return;await this.applyAttributesToElement(element,entityConfig)})))}handleSelection(xPosPct,yPosPct){const{x,y}=mapPosPctToPx(xPosPct,yPosPct);const element=x>0&&y>0?this.selection.getSelectableFromPoint(x,y):undefined;if(!element){this.selection.clearSelection();return}!this.selection.isSelected(element)&&this.selection.selectElement(element);return element}handleSelectionHover(xPosPct,yPosPct){const{x,y}=mapPosPctToPx(xPosPct,yPosPct);const element=x>0&&y>0?this.selection.getSelectableFromPoint(x,y):undefined;element?this.selection.setHoveredElement(element):this.selection.clearHover()}handleInteractionClick(xPosPct,yPosPct){const{x,y}=mapPosPctToPx(xPosPct,yPosPct);const[target]=document.elementsFromPoint(x,y);if(!(target instanceof HTMLElement))return;const mouseEventInit={clientX:x,clientY:y,bubbles:true,cancelable:true,view:window,button:0};const pointerEventInit={...mouseEventInit,pointerId:1,pointerType:"mouse",isPrimary:true};if(window.PointerEvent!=null)target.dispatchEvent(new PointerEvent("pointerdown",pointerEventInit));target.dispatchEvent(new MouseEvent("mousedown",mouseEventInit));if(window.PointerEvent!=null)target.dispatchEvent(new PointerEvent("pointerup",pointerEventInit));target.dispatchEvent(new MouseEvent("mouseup",mouseEventInit));target.dispatchEvent(new MouseEvent("click",mouseEventInit));target.focus()}sendHoverElementChanged(rect){this.errorService.info(`Sending hover element changed: ${rect}`);return this.commsClient?.hoverElementChanged(new HoverElementChangedRequest({rect}))}sendSelectionChangeCompleted(selection){this.errorService.info(`Sending selection change completed: ${selection}`);return this.commsClient?.selectionChanged(new SelectionChangeRequest({selection}))}sendTextChanged(entityId,textContent){this.errorService.info(`Sending text changed: ${entityId}, ${textContent}`);try{return this.commsClient?.textContentChanged(new TextContentChangedRequest({entityId,textContent}))}catch(e){this.errorService.error(new Error(`Failed to update text`,{cause:e}))}}sendScrollStarted(){this.errorService.info("Sending scroll started");return this.commsClient?.scrolled(new ScrollEventRequest({status:ScrollEventStatus.STARTED}))}sendScrollCompleted(){this.errorService.info("Sending scroll completed");return this.commsClient?.scrolled(new ScrollEventRequest({status:ScrollEventStatus.COMPLETED}))}sendTextFocusChanged(entityId,focused,textDimensions){this.errorService.info(`Sending text focus changed: ${entityId}, ${focused} ${textDimensions}`);try{return this.commsClient?.textFocusChanged(new TextFocusChangedRequest({entityId,focused,textDimensions}))}catch(e){this.errorService.error(new Error(`Failed to update text focus`,{cause:e}))}}sendShowContextMenu(entityId){this.errorService.info(`Sending show context menu: ${entityId}`);return this.commsClient?.showContextMenu?.(new ShowContextMenuRequest({entityId}))}sendClearEditMode(){this.errorService.info(`Sending clear edit mode request`);return this.commsClient?.clearEditMode?.(new ClearEditModeRequest)}constructor(comms,createEditingClientComms,errorService){this.comms=comms;this.createEditingClientComms=createEditingClientComms;this.errorService=errorService;this.enableClampingToPreventWordBreaks=true;this.config=new Map;this.debouncedWindowResize=debounce((()=>{if(!this.flags.enableClampingToPreventWordBreaks)return;const elements=[...document.querySelectorAll(`[${editing_sdk_impl_DATA_TEMPLATE_ID}][data-canva-font-size]`)];elements.forEach((e=>{clampFontSize(e);TextEditor.getEditorIfActive(e)?.syncConfig()}))}));this.setupCommsClient();this.selection=new selection_Selection(this);this.dragAndDrop=new DragAndDrop(this);this.scrollObserver=new ScrollObserver({onScrollStarted:()=>{this.selection.onScrollStarted();this.sendScrollStarted()},onScrollCompleted:()=>{this.selection.onScrollCompleted();this.sendScrollCompleted()}});this.setupDOMObserver()}}function backgroundChanged(prev,next){return prev?.background!==next.background||prev?.backgroundDimensions?.width!==next.backgroundDimensions?.width||prev?.backgroundDimensions?.height!==next.backgroundDimensions?.height}function areFontVariantsEqual(a,b){const left=a??[];const right=b??[];return left.length===right.length&&left.every(((variant,index)=>{const other=right[index];return other!=null&&variant.src===other.src&&variant.weight===other.weight&&variant.style===other.style&&variant.loadMode===other.loadMode}))}function fillChanged(prev,next){return backgroundChanged(prev,next)||!imageSrcsEqual(prev?.backgroundImageSrcs,next.backgroundImageSrcs)||prev?.imageSrc!==next.imageSrc||!imageSrcsEqual(prev?.imageSrcs,next.imageSrcs)||prev?.altText!==next.altText}function hasFill(config){return config.background!=null||config.imageSrc!=null||config.backgroundImageSrcs.length>0||config.imageSrcs.length>0||config.altText!=null}function mapPosPctToPx(xPosPct,yPosPct){const x=window.innerWidth*xPosPct;const y=window.innerHeight*yPosPct;return{x,y}}function imageSrcsEqual(a,b){if(a===b)return true;const normalizedA=a??[];const normalizedB=b??[];if(normalizedA.length!==normalizedB.length)return false;return normalizedA.every(((imageSrc,index)=>imageSrc.src===normalizedB[index]?.src&&imageSrc.width===normalizedB[index]?.width))}const TARGET_ORIGIN="*";customElements.get("canva-text-editor")??customElements.define("canva-text-editor",TextEditor);customElements.get("canva-interaction-block-overlay")??customElements.define("canva-interaction-block-overlay",InteractionBlockOverlay);customElements.get("canva-element-overlay")??customElements.define("canva-element-overlay",ElementOverlay);function getErrorService(){const telemetry=window.telemetrySdk?.errorService;return telemetry?.createChild("Editing")??new ConsoleErrorService("Editing")}const errorService=getErrorService();connectToParent(errorService,TARGET_ORIGIN,window,EDITING_CLIENT_ID).then((result=>new Promise(((resolve,reject)=>{if(!result.ok){reject(new Error("Failed to connect to parent"));return}addAdoptedStyleSheets();resolve(new EditingSdk(result.value,((comms,handler)=>{setupSandboxedEditingRequestHandlers(comms,handler);return new EditingSdkClient(comms)}),errorService))}))));connectToParent(errorService,TARGET_ORIGIN,window,EDITING2_SDK_CLIENT_ID).then((result=>new Promise(((resolve,reject)=>{if(!result.ok){reject(new Error("Failed to connect to parent"));return}const sandboxCommsService=new CodeletSandboxCommsRpcService(result.value);const editing2SdkClient=createEditing2SdkServiceRpcClient(sandboxCommsService);const editing2Sdk=new Editing2Sdk(editing2SdkClient,errorService);registerEditing2SdkIframeServiceHost(sandboxCommsService,editing2Sdk);editing2Sdk.init();resolve(editing2Sdk)}))))})();