diff --git a/package-lock.json b/package-lock.json index bcb55ae..19ce83c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8,12 +8,44 @@ "name": "re-commander", "version": "1.0.0", "dependencies": { + "@theatre/core": "^0.7.2", + "@theatre/studio": "^0.7.2", "dotenv": "^17.4.2", "express": "^4.18.2", "golden-layout": "^2.6.0", "ws": "^8.14.2" } }, + "node_modules/@theatre/core": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/@theatre/core/-/core-0.7.2.tgz", + "integrity": "sha512-IDQa/6WY7mIJAtsSd4EgNcM0IUZkl+FrqZ8DdYiCVTFap9ARDNmrngJOeFjJOsnnaHlc5GdEB/jj7fsjbIrAzQ==", + "license": "Apache-2.0", + "dependencies": { + "@theatre/dataverse": "0.7.2" + } + }, + "node_modules/@theatre/dataverse": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/@theatre/dataverse/-/dataverse-0.7.2.tgz", + "integrity": "sha512-YyfoyX7EyhFUY2OM5fsM0LPrs1SdgLwpiTMkkvTIoZLdOwvQhstjYq4Yz/8ZncJlRoTWvakfmgvCaBN+QuBYxg==", + "license": "Apache-2.0", + "dependencies": { + "lodash-es": "^4.17.21" + } + }, + "node_modules/@theatre/studio": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/@theatre/studio/-/studio-0.7.2.tgz", + "integrity": "sha512-p6LTKzJWVlcHkpGzIlNHh9AkGbB3E+0q9Pjxv+OJoTDe1IK+CMKW695Wp+1//lB4vfC9qShe4z/p+Zaj1q8KtA==", + "license": "AGPL-3.0-only", + "dependencies": { + "@theatre/dataverse": "0.7.2" + }, + "peerDependencies": { + "@theatre/core": "*" + } + }, "node_modules/accepts": { "version": "1.3.8", "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", @@ -461,6 +493,12 @@ "node": ">= 0.10" } }, + "node_modules/lodash-es": { + "version": "4.18.1", + "resolved": "https://registry.npmjs.org/lodash-es/-/lodash-es-4.18.1.tgz", + "integrity": "sha512-J8xewKD/Gk22OZbhpOVSwcs60zhd95ESDwezOFuA3/099925PdHJ7OFHNTGtajL3AlZkykD32HykiMo+BIBI8A==", + "license": "MIT" + }, "node_modules/math-intrinsics": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", diff --git a/package.json b/package.json index caf37ba..338f395 100644 --- a/package.json +++ b/package.json @@ -7,6 +7,8 @@ "start": "node server.js" }, "dependencies": { + "@theatre/core": "^0.7.2", + "@theatre/studio": "^0.7.2", "dotenv": "^17.4.2", "express": "^4.18.2", "golden-layout": "^2.6.0", diff --git a/public/animator-simple.html b/public/animator-simple.html new file mode 100644 index 0000000..de01512 --- /dev/null +++ b/public/animator-simple.html @@ -0,0 +1,694 @@ + + +
+ + +".concat(e2.message, "\n\nSee **console** for details.") + ); + }); + window.addEventListener("unhandledrejection", (e2) => { + notify.error( + "An error occurred", + "
".concat(e2.reason, "\n\nSee **console** for details.") + ); + }); +} + +// core/src/sequences/playbackControllers/AudioPlaybackController.ts +var AudioPlaybackController = class { + constructor(_decodedBuffer, _audioContext, _nodeDestination) { + this._decodedBuffer = _decodedBuffer; + this._audioContext = _audioContext; + this._nodeDestination = _nodeDestination; + __publicField(this, "_mainGain"); + __publicField(this, "_state", new import_dataverse8.Atom({ + position: 0, + playing: false + })); + __publicField(this, "statePointer"); + __publicField(this, "_stopPlayCallback", noop_default); + this.statePointer = this._state.pointer; + this._mainGain = this._audioContext.createGain(); + this._mainGain.connect(this._nodeDestination); + } + playDynamicRange(rangeD, ticker) { + const deferred = defer(); + if (this._playing) + this.pause(); + this._playing = true; + let stop = void 0; + const play = () => { + stop == null ? void 0 : stop(); + stop = this._loopInRange(rangeD.getValue(), ticker).stop; + }; + const untapFromRangeD = rangeD.onStale(play); + play(); + this._stopPlayCallback = () => { + stop == null ? void 0 : stop(); + untapFromRangeD(); + deferred.resolve(false); + }; + return deferred.promise; + } + _loopInRange(range, ticker) { + const rate = 1; + let startPos = this.getCurrentPosition(); + const iterationLength = range[1] - range[0]; + if (startPos < range[0] || startPos > range[1]) { + this._updatePositionInState(range[0]); + } else if (startPos === range[1]) { + this._updatePositionInState(range[0]); + } + startPos = this.getCurrentPosition(); + const currentSource = this._audioContext.createBufferSource(); + currentSource.buffer = this._decodedBuffer; + currentSource.connect(this._mainGain); + currentSource.playbackRate.value = rate; + currentSource.loop = true; + currentSource.loopStart = range[0]; + currentSource.loopEnd = range[1]; + const initialTickerTime = ticker.time; + let initialElapsedPos = startPos - range[0]; + currentSource.start(0, startPos); + const tick = (currentTickerTime) => { + const elapsedTickerTime = Math.max( + currentTickerTime - initialTickerTime, + 0 + ); + const elapsedTickerTimeInSeconds = elapsedTickerTime / 1e3; + const elapsedPos = elapsedTickerTimeInSeconds * rate + initialElapsedPos; + let currentIterationPos = elapsedPos / iterationLength % 1 * iterationLength; + this._updatePositionInState(currentIterationPos + range[0]); + requestNextTick(); + }; + const requestNextTick = () => ticker.onNextTick(tick); + ticker.onThisOrNextTick(tick); + const stop = () => { + currentSource.stop(); + currentSource.disconnect(); + ticker.offThisOrNextTick(tick); + ticker.offNextTick(tick); + }; + return { stop }; + } + get _playing() { + return this._state.get().playing; + } + set _playing(playing) { + this._state.setByPointer((p2) => p2.playing, playing); + } + destroy() { + } + pause() { + this._stopPlayCallback(); + this._playing = false; + this._stopPlayCallback = noop_default; + } + gotoPosition(time) { + this._updatePositionInState(time); + } + _updatePositionInState(time) { + this._state.reduce((s2) => __spreadProps(__spreadValues({}, s2), { position: time })); + } + getCurrentPosition() { + return this._state.get().position; + } + play(iterationCount, range, rate, direction, ticker) { + if (this._playing) { + this.pause(); + } + this._playing = true; + let startPos = this.getCurrentPosition(); + const iterationLength = range[1] - range[0]; + if (direction !== "normal") { + throw new InvalidArgumentError( + 'Audio-controlled sequences can only be played in the "normal" direction. ' + "'".concat(direction, "' given.") + ); + } + if (startPos < range[0] || startPos > range[1]) { + this._updatePositionInState(range[0]); + } else if (startPos === range[1]) { + this._updatePositionInState(range[0]); + } + startPos = this.getCurrentPosition(); + const deferred = defer(); + const currentSource = this._audioContext.createBufferSource(); + currentSource.buffer = this._decodedBuffer; + currentSource.connect(this._mainGain); + currentSource.playbackRate.value = rate; + if (iterationCount > 1e3) { + notify.warning( + "Can't play sequences with audio more than 1000 times", + "The sequence will still play, but only 1000 times. The `iterationCount: ".concat(iterationCount, "` provided to `sequence.play()`\nis too high for a sequence with audio.\n\nTo fix this, either set `iterationCount` to a lower value, or remove the audio from the sequence."), + [ + { + url: "https://www.theatrejs.com/docs/latest/manual/audio", + title: "Using Audio" + }, + { + url: "https://www.theatrejs.com/docs/latest/api/core#sequence.attachaudio", + title: "Audio API" + } + ] + ); + iterationCount = 1e3; + } + if (iterationCount > 1) { + currentSource.loop = true; + currentSource.loopStart = range[0]; + currentSource.loopEnd = range[1]; + } + const initialTickerTime = ticker.time; + let initialElapsedPos = startPos - range[0]; + const totalPlaybackLength = iterationLength * iterationCount; + currentSource.start(0, startPos, totalPlaybackLength - initialElapsedPos); + const tick = (currentTickerTime) => { + const elapsedTickerTime = Math.max( + currentTickerTime - initialTickerTime, + 0 + ); + const elapsedTickerTimeInSeconds = elapsedTickerTime / 1e3; + const elapsedPos = Math.min( + elapsedTickerTimeInSeconds * rate + initialElapsedPos, + totalPlaybackLength + ); + if (elapsedPos !== totalPlaybackLength) { + let currentIterationPos = elapsedPos / iterationLength % 1 * iterationLength; + this._updatePositionInState(currentIterationPos + range[0]); + requestNextTick(); + } else { + this._updatePositionInState(range[1]); + this._playing = false; + cleanup(); + deferred.resolve(true); + } + }; + const cleanup = () => { + currentSource.stop(); + currentSource.disconnect(); + }; + this._stopPlayCallback = () => { + cleanup(); + ticker.offThisOrNextTick(tick); + ticker.offNextTick(tick); + if (this._playing) + deferred.resolve(false); + }; + const requestNextTick = () => ticker.onNextTick(tick); + ticker.onThisOrNextTick(tick); + return deferred.promise; + } +}; + +// core/src/rafDrivers.ts +var import_dataverse9 = require("@theatre/dataverse"); +var lastDriverId = 0; +function createRafDriver(conf) { + var _a; + const tick = (time) => { + ticker.tick(time); + }; + const ticker = new import_dataverse9.Ticker({ + onActive() { + var _a2; + (_a2 = conf == null ? void 0 : conf.start) == null ? void 0 : _a2.call(conf); + }, + onDormant() { + var _a2; + (_a2 = conf == null ? void 0 : conf.stop) == null ? void 0 : _a2.call(conf); + } + }); + const driverPublicApi = { + tick, + id: lastDriverId++, + name: (_a = conf == null ? void 0 : conf.name) != null ? _a : "CustomRafDriver-".concat(lastDriverId), + type: "Theatre_RafDriver_PublicAPI" + }; + const driverPrivateApi = { + type: "Theatre_RafDriver_PrivateAPI", + publicApi: driverPublicApi, + ticker, + start: conf == null ? void 0 : conf.start, + stop: conf == null ? void 0 : conf.stop + }; + setPrivateAPI(driverPublicApi, driverPrivateApi); + return driverPublicApi; +} + +// core/src/coreTicker.ts +function createBasicRafDriver() { + let rafId = null; + const start = () => { + if (typeof window !== "undefined") { + const onAnimationFrame = (t2) => { + driver.tick(t2); + rafId = window.requestAnimationFrame(onAnimationFrame); + }; + rafId = window.requestAnimationFrame(onAnimationFrame); + } else { + driver.tick(0); + setTimeout(() => driver.tick(1), 0); + } + }; + const stop = () => { + if (typeof window !== "undefined") { + if (rafId !== null) { + window.cancelAnimationFrame(rafId); + } + } else { + } + }; + const driver = createRafDriver({ name: "DefaultCoreRafDriver", start, stop }); + return driver; +} +var coreRafDriver; +function getCoreRafDriver() { + if (!coreRafDriver) { + setCoreRafDriver(createBasicRafDriver()); + } + return coreRafDriver; +} +function getCoreTicker() { + return getCoreRafDriver().ticker; +} +function setCoreRafDriver(driver) { + if (coreRafDriver) { + throw new Error("`setCoreRafDriver()` is already called."); + } + const driverPrivateApi = privateAPI(driver); + coreRafDriver = driverPrivateApi; +} + +// core/src/sequences/TheatreSequence.ts +var TheatreSequence = class { + get type() { + return "Theatre_Sequence_PublicAPI"; + } + /** + * @internal + */ + constructor(sheet) { + setPrivateAPI(this, sheet); + } + play(conf) { + const priv = privateAPI(this); + if (priv._project.isReady()) { + const ticker = (conf == null ? void 0 : conf.rafDriver) ? privateAPI(conf.rafDriver).ticker : getCoreTicker(); + return priv.play(conf != null ? conf : {}, ticker); + } else { + if (process.env.NODE_ENV !== "production") { + notify.warning( + "Sequence can't be played", + "You seem to have called `sequence.play()` before the project has finished loading.\n\nThis would **not** a problem in production when using `@theatre/core`, since Theatre.js loads instantly in core mode. However, when using `@theatre/studio`, it takes a few milliseconds for it to load your project's state, before which your sequences cannot start playing.\n\nTo fix this, simply defer calling `sequence.play()` until after the project is loaded, like this:\n\n```\nproject.ready.then(() => {\n sequence.play()\n})\n```", + [ + { + url: "https://www.theatrejs.com/docs/0.5/api/core#project.ready", + title: "Project.ready" + } + ] + ); + } + const d2 = defer(); + d2.resolve(true); + return d2.promise; + } + } + pause() { + privateAPI(this).pause(); + } + get position() { + return privateAPI(this).position; + } + set position(position) { + privateAPI(this).position = position; + } + __experimental_getKeyframes(prop) { + return privateAPI(this).getKeyframesOfSimpleProp(prop); + } + async attachAudio(args) { + const { audioContext, destinationNode, decodedBuffer, gainNode } = await resolveAudioBuffer(args); + const playbackController = new AudioPlaybackController( + decodedBuffer, + audioContext, + gainNode + ); + privateAPI(this).replacePlaybackController(playbackController); + return { audioContext, destinationNode, decodedBuffer, gainNode }; + } + get pointer() { + return privateAPI(this).pointer; + } +}; +async function resolveAudioBuffer(args) { + function getAudioContext() { + if (args.audioContext) + return Promise.resolve(args.audioContext); + const ctx = new AudioContext(); + if (ctx.state === "running") + return Promise.resolve(ctx); + if (typeof window === "undefined") { + return Promise.resolve(ctx); + } + return new Promise((resolve) => { + const listener = () => { + ctx.resume().catch((err) => { + console.error(err); + }); + }; + const eventsToHookInto = [ + "mousedown", + "keydown", + "touchstart" + ]; + const eventListenerOpts = { capture: true, passive: false }; + eventsToHookInto.forEach((eventName) => { + window.addEventListener(eventName, listener, eventListenerOpts); + }); + ctx.addEventListener("statechange", () => { + if (ctx.state === "running") { + eventsToHookInto.forEach((eventName) => { + window.removeEventListener(eventName, listener, eventListenerOpts); + }); + resolve(ctx); + } + }); + }); + } + async function getAudioBuffer() { + if (args.source instanceof AudioBuffer) { + return args.source; + } + const decodedBufferDeferred = defer(); + if (typeof args.source !== "string") { + throw new Error( + "Error validating arguments to sequence.attachAudio(). args.source must either be a string or an instance of AudioBuffer." + ); + } + let fetchResponse; + try { + fetchResponse = await fetch(args.source); + } catch (e2) { + console.error(e2); + throw new Error( + "Could not fetch '".concat(args.source, "'. Network error logged above.") + ); + } + let arrayBuffer; + try { + arrayBuffer = await fetchResponse.arrayBuffer(); + } catch (e2) { + console.error(e2); + throw new Error("Could not read '".concat(args.source, "' as an arrayBuffer.")); + } + const audioContext2 = await audioContextPromise; + audioContext2.decodeAudioData( + arrayBuffer, + decodedBufferDeferred.resolve, + decodedBufferDeferred.reject + ); + let decodedBuffer2; + try { + decodedBuffer2 = await decodedBufferDeferred.promise; + } catch (e2) { + console.error(e2); + throw new Error("Could not decode ".concat(args.source, " as an audio file.")); + } + return decodedBuffer2; + } + const audioContextPromise = getAudioContext(); + const audioBufferPromise = getAudioBuffer(); + const [audioContext, decodedBuffer] = await Promise.all([ + audioContextPromise, + audioBufferPromise + ]); + const destinationNode = args.destinationNode || audioContext.destination; + const gainNode = audioContext.createGain(); + gainNode.connect(destinationNode); + return { + audioContext, + decodedBuffer, + gainNode, + destinationNode + }; +} + +// shared/src/instanceTypes.ts +var isProject = typeAsserter("Theatre_Project"); +var isSheet = typeAsserter("Theatre_Sheet"); +var isSheetTemplate = typeAsserter( + "Theatre_SheetTemplate" +); +var isSheetObject = typeAsserter("Theatre_SheetObject"); +var isSequence = typeAsserter("Theatre_Sequence"); +var isSheetObjectTemplate = typeAsserter( + "Theatre_SheetObjectTemplate" +); +var isProjectPublicAPI = typeAsserter( + "Theatre_Project_PublicAPI" +); +var isSheetPublicAPI = typeAsserter("Theatre_Sheet_PublicAPI"); +var isSheetObjectPublicAPI = typeAsserter( + "Theatre_SheetObject_PublicAPI" +); +function typeAsserter(t2) { + return (v2) => typeof v2 === "object" && !!v2 && v2.type === t2; +} + +// core/src/sequences/Sequence.ts +var possibleDirections = [ + "normal", + "reverse", + "alternate", + "alternateReverse" +]; +var Sequence = class { + constructor(_project, _sheet, _lengthD, _subUnitsPerUnitD, playbackController) { + this._project = _project; + this._sheet = _sheet; + this._lengthD = _lengthD; + this._subUnitsPerUnitD = _subUnitsPerUnitD; + __publicField(this, "address"); + __publicField(this, "publicApi"); + __publicField(this, "_playbackControllerBox"); + __publicField(this, "_prismOfStatePointer"); + __publicField(this, "_positionD"); + __publicField(this, "_positionFormatterD"); + __publicField(this, "_playableRangeD"); + __publicField(this, "pointer", (0, import_dataverse12.pointer)({ root: this, path: [] })); + __publicField(this, "$$isPointerToPrismProvider", true); + __publicField(this, "_logger"); + __publicField(this, "closestGridPosition", (posInUnitSpace) => { + const subUnitsPerUnit = this.subUnitsPerUnit; + const gridLength = 1 / subUnitsPerUnit; + return parseFloat( + (Math.round(posInUnitSpace / gridLength) * gridLength).toFixed(3) + ); + }); + this._logger = _project._logger.named("Sheet", _sheet.address.sheetId).named("Instance", _sheet.address.sheetInstanceId); + this.address = __spreadProps(__spreadValues({}, this._sheet.address), { sequenceName: "default" }); + this.publicApi = new TheatreSequence(this); + this._playbackControllerBox = new import_dataverse11.Atom( + playbackController != null ? playbackController : new DefaultPlaybackController() + ); + this._prismOfStatePointer = (0, import_dataverse13.prism)( + () => this._playbackControllerBox.prism.getValue().statePointer + ); + this._positionD = (0, import_dataverse13.prism)(() => { + const statePointer = this._prismOfStatePointer.getValue(); + return (0, import_dataverse13.val)(statePointer.position); + }); + this._positionFormatterD = (0, import_dataverse13.prism)(() => { + const subUnitsPerUnit = (0, import_dataverse13.val)(this._subUnitsPerUnitD); + return new TimeBasedPositionFormatter(subUnitsPerUnit); + }); + } + get type() { + return "Theatre_Sequence"; + } + pointerToPrism(pointer3) { + const { path } = (0, import_dataverse10.getPointerParts)(pointer3); + if (path.length === 0) { + return (0, import_dataverse13.prism)(() => ({ + length: (0, import_dataverse13.val)(this.pointer.length), + playing: (0, import_dataverse13.val)(this.pointer.playing), + position: (0, import_dataverse13.val)(this.pointer.position), + subUnitsPerUnit: (0, import_dataverse13.val)(this.pointer.subUnitsPerUnit) + })); + } + if (path.length > 1) { + return (0, import_dataverse13.prism)(() => void 0); + } + const [prop] = path; + if (prop === "length") { + return this._lengthD; + } else if (prop === "subUnitsPerUnit") { + return this._subUnitsPerUnitD; + } else if (prop === "position") { + return this._positionD; + } else if (prop === "playing") { + return (0, import_dataverse13.prism)(() => { + return (0, import_dataverse13.val)(this._prismOfStatePointer.getValue().playing); + }); + } else { + return (0, import_dataverse13.prism)(() => void 0); + } + } + /** + * Takes a pointer to a property of a SheetObject and returns the keyframes of that property. + * + * Theoretically, this method can be called from inside a prism so it can be reactive. + */ + getKeyframesOfSimpleProp(prop) { + const { path, root: root2 } = (0, import_dataverse10.getPointerParts)(prop); + if (!isSheetObject(root2)) { + throw new InvalidArgumentError( + "Argument prop must be a pointer to a SheetObject property" + ); + } + const trackP = (0, import_dataverse13.val)( + this._project.pointers.historic.sheetsById[this._sheet.address.sheetId].sequence.tracksByObject[root2.address.objectKey] + ); + if (!trackP) { + return []; + } + const { trackData, trackIdByPropPath } = trackP; + const objectAddress = encodePathToProp(path); + const id = trackIdByPropPath[objectAddress]; + if (!id) { + return []; + } + const track = trackData[id]; + if (!track) { + return []; + } + return track.keyframes; + } + get positionFormatter() { + return this._positionFormatterD.getValue(); + } + get prismOfStatePointer() { + return this._prismOfStatePointer; + } + get length() { + return this._lengthD.getValue(); + } + get positionPrism() { + return this._positionD; + } + get position() { + return this._playbackControllerBox.get().getCurrentPosition(); + } + get subUnitsPerUnit() { + return this._subUnitsPerUnitD.getValue(); + } + get positionSnappedToGrid() { + return this.closestGridPosition(this.position); + } + set position(requestedPosition) { + let position = requestedPosition; + this.pause(); + if (process.env.NODE_ENV !== "production") { + if (typeof position !== "number") { + console.error( + "value t in sequence.position = t must be a number. ".concat(typeof position, " given") + ); + position = 0; + } + if (position < 0) { + console.error( + "sequence.position must be a positive number. ".concat(position, " given") + ); + position = 0; + } + } + if (position > this.length) { + position = this.length; + } + const dur = this.length; + this._playbackControllerBox.get().gotoPosition(position > dur ? dur : position); + } + getDurationCold() { + return this._lengthD.getValue(); + } + get playing() { + return (0, import_dataverse13.val)(this._playbackControllerBox.get().statePointer.playing); + } + _makeRangeFromSequenceTemplate() { + return (0, import_dataverse13.prism)(() => { + return [0, (0, import_dataverse13.val)(this._lengthD)]; + }); + } + /** + * Controls the playback within a range. Repeats infinitely unless stopped. + * + * @remarks + * One use case for this is to play the playback within the focus range. + * + * @param rangeD - The prism that contains the range that will be used for the playback + * + * @returns a promise that gets rejected if the playback stopped for whatever reason + * + */ + playDynamicRange(rangeD, ticker) { + return this._playbackControllerBox.get().playDynamicRange(rangeD, ticker); + } + async play(conf, ticker) { + const sequenceDuration = this.length; + const range = conf && conf.range ? conf.range : [0, sequenceDuration]; + if (process.env.NODE_ENV !== "production") { + if (typeof range[0] !== "number" || range[0] < 0) { + throw new InvalidArgumentError( + "Argument conf.range[0] in sequence.play(conf) must be a positive number. ".concat(JSON.stringify( + range[0] + ), " given.") + ); + } + if (range[0] >= sequenceDuration) { + throw new InvalidArgumentError( + "Argument conf.range[0] in sequence.play(conf) cannot be longer than the duration of the sequence, which is ".concat(sequenceDuration, "s. ").concat(JSON.stringify( + range[0] + ), " given.") + ); + } + if (typeof range[1] !== "number" || range[1] <= 0) { + throw new InvalidArgumentError( + "Argument conf.range[1] in sequence.play(conf) must be a number larger than zero. ".concat(JSON.stringify( + range[1] + ), " given.") + ); + } + if (range[1] > sequenceDuration) { + notify.warning( + "Couldn't play sequence in given range", + "Your animation will still play until the end of the sequence, however the argument `conf.range[1]` given in `sequence.play(conf)` (".concat(JSON.stringify( + range[1] + ), "s) is longer than the duration of the sequence (").concat(sequenceDuration, "s).\n\nTo fix this, either set `conf.range[1]` to be less the duration of the sequence, or adjust the sequence duration in the UI."), + [ + { + url: "https://www.theatrejs.com/docs/latest/manual/sequences", + title: "Sequences" + }, + { + url: "https://www.theatrejs.com/docs/latest/manual/sequences", + title: "Playback API" + } + ] + ); + range[1] = sequenceDuration; + } + if (range[1] <= range[0]) { + throw new InvalidArgumentError( + "Argument conf.range[1] in sequence.play(conf) must be larger than conf.range[0]. ".concat(JSON.stringify( + range + ), " given.") + ); + } + } + const iterationCount = conf && typeof conf.iterationCount === "number" ? conf.iterationCount : 1; + if (process.env.NODE_ENV !== "production") { + if (!(Number.isInteger(iterationCount) && iterationCount > 0) && iterationCount !== Infinity) { + throw new InvalidArgumentError( + "Argument conf.iterationCount in sequence.play(conf) must be an integer larger than 0. ".concat(JSON.stringify( + iterationCount + ), " given.") + ); + } + } + const rate = conf && typeof conf.rate !== "undefined" ? conf.rate : 1; + if (process.env.NODE_ENV !== "production") { + if (typeof rate !== "number" || rate === 0) { + throw new InvalidArgumentError( + "Argument conf.rate in sequence.play(conf) must be a number larger than 0. ".concat(JSON.stringify( + rate + ), " given.") + ); + } + if (rate < 0) { + throw new InvalidArgumentError( + "Argument conf.rate in sequence.play(conf) must be a number larger than 0. ".concat(JSON.stringify( + rate + ), " given. If you want the animation to play backwards, try setting conf.direction to 'reverse' or 'alternateReverse'.") + ); + } + } + const direction = conf && conf.direction ? conf.direction : "normal"; + if (process.env.NODE_ENV !== "production") { + if (possibleDirections.indexOf(direction) === -1) { + throw new InvalidArgumentError( + "Argument conf.direction in sequence.play(conf) must be one of ".concat(JSON.stringify( + possibleDirections + ), ". ").concat(JSON.stringify(direction), " given. ").concat(didYouMean( + direction, + possibleDirections + )) + ); + } + } + return await this._play( + iterationCount, + [range[0], range[1]], + rate, + direction, + ticker + ); + } + _play(iterationCount, range, rate, direction, ticker) { + return this._playbackControllerBox.get().play(iterationCount, range, rate, direction, ticker); + } + pause() { + this._playbackControllerBox.get().pause(); + } + replacePlaybackController(playbackController) { + this.pause(); + const oldController = this._playbackControllerBox.get(); + this._playbackControllerBox.set(playbackController); + const time = oldController.getCurrentPosition(); + oldController.destroy(); + playbackController.gotoPosition(time); + } +}; +var TimeBasedPositionFormatter = class { + constructor(_fps) { + this._fps = _fps; + } + formatSubUnitForGrid(posInUnitSpace) { + const subSecondPos = posInUnitSpace % 1; + const frame = 1 / this._fps; + const frames = Math.round(subSecondPos / frame); + return frames + "f"; + } + formatFullUnitForGrid(posInUnitSpace) { + let p2 = posInUnitSpace; + let s2 = ""; + if (p2 >= hour) { + const hours = Math.floor(p2 / hour); + s2 += hours + "h"; + p2 = p2 % hour; + } + if (p2 >= minute) { + const minutes = Math.floor(p2 / minute); + s2 += minutes + "m"; + p2 = p2 % minute; + } + if (p2 >= second) { + const seconds = Math.floor(p2 / second); + s2 += seconds + "s"; + p2 = p2 % second; + } + const frame = 1 / this._fps; + if (p2 >= frame) { + const frames = Math.floor(p2 / frame); + s2 += frames + "f"; + p2 = p2 % frame; + } + return s2.length === 0 ? "0s" : s2; + } + formatForPlayhead(posInUnitSpace) { + let p2 = posInUnitSpace; + let s2 = ""; + if (p2 >= hour) { + const hours = Math.floor(p2 / hour); + s2 += padStart_default(hours.toString(), 2, "0") + "h"; + p2 = p2 % hour; + } + if (p2 >= minute) { + const minutes = Math.floor(p2 / minute); + s2 += padStart_default(minutes.toString(), 2, "0") + "m"; + p2 = p2 % minute; + } else if (s2.length > 0) { + s2 += "00m"; + } + if (p2 >= second) { + const seconds = Math.floor(p2 / second); + s2 += padStart_default(seconds.toString(), 2, "0") + "s"; + p2 = p2 % second; + } else { + s2 += "00s"; + } + const frameLength = 1 / this._fps; + if (p2 >= frameLength) { + const frames = Math.round(p2 / frameLength); + s2 += padStart_default(frames.toString(), 2, "0") + "f"; + p2 = p2 % frameLength; + } else if (p2 / frameLength > 0.98) { + const frames = 1; + s2 += padStart_default(frames.toString(), 2, "0") + "f"; + p2 = p2 % frameLength; + } else { + s2 += "00f"; + } + return s2.length === 0 ? "00s00f" : s2; + } + formatBasic(posInUnitSpace) { + return posInUnitSpace.toFixed(2) + "s"; + } +}; +var second = 1; +var minute = second * 60; +var hour = minute * 60; + +// core/src/propTypes/index.ts +var propTypes_exports = {}; +__export(propTypes_exports, { + boolean: () => boolean, + compound: () => compound, + file: () => file, + image: () => image, + number: () => number, + rgba: () => rgba, + string: () => string, + stringLiteral: () => stringLiteral +}); + +// shared/src/utils/ellipsify.ts +function ellipsify(str, maxLength) { + if (str.length <= maxLength) + return str; + return str.substr(0, maxLength - 3) + "..."; +} + +// shared/src/utils/userReadableTypeOfValue.ts +var userReadableTypeOfValue = (v2) => { + if (typeof v2 === "string") { + return 'string("'.concat(ellipsify(v2, 10), '")'); + } else if (typeof v2 === "number") { + return "number(".concat(ellipsify(String(v2), 10), ")"); + } else if (v2 === null) { + return "null"; + } else if (v2 === void 0) { + return "undefined"; + } else if (typeof v2 === "boolean") { + return String(v2); + } else if (Array.isArray(v2)) { + return "array"; + } else if (typeof v2 === "object") { + return "object"; + } else { + return "unknown"; + } +}; +var userReadableTypeOfValue_default = userReadableTypeOfValue; + +// shared/src/utils/color.ts +function rgba2hex(rgba2, { + /** Alpha is usually an optional value for most hex inputs, so if it's opaque, we can omit its value. */ + removeAlphaIfOpaque = false +} = {}) { + const alpha = (rgba2.a * 255 | 1 << 8).toString(16).slice(1); + const hex = (rgba2.r * 255 | 1 << 8).toString(16).slice(1) + (rgba2.g * 255 | 1 << 8).toString(16).slice(1) + (rgba2.b * 255 | 1 << 8).toString(16).slice(1) + (removeAlphaIfOpaque && alpha === "ff" ? "" : alpha); + return "#".concat(hex); +} +function decorateRgba(rgba2) { + return __spreadProps(__spreadValues({}, rgba2), { + toString() { + return rgba2hex(this, { removeAlphaIfOpaque: true }); + } + }); +} +function clampRgba(rgba2) { + return Object.fromEntries( + Object.entries(rgba2).map(([key, value]) => [key, clamp_default(value, 0, 1)]) + ); +} +function linearSrgbToSrgb(rgba2) { + function compress(x2) { + if (x2 >= 31308e-7) + return 1.055 * x2 ** (1 / 2.4) - 0.055; + else + return 12.92 * x2; + } + return clampRgba({ + r: compress(rgba2.r), + g: compress(rgba2.g), + b: compress(rgba2.b), + a: rgba2.a + }); +} +function srgbToLinearSrgb(rgba2) { + function expand(x2) { + if (x2 >= 0.04045) + return ((x2 + 0.055) / (1 + 0.055)) ** 2.4; + else + return x2 / 12.92; + } + return { + r: expand(rgba2.r), + g: expand(rgba2.g), + b: expand(rgba2.b), + a: rgba2.a + }; +} +function linearSrgbToOklab(rgba2) { + let l2 = 0.4122214708 * rgba2.r + 0.5363325363 * rgba2.g + 0.0514459929 * rgba2.b; + let m = 0.2119034982 * rgba2.r + 0.6806995451 * rgba2.g + 0.1073969566 * rgba2.b; + let s2 = 0.0883024619 * rgba2.r + 0.2817188376 * rgba2.g + 0.6299787005 * rgba2.b; + let l_ = Math.cbrt(l2); + let m_ = Math.cbrt(m); + let s_ = Math.cbrt(s2); + return { + L: 0.2104542553 * l_ + 0.793617785 * m_ - 0.0040720468 * s_, + a: 1.9779984951 * l_ - 2.428592205 * m_ + 0.4505937099 * s_, + b: 0.0259040371 * l_ + 0.7827717662 * m_ - 0.808675766 * s_, + alpha: rgba2.a + }; +} +function oklabToLinearSrgb(laba) { + let l_ = laba.L + 0.3963377774 * laba.a + 0.2158037573 * laba.b; + let m_ = laba.L - 0.1055613458 * laba.a - 0.0638541728 * laba.b; + let s_ = laba.L - 0.0894841775 * laba.a - 1.291485548 * laba.b; + let l2 = l_ * l_ * l_; + let m = m_ * m_ * m_; + let s2 = s_ * s_ * s_; + return { + r: 4.0767416621 * l2 - 3.3077115913 * m + 0.2309699292 * s2, + g: -1.2684380046 * l2 + 2.6097574011 * m - 0.3413193965 * s2, + b: -0.0041960863 * l2 - 0.7034186147 * m + 1.707614701 * s2, + a: laba.alpha + }; +} + +// core/src/propTypes/internals.ts +var propTypeSymbol = Symbol("TheatrePropType_Basic"); +function isLonghandPropType(t2) { + return typeof t2 === "object" && !!t2 && t2[propTypeSymbol] === "TheatrePropType"; +} +function toLonghandProp(p2) { + if (typeof p2 === "number") { + return number(p2); + } else if (typeof p2 === "boolean") { + return boolean(p2); + } else if (typeof p2 === "string") { + return string(p2); + } else if (typeof p2 === "object" && !!p2) { + if (isLonghandPropType(p2)) + return p2; + if (isPlainObject_default(p2)) { + return compound(p2); + } else { + throw new InvalidArgumentError( + "This value is not a valid prop type: ".concat(userReadableTypeOfValue_default(p2)) + ); + } + } else { + throw new InvalidArgumentError( + "This value is not a valid prop type: ".concat(userReadableTypeOfValue_default(p2)) + ); + } +} +function sanitizeCompoundProps(props) { + const sanitizedProps = {}; + if (process.env.NODE_ENV !== "production") { + if (typeof props !== "object" || !props) { + throw new InvalidArgumentError( + "t.compound() expects an object, like: {x: 10}. ".concat(userReadableTypeOfValue_default( + props + ), " given.") + ); + } + } + for (const key of Object.keys(props)) { + if (process.env.NODE_ENV !== "production") { + if (typeof key !== "string") { + throw new InvalidArgumentError( + "t.compound()'s keys must be all strings. ".concat(userReadableTypeOfValue_default( + key + ), " given.") + ); + } else if (key.length === 0 || !key.match(/^\w+$/)) { + throw new InvalidArgumentError( + "compound key ".concat(userReadableTypeOfValue_default( + key + ), " is invalid. The keys must be alphanumeric and start with a letter.") + ); + } else if (key.length > 64) { + throw new InvalidArgumentError( + "compound key ".concat(userReadableTypeOfValue_default(key), " is too long.") + ); + } + } + const val8 = props[key]; + if (isLonghandPropType(val8)) { + sanitizedProps[key] = val8; + } else { + sanitizedProps[key] = toLonghandProp(val8); + } + } + return sanitizedProps; +} + +// core/src/propTypes/index.ts +var validateCommonOpts = (fnCallSignature, opts) => { + if (process.env.NODE_ENV !== "production") { + if (opts === void 0) + return; + if (typeof opts !== "object" || opts === null) { + throw new Error( + "opts in ".concat(fnCallSignature, " must either be undefined or an object.") + ); + } + if (Object.prototype.hasOwnProperty.call(opts, "label")) { + const { label } = opts; + if (typeof label !== "string") { + throw new Error( + "opts.label in ".concat(fnCallSignature, " should be a string. ").concat(userReadableTypeOfValue_default( + label + ), " given.") + ); + } + if (label.trim().length !== label.length) { + throw new Error( + "opts.label in ".concat(fnCallSignature, ' should not start/end with whitespace. "').concat(label, '" given.') + ); + } + if (label.length === 0) { + throw new Error( + "opts.label in ".concat(fnCallSignature, " should not be an empty string. If you wish to have no label, remove opts.label from opts.") + ); + } + } + } +}; +var compound = (props, opts = {}) => { + validateCommonOpts("t.compound(props, opts)", opts); + const sanitizedProps = sanitizeCompoundProps(props); + const deserializationCache = /* @__PURE__ */ new WeakMap(); + const config = { + type: "compound", + props: sanitizedProps, + valueType: null, + [propTypeSymbol]: "TheatrePropType", + label: opts.label, + default: mapValues_default(sanitizedProps, (p2) => p2.default), + deserializeAndSanitize: (json) => { + if (typeof json !== "object" || !json) + return void 0; + if (deserializationCache.has(json)) { + return deserializationCache.get(json); + } + const deserialized = {}; + let atLeastOnePropWasDeserialized = false; + for (const [key, propConfig] of Object.entries(sanitizedProps)) { + if (Object.prototype.hasOwnProperty.call(json, key)) { + const deserializedSub = propConfig.deserializeAndSanitize( + json[key] + ); + if (deserializedSub != null) { + atLeastOnePropWasDeserialized = true; + deserialized[key] = deserializedSub; + } + } + } + deserializationCache.set(json, deserialized); + if (atLeastOnePropWasDeserialized) { + return deserialized; + } + } + }; + return config; +}; +var file = (defaultValue, opts = {}) => { + if (process.env.NODE_ENV !== "production") { + validateCommonOpts("t.file(defaultValue, opts)", opts); + } + const interpolate = (left, right, progression) => { + var _a; + const stringInterpolate = (_a = opts.interpolate) != null ? _a : leftInterpolate; + return { + type: "file", + id: stringInterpolate(left.id, right.id, progression) + }; + }; + return { + type: "file", + default: { type: "file", id: defaultValue }, + valueType: null, + [propTypeSymbol]: "TheatrePropType", + label: opts.label, + interpolate, + deserializeAndSanitize: _ensureFile + }; +}; +var _ensureFile = (val8) => { + if (!val8) + return void 0; + let valid = true; + if (typeof val8.id !== "string" && ![null, void 0].includes(val8.id)) { + valid = false; + } + if (val8.type !== "file") + valid = false; + if (!valid) + return void 0; + return val8; +}; +var image = (defaultValue, opts = {}) => { + if (process.env.NODE_ENV !== "production") { + validateCommonOpts("t.image(defaultValue, opts)", opts); + } + const interpolate = (left, right, progression) => { + var _a; + const stringInterpolate = (_a = opts.interpolate) != null ? _a : leftInterpolate; + return { + type: "image", + id: stringInterpolate(left.id, right.id, progression) + }; + }; + return { + type: "image", + default: { type: "image", id: defaultValue }, + valueType: null, + [propTypeSymbol]: "TheatrePropType", + label: opts.label, + interpolate, + deserializeAndSanitize: _ensureImage + }; +}; +var _ensureImage = (val8) => { + if (!val8) + return void 0; + let valid = true; + if (typeof val8.id !== "string" && ![null, void 0].includes(val8.id)) { + valid = false; + } + if (val8.type !== "image") + valid = false; + if (!valid) + return void 0; + return val8; +}; +var number = (defaultValue, opts = {}) => { + var _a; + if (process.env.NODE_ENV !== "production") { + validateCommonOpts("t.number(defaultValue, opts)", opts); + if (typeof defaultValue !== "number" || !isFinite(defaultValue)) { + throw new Error( + "Argument defaultValue in t.number(defaultValue) must be a number. ".concat(userReadableTypeOfValue_default( + defaultValue + ), " given.") + ); + } + if (typeof opts === "object" && opts !== null) { + if (Object.prototype.hasOwnProperty.call(opts, "range")) { + if (!Array.isArray(opts.range)) { + throw new Error( + "opts.range in t.number(defaultValue, opts) must be a tuple of two numbers. ".concat(userReadableTypeOfValue_default( + opts.range + ), " given.") + ); + } + if (opts.range.length !== 2) { + throw new Error( + "opts.range in t.number(defaultValue, opts) must have two elements. ".concat(opts.range.length, " given.") + ); + } + if (!opts.range.every((n2) => typeof n2 === "number" && !isNaN(n2))) { + throw new Error( + "opts.range in t.number(defaultValue, opts) must be a tuple of two numbers." + ); + } + if (opts.range[0] >= opts.range[1]) { + throw new Error( + "opts.range[0] in t.number(defaultValue, opts) must be smaller than opts.range[1]. Given: ".concat(JSON.stringify( + opts.range + )) + ); + } + } + if (Object.prototype.hasOwnProperty.call(opts, "nudgeMultiplier")) { + if (typeof opts.nudgeMultiplier !== "number" || !isFinite(opts.nudgeMultiplier)) { + throw new Error( + "opts.nudgeMultiplier in t.number(defaultValue, opts) must be a finite number. ".concat(userReadableTypeOfValue_default( + opts.nudgeMultiplier + ), " given.") + ); + } + } + if (Object.prototype.hasOwnProperty.call(opts, "nudgeFn")) { + if (typeof opts.nudgeFn !== "function") { + throw new Error( + "opts.nudgeFn in t.number(defaultValue, opts) must be a function. ".concat(userReadableTypeOfValue_default( + opts.nudgeFn + ), " given.") + ); + } + } + } + } + return __spreadProps(__spreadValues({ + type: "number", + valueType: 0, + default: defaultValue, + [propTypeSymbol]: "TheatrePropType" + }, opts ? opts : {}), { + label: opts.label, + nudgeFn: (_a = opts.nudgeFn) != null ? _a : defaultNumberNudgeFn, + nudgeMultiplier: typeof opts.nudgeMultiplier === "number" ? opts.nudgeMultiplier : void 0, + interpolate: _interpolateNumber, + deserializeAndSanitize: numberDeserializer(opts.range) + }); +}; +var numberDeserializer = (range) => range ? (json) => { + if (!(typeof json === "number" && isFinite(json))) + return void 0; + return clamp_default(json, range[0], range[1]); +} : _ensureNumber; +var _ensureNumber = (value) => typeof value === "number" && isFinite(value) ? value : void 0; +var _interpolateNumber = (left, right, progression) => { + return left + progression * (right - left); +}; +var rgba = (defaultValue = { r: 0, g: 0, b: 0, a: 1 }, opts = {}) => { + if (process.env.NODE_ENV !== "production") { + validateCommonOpts("t.rgba(defaultValue, opts)", opts); + let valid = true; + for (const p2 of ["r", "g", "b", "a"]) { + if (!Object.prototype.hasOwnProperty.call(defaultValue, p2) || typeof defaultValue[p2] !== "number") { + valid = false; + } + } + if (!valid) { + throw new Error( + "Argument defaultValue in t.rgba(defaultValue) must be of the shape { r: number; g: number, b: number, a: number; }." + ); + } + } + const sanitized = {}; + for (const component of ["r", "g", "b", "a"]) { + ; + sanitized[component] = Math.min( + Math.max(defaultValue[component], 0), + 1 + ); + } + return { + type: "rgba", + valueType: null, + default: decorateRgba(sanitized), + [propTypeSymbol]: "TheatrePropType", + label: opts.label, + interpolate: _interpolateRgba, + deserializeAndSanitize: _sanitizeRgba + }; +}; +var _sanitizeRgba = (val8) => { + if (!val8) + return void 0; + let valid = true; + for (const c2 of ["r", "g", "b", "a"]) { + if (!Object.prototype.hasOwnProperty.call(val8, c2) || typeof val8[c2] !== "number") { + valid = false; + } + } + if (!valid) + return void 0; + const sanitized = {}; + for (const c2 of ["r", "g", "b", "a"]) { + ; + sanitized[c2] = Math.min( + Math.max(val8[c2], 0), + 1 + ); + } + return decorateRgba(sanitized); +}; +var _interpolateRgba = (left, right, progression) => { + const leftLab = linearSrgbToOklab(srgbToLinearSrgb(left)); + const rightLab = linearSrgbToOklab(srgbToLinearSrgb(right)); + const interpolatedLab = { + L: (1 - progression) * leftLab.L + progression * rightLab.L, + a: (1 - progression) * leftLab.a + progression * rightLab.a, + b: (1 - progression) * leftLab.b + progression * rightLab.b, + alpha: (1 - progression) * leftLab.alpha + progression * rightLab.alpha + }; + const interpolatedRgba = linearSrgbToSrgb(oklabToLinearSrgb(interpolatedLab)); + return decorateRgba(interpolatedRgba); +}; +var boolean = (defaultValue, opts = {}) => { + var _a; + if (process.env.NODE_ENV !== "production") { + validateCommonOpts("t.boolean(defaultValue, opts)", opts); + if (typeof defaultValue !== "boolean") { + throw new Error( + "defaultValue in t.boolean(defaultValue) must be a boolean. ".concat(userReadableTypeOfValue_default( + defaultValue + ), " given.") + ); + } + } + return { + type: "boolean", + default: defaultValue, + valueType: null, + [propTypeSymbol]: "TheatrePropType", + label: opts.label, + interpolate: (_a = opts.interpolate) != null ? _a : leftInterpolate, + deserializeAndSanitize: _ensureBoolean + }; +}; +var _ensureBoolean = (val8) => { + return typeof val8 === "boolean" ? val8 : void 0; +}; +function leftInterpolate(left) { + return left; +} +var string = (defaultValue, opts = {}) => { + var _a; + if (process.env.NODE_ENV !== "production") { + validateCommonOpts("t.string(defaultValue, opts)", opts); + if (typeof defaultValue !== "string") { + throw new Error( + "defaultValue in t.string(defaultValue) must be a string. ".concat(userReadableTypeOfValue_default( + defaultValue + ), " given.") + ); + } + } + return { + type: "string", + default: defaultValue, + valueType: null, + [propTypeSymbol]: "TheatrePropType", + label: opts.label, + interpolate: (_a = opts.interpolate) != null ? _a : leftInterpolate, + deserializeAndSanitize: _ensureString + }; +}; +function _ensureString(s2) { + return typeof s2 === "string" ? s2 : void 0; +} +function stringLiteral(defaultValue, valuesAndLabels, opts = {}) { + var _a, _b; + return { + type: "stringLiteral", + default: defaultValue, + valuesAndLabels: __spreadValues({}, valuesAndLabels), + [propTypeSymbol]: "TheatrePropType", + valueType: null, + as: (_a = opts.as) != null ? _a : "menu", + label: opts.label, + interpolate: (_b = opts.interpolate) != null ? _b : leftInterpolate, + deserializeAndSanitize(json) { + if (typeof json !== "string") + return void 0; + if (Object.prototype.hasOwnProperty.call(valuesAndLabels, json)) { + return json; + } else { + return void 0; + } + } + }; +} +var defaultNumberNudgeFn = ({ + config, + deltaX, + deltaFraction, + magnitude +}) => { + var _a; + const { range } = config; + if (!config.nudgeMultiplier && range && !range.includes(Infinity) && !range.includes(-Infinity)) { + return deltaFraction * (range[1] - range[0]) * magnitude; + } + return deltaX * magnitude * ((_a = config.nudgeMultiplier) != null ? _a : 1); +}; + +// shared/src/utils/slashedPaths.ts +var normalizeSlashedPath = (p2) => p2.replace(/^[\s\/]*/, "").replace(/[\s\/]*$/, "").replace(/\s*\/\s*/g, " / "); +var getValidationErrorsOfSlashedPath = (p2) => { + if (typeof p2 !== "string") + return "it is not a string. (it is a ".concat(typeof p2, ")"); + const components = p2.split(/\//); + if (components.length === 0) + return "it is empty."; + for (let i2 = 0; i2 < components.length; i2++) { + const component = components[i2].trim(); + if (component.length === 0) + return "the component #".concat(i2 + 1, " is empty."); + if (component.length > 64) + return "the component '".concat(component, "' must have 64 characters or less."); + } +}; +function validateAndSanitiseSlashedPathOrThrow(unsanitisedPath, fnName) { + const sanitisedPath = normalizeSlashedPath(unsanitisedPath); + if (process.env.NODE_ENV !== "development") { + return sanitisedPath; + } + const validation = getValidationErrorsOfSlashedPath(sanitisedPath); + if (validation) { + throw new InvalidArgumentError( + "The path in ".concat(fnName, "(").concat(typeof unsanitisedPath === "string" ? '"'.concat(unsanitisedPath, '"') : "", ") is invalid because ").concat(validation) + ); + } + if (unsanitisedPath !== sanitisedPath) { + notify.warning( + "Invalid path provided to object", + "The path in `".concat(fnName, '("').concat(unsanitisedPath, '")` was sanitized to `"').concat(sanitisedPath, '"`.\n\n') + "Please replace the path with the sanitized one, otherwise it will likely break in the future.", + [ + { + url: "https://www.theatrejs.com/docs/latest/manual/objects#creating-sheet-objects", + title: "Sheet Objects" + }, + { + url: "https://www.theatrejs.com/docs/latest/api/core#sheet.object", + title: "API" + } + ] + ); + } + return sanitisedPath; +} + +// core/src/sheets/TheatreSheet.ts +var import_fast_deep_equal = __toESM(require_fast_deep_equal()); +var weakMapOfUnsanitizedProps = /* @__PURE__ */ new WeakMap(); +var TheatreSheet = class { + get type() { + return "Theatre_Sheet_PublicAPI"; + } + /** + * @internal + */ + constructor(sheet) { + setPrivateAPI(this, sheet); + } + object(key, config, opts) { + const internal2 = privateAPI(this); + const sanitizedPath = validateAndSanitiseSlashedPathOrThrow( + key, + "sheet.object" + ); + const existingObject = internal2.getObject(sanitizedPath); + const nativeObject = null; + const actions = opts == null ? void 0 : opts.__actions__THIS_API_IS_UNSTABLE_AND_WILL_CHANGE_IN_THE_NEXT_VERSION; + if (existingObject) { + if (process.env.NODE_ENV !== "production") { + const prevConfig = weakMapOfUnsanitizedProps.get(existingObject); + if (prevConfig) { + if (!(0, import_fast_deep_equal.default)(config, prevConfig)) { + if ((opts == null ? void 0 : opts.reconfigure) === true) { + const sanitizedConfig = compound(config); + existingObject.template.reconfigure(sanitizedConfig); + weakMapOfUnsanitizedProps.set(existingObject, config); + return existingObject.publicApi; + } else { + throw new Error( + 'You seem to have called sheet.object("'.concat(key, '", config) twice, with different values for `config`. ') + "This is disallowed because changing the config of an object on the fly would make it difficult to reason about.\n\n" + 'You can fix this by either re-using the existing object, or calling sheet.object("'.concat(key, '", config) with the same config.\n\n') + "If you mean to reconfigure the object's config, set `{reconfigure: true}` in sheet.object(\"".concat(key, '", config, {reconfigure: true})') + ); + } + } + } + } + if (actions) { + existingObject.template._temp_setActions(actions); + } + return existingObject.publicApi; + } else { + const sanitizedConfig = compound(config); + const object = internal2.createObject( + sanitizedPath, + nativeObject, + sanitizedConfig, + actions + ); + if (process.env.NODE_ENV !== "production") { + weakMapOfUnsanitizedProps.set(object, config); + } + return object.publicApi; + } + } + __experimental_getExistingObject(key) { + const internal2 = privateAPI(this); + const sanitizedPath = validateAndSanitiseSlashedPathOrThrow( + key, + "sheet.object" + ); + const existingObject = internal2.getObject(sanitizedPath); + return existingObject == null ? void 0 : existingObject.publicApi; + } + get sequence() { + return privateAPI(this).getSequence().publicApi; + } + get project() { + return privateAPI(this).project.publicApi; + } + get address() { + return __spreadValues({}, privateAPI(this).address); + } + detachObject(key) { + const internal2 = privateAPI(this); + const sanitizedPath = validateAndSanitiseSlashedPathOrThrow( + key, + 'sheet.deleteObject("'.concat(key, '")') + ); + const obj = internal2.getObject(sanitizedPath); + if (!obj) { + notify.warning( + "Couldn't delete object \"".concat(sanitizedPath, '"'), + 'There is no object with key "'.concat(sanitizedPath, '".\n\nTo fix this, make sure you are calling `sheet.deleteObject("').concat(sanitizedPath, '")` with the correct key.') + ); + console.warn('Object key "'.concat(sanitizedPath, '" does not exist.')); + return; + } + internal2.deleteObject(sanitizedPath); + } +}; + +// core/src/sheets/Sheet.ts +var import_dataverse14 = require("@theatre/dataverse"); +var Sheet = class { + constructor(template, instanceId) { + this.template = template; + this.instanceId = instanceId; + __publicField(this, "_objects", new import_dataverse14.Atom({})); + __publicField(this, "_sequence"); + __publicField(this, "address"); + __publicField(this, "publicApi"); + __publicField(this, "project"); + __publicField(this, "objectsP", this._objects.pointer); + __publicField(this, "type", "Theatre_Sheet"); + __publicField(this, "_logger"); + this._logger = template.project._logger.named("Sheet", instanceId); + this._logger._trace("creating sheet"); + this.project = template.project; + this.address = __spreadProps(__spreadValues({}, template.address), { + sheetInstanceId: this.instanceId + }); + this.publicApi = new TheatreSheet(this); + } + /** + * @remarks At some point, we have to reconcile the concept of "an object" + * with that of "an element." + */ + createObject(objectKey, nativeObject, config, actions = {}) { + const objTemplate = this.template.getObjectTemplate( + objectKey, + nativeObject, + config, + actions + ); + const object = objTemplate.createInstance(this, nativeObject, config); + this._objects.setByPointer((p2) => p2[objectKey], object); + return object; + } + getObject(key) { + return this._objects.get()[key]; + } + deleteObject(objectKey) { + this._objects.reduce((state) => { + const newState = __spreadValues({}, state); + delete newState[objectKey]; + return newState; + }); + } + getSequence() { + if (!this._sequence) { + const lengthD = (0, import_dataverse14.prism)(() => { + const unsanitized = (0, import_dataverse14.val)( + this.project.pointers.historic.sheetsById[this.address.sheetId].sequence.length + ); + return sanitizeSequenceLength(unsanitized); + }); + const subUnitsPerUnitD = (0, import_dataverse14.prism)(() => { + const unsanitized = (0, import_dataverse14.val)( + this.project.pointers.historic.sheetsById[this.address.sheetId].sequence.subUnitsPerUnit + ); + return sanitizeSequenceSubUnitsPerUnit(unsanitized); + }); + this._sequence = new Sequence( + this.template.project, + this, + lengthD, + subUnitsPerUnitD + ); + } + return this._sequence; + } +}; +var sanitizeSequenceLength = (len) => typeof len === "number" && isFinite(len) && len > 0 ? len : 10; +var sanitizeSequenceSubUnitsPerUnit = (subs) => typeof subs === "number" && isInteger_default(subs) && subs >= 1 && subs <= 1e3 ? subs : 30; + +// core/src/sheets/SheetTemplate.ts +var SheetTemplate = class { + constructor(project, sheetId) { + this.project = project; + __publicField(this, "type", "Theatre_SheetTemplate"); + __publicField(this, "address"); + __publicField(this, "_instances", new import_dataverse15.Atom({})); + __publicField(this, "instancesP", this._instances.pointer); + __publicField(this, "_objectTemplates", new import_dataverse15.Atom({})); + __publicField(this, "objectTemplatesP", this._objectTemplates.pointer); + this.address = __spreadProps(__spreadValues({}, project.address), { sheetId }); + } + getInstance(instanceId) { + let inst = this._instances.get()[instanceId]; + if (!inst) { + inst = new Sheet(this, instanceId); + this._instances.setByPointer((p2) => p2[instanceId], inst); + } + return inst; + } + getObjectTemplate(objectKey, nativeObject, config, actions) { + let template = this._objectTemplates.get()[objectKey]; + if (!template) { + template = new SheetObjectTemplate( + this, + objectKey, + nativeObject, + config, + actions + ); + this._objectTemplates.setByPointer((p2) => p2[objectKey], template); + } + return template; + } +}; + +// core/src/projects/Project.ts +var import_dataverse16 = require("@theatre/dataverse"); +var import_dataverse17 = require("@theatre/dataverse"); + +// shared/src/utils/delay.ts +var delay = (dur) => new Promise((resolve) => setTimeout(resolve, dur)); +var delay_default = delay; + +// ../node_modules/immer/dist/immer.esm.js +function n(n2) { + for (var t2 = arguments.length, r2 = Array(t2 > 1 ? t2 - 1 : 0), e2 = 1; e2 < t2; e2++) + r2[e2 - 1] = arguments[e2]; + if ("production" !== process.env.NODE_ENV) { + var i2 = Y[n2], o2 = i2 ? "function" == typeof i2 ? i2.apply(null, r2) : i2 : "unknown error nr: " + n2; + throw Error("[Immer] " + o2); + } + throw Error("[Immer] minified error nr: " + n2 + (r2.length ? " " + r2.map(function(n3) { + return "'" + n3 + "'"; + }).join(",") : "") + ". Find the full error at: https://bit.ly/3cXEKWf"); +} +function t(n2) { + return !!n2 && !!n2[Q]; +} +function r(n2) { + return !!n2 && (function(n3) { + if (!n3 || "object" != typeof n3) + return false; + var t2 = Object.getPrototypeOf(n3); + if (null === t2) + return true; + var r2 = Object.hasOwnProperty.call(t2, "constructor") && t2.constructor; + return r2 === Object || "function" == typeof r2 && Function.toString.call(r2) === Z; + }(n2) || Array.isArray(n2) || !!n2[L] || !!n2.constructor[L] || s(n2) || v(n2)); +} +function e(r2) { + return t(r2) || n(23, r2), r2[Q].t; +} +function i(n2, t2, r2) { + void 0 === r2 && (r2 = false), 0 === o(n2) ? (r2 ? Object.keys : nn)(n2).forEach(function(e2) { + r2 && "symbol" == typeof e2 || t2(e2, n2[e2], n2); + }) : n2.forEach(function(r3, e2) { + return t2(e2, r3, n2); + }); +} +function o(n2) { + var t2 = n2[Q]; + return t2 ? t2.i > 3 ? t2.i - 4 : t2.i : Array.isArray(n2) ? 1 : s(n2) ? 2 : v(n2) ? 3 : 0; +} +function u(n2, t2) { + return 2 === o(n2) ? n2.has(t2) : Object.prototype.hasOwnProperty.call(n2, t2); +} +function a(n2, t2) { + return 2 === o(n2) ? n2.get(t2) : n2[t2]; +} +function f(n2, t2, r2) { + var e2 = o(n2); + 2 === e2 ? n2.set(t2, r2) : 3 === e2 ? (n2.delete(t2), n2.add(r2)) : n2[t2] = r2; +} +function c(n2, t2) { + return n2 === t2 ? 0 !== n2 || 1 / n2 == 1 / t2 : n2 != n2 && t2 != t2; +} +function s(n2) { + return X && n2 instanceof Map; +} +function v(n2) { + return q && n2 instanceof Set; +} +function p(n2) { + return n2.o || n2.t; +} +function l(n2) { + if (Array.isArray(n2)) + return Array.prototype.slice.call(n2); + var t2 = tn(n2); + delete t2[Q]; + for (var r2 = nn(t2), e2 = 0; e2 < r2.length; e2++) { + var i2 = r2[e2], o2 = t2[i2]; + false === o2.writable && (o2.writable = true, o2.configurable = true), (o2.get || o2.set) && (t2[i2] = { configurable: true, writable: true, enumerable: o2.enumerable, value: n2[i2] }); + } + return Object.create(Object.getPrototypeOf(n2), t2); +} +function d(n2, e2) { + return void 0 === e2 && (e2 = false), y(n2) || t(n2) || !r(n2) ? n2 : (o(n2) > 1 && (n2.set = n2.add = n2.clear = n2.delete = h), Object.freeze(n2), e2 && i(n2, function(n3, t2) { + return d(t2, true); + }, true), n2); +} +function h() { + n(2); +} +function y(n2) { + return null == n2 || "object" != typeof n2 || Object.isFrozen(n2); +} +function b(t2) { + var r2 = rn[t2]; + return r2 || n(18, t2), r2; +} +function _() { + return "production" === process.env.NODE_ENV || U || n(0), U; +} +function j(n2, t2) { + t2 && (b("Patches"), n2.u = [], n2.s = [], n2.v = t2); +} +function O(n2) { + g(n2), n2.p.forEach(S), n2.p = null; +} +function g(n2) { + n2 === U && (U = n2.l); +} +function w(n2) { + return U = { p: [], l: U, h: n2, m: true, _: 0 }; +} +function S(n2) { + var t2 = n2[Q]; + 0 === t2.i || 1 === t2.i ? t2.j() : t2.O = true; +} +function P(t2, e2) { + e2._ = e2.p.length; + var i2 = e2.p[0], o2 = void 0 !== t2 && t2 !== i2; + return e2.h.g || b("ES5").S(e2, t2, o2), o2 ? (i2[Q].P && (O(e2), n(4)), r(t2) && (t2 = M(e2, t2), e2.l || x(e2, t2)), e2.u && b("Patches").M(i2[Q], t2, e2.u, e2.s)) : t2 = M(e2, i2, []), O(e2), e2.u && e2.v(e2.u, e2.s), t2 !== H ? t2 : void 0; +} +function M(n2, t2, r2) { + if (y(t2)) + return t2; + var e2 = t2[Q]; + if (!e2) + return i(t2, function(i2, o3) { + return A(n2, e2, t2, i2, o3, r2); + }, true), t2; + if (e2.A !== n2) + return t2; + if (!e2.P) + return x(n2, e2.t, true), e2.t; + if (!e2.I) { + e2.I = true, e2.A._--; + var o2 = 4 === e2.i || 5 === e2.i ? e2.o = l(e2.k) : e2.o; + i(3 === e2.i ? new Set(o2) : o2, function(t3, i2) { + return A(n2, e2, o2, t3, i2, r2); + }), x(n2, o2, false), r2 && n2.u && b("Patches").R(e2, r2, n2.u, n2.s); + } + return e2.o; +} +function A(e2, i2, o2, a2, c2, s2) { + if ("production" !== process.env.NODE_ENV && c2 === o2 && n(5), t(c2)) { + var v2 = M(e2, c2, s2 && i2 && 3 !== i2.i && !u(i2.D, a2) ? s2.concat(a2) : void 0); + if (f(o2, a2, v2), !t(v2)) + return; + e2.m = false; + } + if (r(c2) && !y(c2)) { + if (!e2.h.F && e2._ < 1) + return; + M(e2, c2), i2 && i2.A.l || x(e2, c2); + } +} +function x(n2, t2, r2) { + void 0 === r2 && (r2 = false), n2.h.F && n2.m && d(t2, r2); +} +function z(n2, t2) { + var r2 = n2[Q]; + return (r2 ? p(r2) : n2)[t2]; +} +function I(n2, t2) { + if (t2 in n2) + for (var r2 = Object.getPrototypeOf(n2); r2; ) { + var e2 = Object.getOwnPropertyDescriptor(r2, t2); + if (e2) + return e2; + r2 = Object.getPrototypeOf(r2); + } +} +function k(n2) { + n2.P || (n2.P = true, n2.l && k(n2.l)); +} +function E(n2) { + n2.o || (n2.o = l(n2.t)); +} +function R(n2, t2, r2) { + var e2 = s(t2) ? b("MapSet").N(t2, r2) : v(t2) ? b("MapSet").T(t2, r2) : n2.g ? function(n3, t3) { + var r3 = Array.isArray(n3), e3 = { i: r3 ? 1 : 0, A: t3 ? t3.A : _(), P: false, I: false, D: {}, l: t3, t: n3, k: null, o: null, j: null, C: false }, i2 = e3, o2 = en; + r3 && (i2 = [e3], o2 = on); + var u2 = Proxy.revocable(i2, o2), a2 = u2.revoke, f2 = u2.proxy; + return e3.k = f2, e3.j = a2, f2; + }(t2, r2) : b("ES5").J(t2, r2); + return (r2 ? r2.A : _()).p.push(e2), e2; +} +function D(e2) { + return t(e2) || n(22, e2), function n2(t2) { + if (!r(t2)) + return t2; + var e3, u2 = t2[Q], c2 = o(t2); + if (u2) { + if (!u2.P && (u2.i < 4 || !b("ES5").K(u2))) + return u2.t; + u2.I = true, e3 = F(t2, c2), u2.I = false; + } else + e3 = F(t2, c2); + return i(e3, function(t3, r2) { + u2 && a(u2.t, t3) === r2 || f(e3, t3, n2(r2)); + }), 3 === c2 ? new Set(e3) : e3; + }(e2); +} +function F(n2, t2) { + switch (t2) { + case 2: + return new Map(n2); + case 3: + return Array.from(n2); + } + return l(n2); +} +var G; +var U; +var W = "undefined" != typeof Symbol && "symbol" == typeof Symbol("x"); +var X = "undefined" != typeof Map; +var q = "undefined" != typeof Set; +var B = "undefined" != typeof Proxy && void 0 !== Proxy.revocable && "undefined" != typeof Reflect; +var H = W ? Symbol.for("immer-nothing") : ((G = {})["immer-nothing"] = true, G); +var L = W ? Symbol.for("immer-draftable") : "__$immer_draftable"; +var Q = W ? Symbol.for("immer-state") : "__$immer_state"; +var Y = { 0: "Illegal state", 1: "Immer drafts cannot have computed properties", 2: "This object has been frozen and should not be mutated", 3: function(n2) { + return "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? " + n2; +}, 4: "An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.", 5: "Immer forbids circular references", 6: "The first or second argument to `produce` must be a function", 7: "The third argument to `produce` must be a function or undefined", 8: "First argument to `createDraft` must be a plain object, an array, or an immerable object", 9: "First argument to `finishDraft` must be a draft returned by `createDraft`", 10: "The given draft is already finalized", 11: "Object.defineProperty() cannot be used on an Immer draft", 12: "Object.setPrototypeOf() cannot be used on an Immer draft", 13: "Immer only supports deleting array indices", 14: "Immer only supports setting array indices and the 'length' property", 15: function(n2) { + return "Cannot apply patch, path doesn't resolve: " + n2; +}, 16: 'Sets cannot have "replace" patches.', 17: function(n2) { + return "Unsupported patch operation: " + n2; +}, 18: function(n2) { + return "The plugin for '" + n2 + "' has not been loaded into Immer. To enable the plugin, import and call `enable" + n2 + "()` when initializing your application."; +}, 20: "Cannot use proxies if Proxy, Proxy.revocable or Reflect are not available", 21: function(n2) { + return "produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '" + n2 + "'"; +}, 22: function(n2) { + return "'current' expects a draft, got: " + n2; +}, 23: function(n2) { + return "'original' expects a draft, got: " + n2; +}, 24: "Patching reserved attributes like __proto__, prototype and constructor is not allowed" }; +var Z = "" + Object.prototype.constructor; +var nn = "undefined" != typeof Reflect && Reflect.ownKeys ? Reflect.ownKeys : void 0 !== Object.getOwnPropertySymbols ? function(n2) { + return Object.getOwnPropertyNames(n2).concat(Object.getOwnPropertySymbols(n2)); +} : Object.getOwnPropertyNames; +var tn = Object.getOwnPropertyDescriptors || function(n2) { + var t2 = {}; + return nn(n2).forEach(function(r2) { + t2[r2] = Object.getOwnPropertyDescriptor(n2, r2); + }), t2; +}; +var rn = {}; +var en = { get: function(n2, t2) { + if (t2 === Q) + return n2; + var e2 = p(n2); + if (!u(e2, t2)) + return function(n3, t3, r2) { + var e3, i3 = I(t3, r2); + return i3 ? "value" in i3 ? i3.value : null === (e3 = i3.get) || void 0 === e3 ? void 0 : e3.call(n3.k) : void 0; + }(n2, e2, t2); + var i2 = e2[t2]; + return n2.I || !r(i2) ? i2 : i2 === z(n2.t, t2) ? (E(n2), n2.o[t2] = R(n2.A.h, i2, n2)) : i2; +}, has: function(n2, t2) { + return t2 in p(n2); +}, ownKeys: function(n2) { + return Reflect.ownKeys(p(n2)); +}, set: function(n2, t2, r2) { + var e2 = I(p(n2), t2); + if (null == e2 ? void 0 : e2.set) + return e2.set.call(n2.k, r2), true; + if (!n2.P) { + var i2 = z(p(n2), t2), o2 = null == i2 ? void 0 : i2[Q]; + if (o2 && o2.t === r2) + return n2.o[t2] = r2, n2.D[t2] = false, true; + if (c(r2, i2) && (void 0 !== r2 || u(n2.t, t2))) + return true; + E(n2), k(n2); + } + return n2.o[t2] === r2 && "number" != typeof r2 && (void 0 !== r2 || t2 in n2.o) || (n2.o[t2] = r2, n2.D[t2] = true, true); +}, deleteProperty: function(n2, t2) { + return void 0 !== z(n2.t, t2) || t2 in n2.t ? (n2.D[t2] = false, E(n2), k(n2)) : delete n2.D[t2], n2.o && delete n2.o[t2], true; +}, getOwnPropertyDescriptor: function(n2, t2) { + var r2 = p(n2), e2 = Reflect.getOwnPropertyDescriptor(r2, t2); + return e2 ? { writable: true, configurable: 1 !== n2.i || "length" !== t2, enumerable: e2.enumerable, value: r2[t2] } : e2; +}, defineProperty: function() { + n(11); +}, getPrototypeOf: function(n2) { + return Object.getPrototypeOf(n2.t); +}, setPrototypeOf: function() { + n(12); +} }; +var on = {}; +i(en, function(n2, t2) { + on[n2] = function() { + return arguments[0] = arguments[0][0], t2.apply(this, arguments); + }; +}), on.deleteProperty = function(t2, r2) { + return "production" !== process.env.NODE_ENV && isNaN(parseInt(r2)) && n(13), en.deleteProperty.call(this, t2[0], r2); +}, on.set = function(t2, r2, e2) { + return "production" !== process.env.NODE_ENV && "length" !== r2 && isNaN(parseInt(r2)) && n(14), en.set.call(this, t2[0], r2, e2, t2[0]); +}; +var un = function() { + function e2(t2) { + var e3 = this; + this.g = B, this.F = true, this.produce = function(t3, i3, o2) { + if ("function" == typeof t3 && "function" != typeof i3) { + var u2 = i3; + i3 = t3; + var a2 = e3; + return function(n2) { + var t4 = this; + void 0 === n2 && (n2 = u2); + for (var r2 = arguments.length, e4 = Array(r2 > 1 ? r2 - 1 : 0), o3 = 1; o3 < r2; o3++) + e4[o3 - 1] = arguments[o3]; + return a2.produce(n2, function(n3) { + var r3; + return (r3 = i3).call.apply(r3, [t4, n3].concat(e4)); + }); + }; + } + var f2; + if ("function" != typeof i3 && n(6), void 0 !== o2 && "function" != typeof o2 && n(7), r(t3)) { + var c2 = w(e3), s2 = R(e3, t3, void 0), v2 = true; + try { + f2 = i3(s2), v2 = false; + } finally { + v2 ? O(c2) : g(c2); + } + return "undefined" != typeof Promise && f2 instanceof Promise ? f2.then(function(n2) { + return j(c2, o2), P(n2, c2); + }, function(n2) { + throw O(c2), n2; + }) : (j(c2, o2), P(f2, c2)); + } + if (!t3 || "object" != typeof t3) { + if ((f2 = i3(t3)) === H) + return; + return void 0 === f2 && (f2 = t3), e3.F && d(f2, true), f2; + } + n(21, t3); + }, this.produceWithPatches = function(n2, t3) { + return "function" == typeof n2 ? function(t4) { + for (var r3 = arguments.length, i4 = Array(r3 > 1 ? r3 - 1 : 0), o2 = 1; o2 < r3; o2++) + i4[o2 - 1] = arguments[o2]; + return e3.produceWithPatches(t4, function(t5) { + return n2.apply(void 0, [t5].concat(i4)); + }); + } : [e3.produce(n2, t3, function(n3, t4) { + r2 = n3, i3 = t4; + }), r2, i3]; + var r2, i3; + }, "boolean" == typeof (null == t2 ? void 0 : t2.useProxies) && this.setUseProxies(t2.useProxies), "boolean" == typeof (null == t2 ? void 0 : t2.autoFreeze) && this.setAutoFreeze(t2.autoFreeze); + } + var i2 = e2.prototype; + return i2.createDraft = function(e3) { + r(e3) || n(8), t(e3) && (e3 = D(e3)); + var i3 = w(this), o2 = R(this, e3, void 0); + return o2[Q].C = true, g(i3), o2; + }, i2.finishDraft = function(t2, r2) { + var e3 = t2 && t2[Q]; + "production" !== process.env.NODE_ENV && (e3 && e3.C || n(9), e3.I && n(10)); + var i3 = e3.A; + return j(i3, r2), P(void 0, i3); + }, i2.setAutoFreeze = function(n2) { + this.F = n2; + }, i2.setUseProxies = function(t2) { + t2 && !B && n(20), this.g = t2; + }, i2.applyPatches = function(n2, r2) { + var e3; + for (e3 = r2.length - 1; e3 >= 0; e3--) { + var i3 = r2[e3]; + if (0 === i3.path.length && "replace" === i3.op) { + n2 = i3.value; + break; + } + } + var o2 = b("Patches").$; + return t(n2) ? o2(n2, r2) : this.produce(n2, function(n3) { + return o2(n3, r2.slice(e3 + 1)); + }); + }, e2; +}(); +var an = new un(); +var fn = an.produce; +var cn = an.produceWithPatches.bind(an); +var sn = an.setAutoFreeze.bind(an); +var vn = an.setUseProxies.bind(an); +var pn = an.applyPatches.bind(an); +var ln = an.createDraft.bind(an); +var dn = an.finishDraft.bind(an); + +// shared/src/globals.ts +var globals = { + /** + * If the schema of the redux store changes in a backwards-incompatible way, then this version number should be incremented. + * + * While this looks like semver, it is not. There are no patch numbers, so any change in this number is a breaking change. + * + * However, as long as the schema of the redux store is backwards-compatible, then we don't have to change this number. + * + * Since the 0.4.0 release, this number has not had to change. + */ + currentProjectStateDefinitionVersion: "0.4.0" +}; +var globals_default = globals; + +// core/src/projects/initialiseProjectState.ts +async function initialiseProjectState(studio, project, onDiskState) { + await delay_default(0); + studio.transaction(({ drafts }) => { + var _a; + const projectId = project.address.projectId; + drafts.ephemeral.coreByProject[projectId] = { + lastExportedObject: null, + loadingState: { type: "loading" } + }; + drafts.ahistoric.coreByProject[projectId] = { + ahistoricStuff: "" + }; + function useInitialState() { + drafts.ephemeral.coreByProject[projectId].loadingState = { + type: "loaded" + }; + drafts.historic.coreByProject[projectId] = { + sheetsById: {}, + definitionVersion: globals_default.currentProjectStateDefinitionVersion, + revisionHistory: [] + }; + } + function useOnDiskState(state) { + drafts.ephemeral.coreByProject[projectId].loadingState = { + type: "loaded" + }; + drafts.historic.coreByProject[projectId] = state; + } + function useBrowserState() { + drafts.ephemeral.coreByProject[projectId].loadingState = { + type: "loaded" + }; + } + function browserStateIsNotBasedOnDiskState(onDiskState2) { + drafts.ephemeral.coreByProject[projectId].loadingState = { + type: "browserStateIsNotBasedOnDiskState", + onDiskState: onDiskState2 + }; + } + const browserState = (_a = e(drafts.historic)) == null ? void 0 : _a.coreByProject[project.address.projectId]; + if (!browserState) { + if (!onDiskState) { + useInitialState(); + } else { + useOnDiskState(onDiskState); + } + } else { + if (!onDiskState) { + useBrowserState(); + } else { + if (browserState.revisionHistory.indexOf( + onDiskState.revisionHistory[0] + ) == -1) { + browserStateIsNotBasedOnDiskState(onDiskState); + } else { + useBrowserState(); + } + } + } + }); +} + +// core/src/_coreLogger.ts +function noop2() { +} +function _coreLogger(config) { + var _a, _b; + const internalMin = ((_a = config == null ? void 0 : config.logging) == null ? void 0 : _a.internal) ? (_b = config.logging.min) != null ? _b : 256 /* WARN */ : Infinity; + const shouldDebugLogger = internalMin <= 128 /* DEBUG */; + const shouldShowLoggerErrors = internalMin <= 512 /* ERROR */; + const internal2 = createTheatreInternalLogger(void 0, { + _debug: shouldDebugLogger ? console.debug.bind(console, "_coreLogger(TheatreInternalLogger) debug") : noop2, + _error: shouldShowLoggerErrors ? console.error.bind(console, "_coreLogger(TheatreInternalLogger) error") : noop2 + }); + if (config) { + const { logger, logging } = config; + if (logger) + internal2.configureLogger(logger); + if (logging) + internal2.configureLogging(logging); + else { + internal2.configureLogging({ + dev: process.env.NODE_ENV !== "production" + }); + } + } + return internal2.getLogger().named("Theatre"); +} + +// core/src/projects/Project.ts +var Project = class { + constructor(id, config = {}, publicApi) { + this.config = config; + this.publicApi = publicApi; + __publicField(this, "pointers"); + __publicField(this, "_pointerProxies"); + __publicField(this, "address"); + __publicField(this, "_studioReadyDeferred"); + __publicField(this, "_assetStorageReadyDeferred"); + __publicField(this, "_readyPromise"); + __publicField(this, "_sheetTemplates", new import_dataverse17.Atom({})); + __publicField(this, "sheetTemplatesP", this._sheetTemplates.pointer); + __publicField(this, "_studio"); + __publicField(this, "assetStorage"); + __publicField(this, "type", "Theatre_Project"); + __publicField(this, "_logger"); + var _a; + this._logger = _coreLogger({ logging: { dev: true } }).named("Project", id); + this._logger.traceDev("creating project"); + this.address = { projectId: id }; + const onDiskStateAtom = new import_dataverse17.Atom({ + ahistoric: { + ahistoricStuff: "" + }, + historic: (_a = config.state) != null ? _a : { + sheetsById: {}, + definitionVersion: globals_default.currentProjectStateDefinitionVersion, + revisionHistory: [] + }, + ephemeral: { + loadingState: { + type: "loaded" + }, + lastExportedObject: null + } + }); + this._assetStorageReadyDeferred = defer(); + this.assetStorage = { + getAssetUrl: (assetId) => { + var _a2; + return "".concat((_a2 = config.assets) == null ? void 0 : _a2.baseUrl, "/").concat(assetId); + }, + // Until the asset storage is ready, we'll throw an error when the user tries to use it + createAsset: () => { + throw new Error("Please wait for Project.ready to use assets."); + } + }; + this._pointerProxies = { + historic: new import_dataverse16.PointerProxy(onDiskStateAtom.pointer.historic), + ahistoric: new import_dataverse16.PointerProxy(onDiskStateAtom.pointer.ahistoric), + ephemeral: new import_dataverse16.PointerProxy(onDiskStateAtom.pointer.ephemeral) + }; + this.pointers = { + historic: this._pointerProxies.historic.pointer, + ahistoric: this._pointerProxies.ahistoric.pointer, + ephemeral: this._pointerProxies.ephemeral.pointer + }; + projectsSingleton_default.add(id, this); + this._studioReadyDeferred = defer(); + this._readyPromise = Promise.all([ + this._studioReadyDeferred.promise, + this._assetStorageReadyDeferred.promise + // hide the array from the user, i.e. make it Promise
>6:64,d=2
>4,n=(15&v)<<4|(g=l.indexOf(i.charAt(d++)))>>2,h=(3&g)<<6|(s=l.indexOf(i.charAt(d++))),f[z++]=o,g!==64&&(f[z++]=n),s!==64&&(f[z++]=h);return f}},{"./support":30,"./utils":32}],2:[function(t,a,c){"use strict";var r=t("./external"),e=t("./stream/DataWorker"),l=t("./stream/Crc32Probe"),i=t("./stream/DataLengthProbe");function o(n,h,v,g,s){this.compressedSize=n,this.uncompressedSize=h,this.crc32=v,this.compression=g,this.compressedContent=s}o.prototype={getContentWorker:function(){var n=new e(r.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new i("data_length")),h=this;return n.on("end",function(){if(this.streamInfo.data_length!==h.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),n},getCompressedWorker:function(){return new e(r.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},o.createWorkerFrom=function(n,h,v){return n.pipe(new l).pipe(new i("uncompressedSize")).pipe(h.compressWorker(v)).pipe(new i("compressedSize")).withStreamInfo("compression",h)},a.exports=o},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(t,a,c){"use strict";var r=t("./stream/GenericWorker");c.STORE={magic:"\0\0",compressWorker:function(){return new r("STORE compression")},uncompressWorker:function(){return new r("STORE decompression")}},c.DEFLATE=t("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(t,a,c){"use strict";var r=t("./utils"),e=function(){for(var l,i=[],o=0;o<256;o++){l=o;for(var n=0;n<8;n++)l=1&l?3988292384^l>>>1:l>>>1;i[o]=l}return i}();a.exports=function(l,i){return l!==void 0&&l.length?r.getTypeOf(l)!=="string"?function(o,n,h,v){var g=e,s=v+h;o^=-1;for(var d=v;d >10&1023,m[z++]=56320|1023&u)}return m.length!==z&&(m.subarray?m=m.subarray(0,z):m.length=z),r.applyFromCharCode(m)}(g=r.transformTo(e.uint8array?"uint8array":"array",g))},r.inherits(h,i),h.prototype.processChunk=function(g){var s=r.transformTo(e.uint8array?"uint8array":"array",g.data);if(this.leftOver&&this.leftOver.length){if(e.uint8array){var d=s;(s=new Uint8Array(d.length+this.leftOver.length)).set(this.leftOver,0),s.set(d,this.leftOver.length)}else s=this.leftOver.concat(s);this.leftOver=null}var z=function(f,p){var m;for((p=p||f.length)>f.length&&(p=f.length),m=p-1;0<=m&&(192&f[m])==128;)m--;return m<0||m===0?p:m+o[f[m]]>p?m:p}(s),u=s;z!==s.length&&(e.uint8array?(u=s.subarray(0,z),this.leftOver=s.subarray(z,s.length)):(u=s.slice(0,z),this.leftOver=s.slice(z,s.length))),this.push({data:c.utf8decode(u),meta:g.meta})},h.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:c.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},c.Utf8DecodeWorker=h,r.inherits(v,i),v.prototype.processChunk=function(g){this.push({data:c.utf8encode(g.data),meta:g.meta})},c.Utf8EncodeWorker=v},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(t,a,c){"use strict";var r=t("./support"),e=t("./base64"),l=t("./nodejsUtils"),i=t("./external");function o(d){return d}function n(d,z){for(var u=0;u >>=k=y>>>24,p-=k,!(16&(k=y>>>16&255))){if(!(64&k)){y=M[(65535&y)+(f&(1< =j.wsize?(r.arraySet(j.window,P,C-j.wsize,j.wsize,0),j.wnext=0,j.whave=j.wsize):(E<(a1=j.wsize-j.wnext)&&(a1=E),r.arraySet(j.window,P,C-E,a1,j.wnext),(E-=a1)?(r.arraySet(j.window,P,C-E,E,0),j.wnext=E,j.whave=j.wsize):(j.wnext+=a1,j.wnext===j.wsize&&(j.wnext=0),j.whave An error occurred: ".concat(a," An error occurred:>>8^g[255&(o^n[d])];return-1^o}(0|i,l,l.length,0):function(o,n,h,v){var g=e,s=v+h;o^=-1;for(var d=v;d>>8^g[255&(o^n.charCodeAt(d))];return-1^o}(0|i,l,l.length,0):0}},{"./utils":32}],5:[function(t,a,c){"use strict";c.base64=!1,c.binary=!1,c.dir=!1,c.createFolders=!0,c.date=null,c.compression=null,c.compressionOptions=null,c.comment=null,c.unixPermissions=null,c.dosPermissions=null},{}],6:[function(t,a,c){"use strict";var r=null;r=typeof Promise!="undefined"?Promise:t("lie"),a.exports={Promise:r}},{lie:37}],7:[function(t,a,c){"use strict";var r=typeof Uint8Array!="undefined"&&typeof Uint16Array!="undefined"&&typeof Uint32Array!="undefined",e=t("pako"),l=t("./utils"),i=t("./stream/GenericWorker"),o=r?"uint8array":"array";function n(h,v){i.call(this,"FlateWorker/"+h),this._pako=null,this._pakoAction=h,this._pakoOptions=v,this.meta={}}c.magic="\b\0",l.inherits(n,i),n.prototype.processChunk=function(h){this.meta=h.meta,this._pako===null&&this._createPako(),this._pako.push(l.transformTo(o,h.data),!1)},n.prototype.flush=function(){i.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},n.prototype.cleanUp=function(){i.prototype.cleanUp.call(this),this._pako=null},n.prototype._createPako=function(){this._pako=new e[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var h=this;this._pako.onData=function(v){h.push({data:v,meta:h.meta})}},c.compressWorker=function(h){return new n("Deflate",h)},c.uncompressWorker=function(){return new n("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(t,a,c){"use strict";function r(g,s){var d,z="";for(d=0;d>>=8;return z}function e(g,s,d,z,u,f){var p,m,M=g.file,w=g.compression,H=f!==o.utf8encode,y=l.transformTo("string",f(M.name)),k=l.transformTo("string",o.utf8encode(M.name)),F=M.comment,U=l.transformTo("string",f(F)),A=l.transformTo("string",o.utf8encode(F)),P=k.length!==M.name.length,C=A.length!==F.length,E="",a1="",j="",K=M.dir,Z=M.date,J={crc32:0,compressedSize:0,uncompressedSize:0};s&&!d||(J.crc32=g.crc32,J.compressedSize=g.compressedSize,J.uncompressedSize=g.uncompressedSize);var W=0;s&&(W|=8),H||!P&&!C||(W|=2048);var _=0,g1=0;K&&(_|=16),u==="UNIX"?(g1=798,_|=function($,o1){var u1=$;return $||(u1=o1?16893:33204),(65535&u1)<<16}(M.unixPermissions,K)):(g1=20,_|=function($){return 63&($||0)}(M.dosPermissions)),p=Z.getUTCHours(),p<<=6,p|=Z.getUTCMinutes(),p<<=5,p|=Z.getUTCSeconds()/2,m=Z.getUTCFullYear()-1980,m<<=4,m|=Z.getUTCMonth()+1,m<<=5,m|=Z.getUTCDate(),P&&(a1=r(1,1)+r(n(y),4)+k,E+="up"+r(a1.length,2)+a1),C&&(j=r(1,1)+r(n(U),4)+A,E+="uc"+r(j.length,2)+j);var X="";return X+="\n\0",X+=r(W,2),X+=w.magic,X+=r(p,2),X+=r(m,2),X+=r(J.crc32,4),X+=r(J.compressedSize,4),X+=r(J.uncompressedSize,4),X+=r(y.length,2),X+=r(E.length,2),{fileRecord:h.LOCAL_FILE_HEADER+X+y+E,dirRecord:h.CENTRAL_FILE_HEADER+r(g1,2)+X+r(U.length,2)+"\0\0\0\0"+r(_,4)+r(z,4)+y+E+U}}var l=t("../utils"),i=t("../stream/GenericWorker"),o=t("../utf8"),n=t("../crc32"),h=t("../signature");function v(g,s,d,z){i.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=s,this.zipPlatform=d,this.encodeFileName=z,this.streamFiles=g,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}l.inherits(v,i),v.prototype.push=function(g){var s=g.meta.percent||0,d=this.entriesCount,z=this._sources.length;this.accumulate?this.contentBuffer.push(g):(this.bytesWritten+=g.data.length,i.prototype.push.call(this,{data:g.data,meta:{currentFile:this.currentFile,percent:d?(s+100*(d-z-1))/d:100}}))},v.prototype.openedSource=function(g){this.currentSourceOffset=this.bytesWritten,this.currentFile=g.file.name;var s=this.streamFiles&&!g.file.dir;if(s){var d=e(g,s,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:d.fileRecord,meta:{percent:0}})}else this.accumulate=!0},v.prototype.closedSource=function(g){this.accumulate=!1;var s=this.streamFiles&&!g.file.dir,d=e(g,s,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(d.dirRecord),s)this.push({data:function(z){return h.DATA_DESCRIPTOR+r(z.crc32,4)+r(z.compressedSize,4)+r(z.uncompressedSize,4)}(g),meta:{percent:100}});else for(this.push({data:d.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},v.prototype.flush=function(){for(var g=this.bytesWritten,s=0;s>10&1023,f[s++]=56320|1023&d)}return n(f,s)},c.utf8border=function(h,v){var g;for((v=v||h.length)>h.length&&(v=h.length),g=v-1;0<=g&&(192&h[g])==128;)g--;return g<0||g===0?v:g+i[h[g]]>v?g:v}},{"./common":41}],43:[function(t,a,c){"use strict";a.exports=function(r,e,l,i){for(var o=65535&r|0,n=r>>>16&65535|0,h=0;l!==0;){for(l-=h=2e3"+Z2(e.message+"",!0)+"
";throw e}try{let e=Q6.lex(t,a);if(a.walkTokens){if(a.async)return Promise.all(V1.walkTokens(e,a.walkTokens)).then(()=>B5.parse(e,a)).catch(r);V1.walkTokens(e,a.walkTokens)}return B5.parse(e,a)}catch(e){r(e)}}var ht,s51,z51,u51,p51,m51,II,f51,M51,x51,C51,on,L51,H51,V51,hn,zr,H1,m1,Q6,ur,vn,gn,B5,$y1,Qy1,Xy1,Yy1,Jy1,tS1,aS1,_I=x(()=>{ht=EI();s51=/[&<>"']/,z51=/[&<>"']/g,u51=/[<>"']|&(?!#?\w+;)/,p51=/[<>"']|&(?!#?\w+;)/g,m51={"&":"&","<":"<",">":">",'"':""","'":"'"},II=t=>m51[t];f51=/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig;M51=/(^|[^\[])\^/g;x51=/[^\w:]/g,C51=/^$|^[a-z][a-z0-9+.-]*:|^[?#]/i;on={},L51=/^[^:]+:\/*[^/]*$/,H51=/^([^:]+:)[\s\S]*$/,V51=/^([^:]+:\/*[^/]*)[\s\S]*$/;hn={exec:function(){}};zr=class{constructor(a){this.options=a||ht}space(a){let c=this.rules.block.newline.exec(a);if(c&&c[0].length>0)return{type:"space",raw:c[0]}}code(a){let c=this.rules.block.code.exec(a);if(c){let r=c[0].replace(/^ {1,4}/gm,"");return{type:"code",raw:c[0],codeBlockStyle:"indented",text:this.options.pedantic?r:nn(r,"\n")}}}fences(a){let c=this.rules.block.fences.exec(a);if(c){let r=c[0],e=y51(r,c[3]||"");return{type:"code",raw:r,lang:c[2]?c[2].trim():c[2],text:e}}}heading(a){let c=this.rules.block.heading.exec(a);if(c){let r=c[2].trim();if(/#$/.test(r)){let e=nn(r,"#");(this.options.pedantic||!e||/ $/.test(e))&&(r=e.trim())}return{type:"heading",raw:c[0],depth:c[1].length,text:r,tokens:this.lexer.inline(r)}}}hr(a){let c=this.rules.block.hr.exec(a);if(c)return{type:"hr",raw:c[0]}}blockquote(a){let c=this.rules.block.blockquote.exec(a);if(c){let r=c[0].replace(/^ *>[ \t]?/gm,"");return{type:"blockquote",raw:c[0],tokens:this.lexer.blockTokens(r,[]),text:r}}}list(a){let c=this.rules.block.list.exec(a);if(c){let r,e,l,i,o,n,h,v,g,s,d,z,u=c[1].trim(),f=u.length>1,p={type:"list",raw:"",ordered:f,start:f?+u.slice(0,-1):"",loose:!1,items:[]};u=f?"\\d{1,9}\\".concat(u.slice(-1)):"\\".concat(u),this.options.pedantic&&(u=f?u:"[*+-]");let m=new RegExp("^( {0,3}".concat(u,")((?:[ ][^\\n]*)?(?:\\n|$))"));for(;a&&(z=!1,!(!(c=m.exec(a))||this.rules.block.hr.test(a)));){if(r=c[0],a=a.substring(r.length),v=c[2].split("\n",1)[0],g=a.split("\n",1)[0],this.options.pedantic?(i=2,d=v.trimLeft()):(i=c[2].search(/[^ ]/),i=i>4?1:i,d=v.slice(i),i+=c[1].length),n=!1,!v&&/^ *$/.test(g)&&(r+=g+"\n",a=a.substring(g.length+1),z=!0),!z){let w=new RegExp("^ {0,".concat(Math.min(3,i-1),"}(?:[*+-]|\\d{1,9}[.)])((?: [^\\n]*)?(?:\\n|$))")),H=new RegExp("^ {0,".concat(Math.min(3,i-1),"}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)")),y=new RegExp("^ {0,".concat(Math.min(3,i-1),"}(?:```|~~~)")),k=new RegExp("^ {0,".concat(Math.min(3,i-1),"}#"));for(;a&&(s=a.split("\n",1)[0],v=s,this.options.pedantic&&(v=v.replace(/^ {1,4}(?=( {4})*[^ ])/g," ")),!(y.test(v)||k.test(v)||w.test(v)||H.test(a)));){if(v.search(/[^ ]/)>=i||!v.trim())d+="\n"+v.slice(i);else if(!n)d+="\n"+v;else break;!n&&!v.trim()&&(n=!0),r+=s+"\n",a=a.substring(s.length+1)}}p.loose||(h?p.loose=!0:/\n *\n *$/.test(r)&&(h=!0)),this.options.gfm&&(e=/^\[[ xX]\] /.exec(d),e&&(l=e[0]!=="[ ] ",d=d.replace(/^\[[ xX]\] +/,""))),p.items.push({type:"list_item",raw:r,task:!!e,checked:l,loose:!1,text:d}),p.raw+=r}p.items[p.items.length-1].raw=r.trimRight(),p.items[p.items.length-1].text=d.trimRight(),p.raw=p.raw.trimRight();let M=p.items.length;for(o=0;o
\n":"'+(r?a:Z2(a,!0))+"
\n"}blockquote(a){return""+(r?a:Z2(a,!0))+"\n".concat(a,"
\n")}html(a){return a}heading(a,c,r,e){if(this.options.headerIds){let l=this.options.headerPrefix+e.slug(r);return"
\n":"
\n"}list(a,c,r){let e=c?"ol":"ul",l=c&&r!==1?' start="'+r+'"':"";return"<"+e+l+">\n"+a+""+e+">\n"}listitem(a){return"\n\n"+a+"\n"+c+"
\n"}tablerow(a){return"\n".concat(a," \n")}tablecell(a,c){let r=c.header?"th":"td";return(c.align?"<".concat(r,' align="').concat(c.align,'">'):"<".concat(r,">"))+a+"".concat(r,">\n")}strong(a){return"".concat(a,"")}em(a){return"".concat(a,"")}codespan(a){return"".concat(a,"")}br(){return this.options.xhtml?"
":"
"}del(a){return"".concat(a,"")}link(a,c,r){if(a=PI(this.options.sanitize,this.options.baseUrl,a),a===null)return r;let e='"+r+"",e}image(a,c,r){if(a=PI(this.options.sanitize,this.options.baseUrl,a),a===null)return r;let e='":">",e}text(a){return a}},vn=class{strong(a){return a}em(a){return a}codespan(a){return a}del(a){return a}html(a){return a}text(a){return a}link(a,c,r){return""+r}image(a,c,r){return""+r}br(){return""}},gn=class{constructor(){this.seen={}}serialize(a){return a.toLowerCase().trim().replace(/<[!\/a-z].*?>/ig,"").replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~]/g,"").replace(/\s/g,"-")}getNextSafeSlug(a,c){let r=a,e=0;if(this.seen.hasOwnProperty(r)){e=this.seen[a];do e++,r=a+"-"+e;while(this.seen.hasOwnProperty(r))}return c||(this.seen[a]=e,this.seen[r]=0),r}slug(a,c={}){let r=this.serialize(a);return this.getNextSafeSlug(r,c.dryrun)}},B5=class t{constructor(a){this.options=a||ht,this.options.renderer=this.options.renderer||new ur,this.renderer=this.options.renderer,this.renderer.options=this.options,this.textRenderer=new vn,this.slugger=new gn}static parse(a,c){return new t(c).parse(a)}static parseInline(a,c){return new t(c).parseInline(a)}parse(a,c=!0){let r="",e,l,i,o,n,h,v,g,s,d,z,u,f,p,m,M,w,H,y,k=a.length;for(e=0;e
"+Z2(c.message+"",!0)+"
";throw c}};V1.Parser=B5;V1.parser=B5.parse;V1.Renderer=ur;V1.TextRenderer=vn;V1.Lexer=Q6;V1.lexer=Q6.lex;V1.Tokenizer=zr;V1.Slugger=gn;V1.parse=V1;$y1=V1.options,Qy1=V1.setOptions,Xy1=V1.use,Yy1=V1.walkTokens,Jy1=V1.parseInline,tS1=B5.parse,aS1=Q6.lex});var jI,k51,dn,bu=x(()=>{"use strict";c1();gr();k51=B(w5)(jI||(jI=V(["\n padding: 6px;\n"]))),dn=k51});var u2,Fu,zn,Iu,NI,A51,UI,rP,KI,R51,$I,qI,QI,b51,F51,XI,I51,sn,c7,YI,P51,JI,G51,tP,T51,aP,Z51,cP,O51,eP,lP,Pu,vt=x(()=>{"use strict";u2=I(G());FI();c1();G1();M1();f1();_I();nt();bu();Fu=({title:t,message:a})=>"".concat(t," ").concat(a),zn=(()=>{let t=new Map;return{add:a=>{let c=Fu(a);t.has(c)?t.set(c,t.get(c)+1):t.set(c,1)},delete:a=>{let c=Fu(a);t.has(c)&&t.get(c)>1?t.set(c,t.get(c)-1):t.delete(c)},clear:()=>{t.clear()},check:a=>t.has(Fu(a))}})(),Iu=(()=>{let t=new Map;return{add:a=>{t.has(a)?t.set(a,t.get(a)+1):t.set(a,1)},delete:a=>{t.has(a)&&t.get(a)>1?t.set(a,t.get(a)-1):t.delete(a)},clear:()=>{t.clear()},check:a=>t.has(a),get types(){return Array.of(...t.keys())}}})(),A51=B.div(NI||(NI=V(["\n width: 100%;\n border-radius: 4px;\n display: flex;\n gap: 12px;\n ",";\n background-color: rgba(40, 43, 47, 0.8);\n box-shadow: 0 1px 1px rgba(0, 0, 0, 0.25), 0 2px 6px rgba(0, 0, 0, 0.15);\n backdrop-filter: blur(14px);\n\n @supports not (backdrop-filter: blur()) {\n background: rgba(40, 43, 47, 0.95);\n }\n"])),C1),rP=B.div(UI||(UI=V(["\n font-size: 14px;\n font-weight: bold;\n color: #fff;\n"]))),R51=B.div(KI||(KI=V(["\n flex: 1;\n flex-direction: column;\n width: 0;\n display: flex;\n padding: 16px 0;\n gap: 12px;\n"]))),qI=B.div($I||($I=V(["\n color: #b4b4b4;\n font-size: 12px;\n line-height: 1.4;\n\n a {\n color: rgba(255, 255, 255, 0.9);\n }\n\n em {\n font-style: italic;\n }\n\n strong {\n font-weight: bold;\n color: #d5d5d5;\n }\n\n p {\n margin-bottom: 8px;\n }\n\n code {\n font-family: monospace;\n background: rgba(0, 0, 0, 0.3);\n padding: 1px 1px 2px;\n border-radius: 4px;\n border: 1px solid rgba(255, 255, 255, 0.08);\n white-space: pre-wrap;\n }\n\n pre > code {\n white-space: pre;\n display: block;\n overflow: auto;\n padding: 4px;\n }\n\n pre {\n white-space: pre-wrap;\n margin-bottom: 8px;\n }\n"]))),b51=B.button(QI||(QI=V(["\n color: rgba(255, 255, 255, 0.9);\n font-weight: 500;\n display: flex;\n align-items: center;\n justify-content: center;\n background: none;\n border: none;\n padding-left: 12px;\n padding-right: 12px;\n border-left: 1px solid rgba(255, 255, 255, 0.05);\n\n &:hover {\n background: rgba(255, 255, 255, 0.05);\n }\n"]))),F51={info:"#3b82f6",success:"#10b981",warning:"#f59e0b",error:"#ef4444"},I51=B.div(XI||(XI=V(["\n display: flex;\n justify-content: center;\n margin-left: 12px;\n padding-top: 21px;\n\n ::before {\n content: '';\n width: 8px;\n height: 8px;\n border-radius: 999999px;\n background-color: ",";\n }\n"])),({type:t})=>F51[t]),sn=t=>(a,c,r=[],e=!1)=>{(e||!zn.check({title:a,message:c}))&&(zn.add({title:a,message:c}),Iu.add(t),ln.custom(l=>u2.default.createElement(A51,null,u2.default.createElement(I51,{type:t}),u2.default.createElement(R51,null,u2.default.createElement(rP,null,a),u2.default.createElement(qI,{dangerouslySetInnerHTML:{__html:V1.parse(c)}}),r.length>0&&u2.default.createElement(qI,null,u2.default.createElement("span",null,"Docs:"," ",r.map((i,o)=>u2.default.createElement(u2.Fragment,{key:o},o>0&&", ",u2.default.createElement("a",{target:"_blank",href:i.url},i.title)))))),u2.default.createElement(b51,{onClick:()=>{ln.remove(l.id),zn.delete({title:a,message:c}),Iu.delete(t)}},"Close")),{duration:1/0}))},c7={warning:sn("warning"),success:sn("success"),info:sn("info"),error:sn("error")},P51=B.div(YI||(YI=V(["\n display: flex;\n justify-content: ",";\n gap: 12px;\n"])),({align:t})=>t==="center"?"center":"flex-end"),G51=B.button(JI||(JI=V(["\n position: relative;\n border-radius: 4px;\n display: flex;\n align-items: center;\n gap: 12px;\n ",";\n background-color: rgba(40, 43, 47, 0.8);\n box-shadow: 0 1px 1px rgba(0, 0, 0, 0.25), 0 2px 6px rgba(0, 0, 0, 0.15);\n backdrop-filter: blur(14px);\n border: none;\n padding: 12px;\n color: #fff;\n overflow: hidden;\n\n ::before {\n content: '';\n position: absolute;\n inset: 0;\n }\n\n :hover::before {\n background: ",";\n }\n\n @supports not (backdrop-filter: blur()) {\n background: rgba(40, 43, 47, 0.95);\n }\n"])),C1,({danger:t})=>t?"rgba(255, 0, 0, 0.1)":"rgba(255, 255, 255, 0.1)"),T51=B.div(tP||(tP=V(["\n z-index: 10;\n display: flex;\n flex-direction: column;\n gap: 8px;\n position: fixed;\n right: 92px;\n top: 50px;\n width: 500px;\n height: 85vh;\n min-height: 400px;\n"]))),Z51=B.div(aP||(aP=V(["\n overflow: hidden;\n pointer-events: auto;\n border-radius: 4px;\n\n & > div {\n display: flex;\n flex-direction: column-reverse;\n gap: 8px;\n overflow: scroll;\n height: 100%;\n }\n"]))),O51=B.div(cP||(cP=V(["\n width: fit-content;\n padding: 8px;\n border-radius: 4px;\n display: flex;\n flex-direction: column;\n gap: 12px;\n color: #b4b4b4;\n font-size: 12px;\n line-height: 1.4;\n"]))),eP=()=>{let{hasNotifications:t}=Pu();return R3({enabled:!t},()=>u2.default.createElement(dn,null,u2.default.createElement(O51,null,u2.default.createElement(rP,null,"No notifications"),"Notifications will appear here when you get them.")))},lP=()=>{var l;let{toasts:t,handlers:a}=Ru(),{startPause:c,endPause:r}=a,e=(l=s1(T().atomP.ahistoric.pinNotifications))!=null?l:!1;return u2.default.createElement(T51,null,e?t.length>0&&u2.default.createElement(Z51,{onMouseEnter:c,onMouseLeave:r},u2.default.createElement("div",null,t.map(i=>u2.default.createElement("div",{key:i.id},i.message(i))))):null,u2.default.createElement(P51,{align:"side"},e&&t.length>0&&u2.default.createElement(G51,{onClick:()=>{Iu.clear(),zn.clear(),ln.remove()},danger:!0},"Clear")))},Pu=()=>{let{toasts:t}=Ru();return{hasNotifications:t.length>0}}});function pr(t,a){var o;let c=Object.values((o=(0,iP.val)(t.pointers.historic.sheetsById))!=null?o:{}),r=c.flatMap(n=>{var h;return Object.values((h=n==null?void 0:n.staticOverrides.byObject)!=null?h:{})}).flatMap(n=>Object.values(n!=null?n:{})),l=[...c.flatMap(n=>{var h,v;return Object.values((v=(h=n==null?void 0:n.sequence)==null?void 0:h.tracksByObject)!=null?v:{})}).flatMap(n=>{var h;return Object.values((h=n==null?void 0:n.trackData)!=null?h:{})}).flatMap(n=>n==null?void 0:n.keyframes).map(n=>n==null?void 0:n.value)];return r.forEach(n=>{q5(n,h=>{l.push(h)},[])}),l.filter(n=>(n==null?void 0:n.type)&&(a?(n==null?void 0:n.type)==a:typeof(n==null?void 0:n.type)=="string")).map(n=>n.id).filter((n,h,v)=>n!==null&&n!==""&&v.indexOf(n)===h)}var iP,Gu=x(()=>{"use strict";iP=require("@theatre/dataverse");de()});function oP(t,a){let c=new File([t],a),r=URL.createObjectURL(c),e=Object.assign(document.createElement("a"),{href:r,target:"_blank",rel:"noopener"});e.setAttribute("download",a),e.click(),setTimeout(()=>{URL.revokeObjectURL(r)},4e4)}var L0,gP,nP,E51,hP,D51,vP,W51,_51,dP,sP=x(()=>{"use strict";f1();e4();c4();L0=I(G());c1();Bu();SI();gP=I(AI());vt();Gu();E51=B.div(nP||(nP=V([""]))),D51=B.div(hP||(hP=V(["\n padding: 8px 10px;\n display: flex;\n flex-direction: column;\n align-items: stretch;\n"]))),W51=B(T2)(vP||(vP=V(["\n display flex;\n flex-direction: column;\n gap: 1em;\n width: 280px;\n padding: 1em;\n"])));_51=({projects:t})=>{let a=t[0],c=a.address.projectId,r=c.replace(/[^\w\d'_\-]+/g," ").trim(),e="".concat(r,".theatre-project-state.json"),[l,i]=(0,L0.useState)(!1),o=(0,L0.useCallback)(()=>e2(void 0,null,function*(){var s,d;let h=pr(a),v=new Map;try{yield Promise.all(h.map(z=>e2(void 0,null,function*(){let u=a.assetStorage.getAssetUrl(z),f=yield fetch(u);f.ok&&v.set(z,yield f.blob())})))}catch(z){c7.error("Failed to access assets","Export aborted. Failed to access assets at ".concat((d=(s=a.config.assets)==null?void 0:s.baseUrl)!=null?d:"/",". This is likely due to a CORS issue."));return}if(v.size>0){let z=new gP.default;for(let[f,p]of v)z.file(f,p);let u=yield z.generateAsync({type:"blob"});oP(u,"".concat(r,".assets.zip"))}let g=JSON.stringify(T().createContentOfSaveFile(a.address.projectId),null,2);oP(g,e),i(!0),setTimeout(()=>{i(!1)},2e3)}),[a,e]),n=x2({debugName:"ProjectDetails",pointerDistanceThreshold:50},()=>L0.default.createElement(W51,null,L0.default.createElement("p",null,"This will create a JSON file with the state of your project. You can commit this file to your git repo and include it in your production bundle."),L0.default.createElement("p",null,"If your project uses assets, this will also create a zip file with all the assets that you can unpack in your public folder."),L0.default.createElement("a",{href:"https://www.theatrejs.com/docs/latest/manual/projects#state",target:"_blank"},"Here is a quick guide on how to export to production.")));return L0.default.createElement(L0.default.Fragment,null,n.node,L0.default.createElement(E51,null,L0.default.createElement(yI,{projectId:c}),L0.default.createElement(D51,null,L0.default.createElement(vr,{onMouseEnter:h=>n.open(h,h.target),onClick:l?void 0:o,disabled:l},l?"(Exported)":"Export ".concat(c," to JSON")))))},dP=_51});var X6,zP,j51,uP,q51,pP,N51,mP,U51,K51,fP,MP=x(()=>{"use strict";X6=I(G());c1();b9();j51=B.div(zP||(zP=V(["\n padding: 16px;\n display: flex;\n flex-direction: column;\n gap: 24px;\n"]))),q51=B.div(uP||(uP=V(["\n display: flex;\n flex-direction: column;\n gap: 11px;\n color: rgba(255, 255, 255, 0.9);\n"]))),N51=B.div(pP||(pP=V(["\n color: rgba(145, 145, 145, 0.8);\n"]))),U51=B.a(mP||(mP=V(["\n color: #919191;\n font-size: 10px;\n text-decoration-color: #40434a;\n text-underline-offset: 3px;\n"]))),K51=()=>X6.default.createElement(j51,null,X6.default.createElement(q51,null,X6.default.createElement(N51,null,X6.default.createElement(Gc,null)),X6.default.createElement("div",null,"Please select an object from the ",X6.default.createElement("u",null,"Outline Menu")," to see its properties.")),X6.default.createElement(U51,{href:"https://www.theatrejs.com/docs/latest/manual/objects",target:"_blank"},"Learn more about Objects")),fP=K51});function mr(){let[t,a]=(0,un.useState)(!1),c=(0,un.useMemo)(()=>{let r=new Set;return()=>{let e=()=>{r.delete(e),a(r.size>0)};return r.add(e),a(!0),e}},[]);return[t,c]}var un,Tu=x(()=>{"use strict";un=I(G())});var O1,Y6,$51,HP,Zu,VP,xP,wP,CP,BP,LP,N9,Q51,yP,Ou,gt,US1,Io=x(()=>{"use strict";C5();M1();O1=I(G());c1();N5();b4();G1();gI();sP();f1();bz();Y6=require("@theatre/dataverse");MP();Tu();K6();$51="32px",Zu=B.div(HP||(HP=V(["\n ",";\n background-color: rgba(40, 43, 47, 0.8);\n position: fixed;\n right: 8px;\n top: 50px;\n // Temporary, see comment about CSS grid in SingleRowPropEditor.\n width: 280px;\n height: fit-content;\n z-index: ",";\n\n box-shadow: 0 1px 1px rgba(0, 0, 0, 0.25), 0 2px 6px rgba(0, 0, 0, 0.15);\n backdrop-filter: blur(14px);\n border-radius: 2px;\n\n display: ",";\n\n &:hover {\n display: block;\n }\n\n @supports not (backdrop-filter: blur()) {\n background: rgba(40, 43, 47, 0.95);\n }\n"])),C1,M5.propsPanel,({pin:t})=>t?"block":"none"),xP=B.div(VP||(VP=V(["\n margin: 0 10px;\n color: #919191;\n font-weight: 500;\n font-size: 10px;\n user-select: none;\n ",";\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n"])),C1),CP=B.div(wP||(wP=V(["\n height: ",";\n display: flex;\n align-items: center;\n"])),$51),LP=B.div(BP||(BP=V(["\n ",";\n max-height: calc(100vh - 100px);\n overflow-y: scroll;\n &::-webkit-scrollbar {\n display: none;\n }\n\n scrollbar-width: none;\n padding: 0;\n user-select: none;\n\n /* Set the font-size for input values in the detail panel */\n font-size: 12px;\n"])),C1),N9=(0,O1.createContext)([!1,()=>()=>{}]),Q51=t=>{let a=s1(T().atomP.ahistoric.pinDetails)!==!1,c=Dc("right");(0,O1.useLayoutEffect)(()=>{Ou.set(c)},[c]),(0,O1.useEffect)(()=>()=>{gt.set(!1),Ou.set(!1)},[]);let[r]=(0,O1.useContext)(N9),e=a||c||r,[l,i]=(0,O1.useState)(null);return _o(l),v1(()=>{let o=c3(),n=o.find(c0);if(n)return O1.default.createElement(Zu,{"data-testid":"DetailPanel-Object",pin:e,ref:i,onMouseEnter:()=>{gt.set(!0)},onMouseLeave:()=>{gt.set(!1)}},O1.default.createElement(CP,null,O1.default.createElement(xP,{title:"".concat(n.sheet.address.sheetId,": ").concat(n.sheet.address.sheetInstanceId," > ").concat(n.address.objectKey)},O1.default.createElement(x5,null,n.sheet.address.sheetId," "),O1.default.createElement(R9,null,":","\xA0"),O1.default.createElement(x5,null,n.sheet.address.sheetInstanceId," "),O1.default.createElement(R9,null,"\xA0\u2192\xA0"),O1.default.createElement(x5,null,n.address.objectKey))),O1.default.createElement(LP,null,O1.default.createElement(vI,{objects:[n]})));let h=o.find(se);return h?O1.default.createElement(Zu,{pin:e},O1.default.createElement(CP,null,O1.default.createElement(xP,{title:"".concat(h.address.projectId)},O1.default.createElement(x5,null,h.address.projectId," "))),O1.default.createElement(LP,null,O1.default.createElement(dP,{projects:[h]}))):O1.default.createElement(Zu,{pin:e,onMouseEnter:()=>{gt.set(!0)},onMouseLeave:()=>{gt.set(!1)}},O1.default.createElement(fP,null))},[e])},yP=()=>{let t=mr();return O1.default.createElement(N9.Provider,{value:t},O1.default.createElement(Q51,null))},Ou=new Y6.Atom(!1),gt=new Y6.Atom(!1),US1=(0,Y6.prism)(()=>{let t=(0,Y6.val)(gt.prism),a=(0,Y6.val)(Ou.prism);return t||a})});var pn,fr,dt,SP,D4,X51,mn,r7=x(()=>{"use strict";pn=require("@theatre/dataverse");M1();f1();Tu();fr=I(G());Ao();dt=(t,a)=>{let c=t.left/a.width,r=(t.left+t.width)/a.width,e=t.top/a.height,l=(t.height+t.top)/a.height;return{edges:{left:c<=.5?{from:"screenLeft",distance:c}:{from:"screenRight",distance:1-c},right:r<=.5?{from:"screenLeft",distance:r}:{from:"screenRight",distance:1-r},top:e<=.5?{from:"screenTop",distance:e}:{from:"screenBottom",distance:1-e},bottom:l<=.5?{from:"screenTop",distance:l}:{from:"screenBottom",distance:1-l}}}},SP=fr.default.createContext(null),D4=()=>(0,fr.useContext)(SP),X51=({panelId:t,children:a,defaultPosition:c,minDims:r})=>{let e=_9(800,200),[l,i]=mr(),{stuff:o}=v1(()=>{var p;let{edges:n}=(p=(0,pn.val)(T().atomP.historic.panelPositions[t]))!=null?p:c,h=Math.floor(e.width*(n.left.from==="screenLeft"?n.left.distance:1-n.left.distance)),v=Math.floor(e.width*(n.right.from==="screenLeft"?n.right.distance:1-n.right.distance)),g=Math.floor(e.height*(n.top.from==="screenTop"?n.top.distance:1-n.top.distance)),s=Math.floor(e.height*(n.bottom.from==="screenTop"?n.bottom.distance:1-n.bottom.distance)),d=Math.max(v-h,r.width),z=Math.max(s-g,r.height);return{stuff:{dims:pn.prism.memo("dims",()=>({width:d,left:h,top:g,height:z}),[d,h,g,z]),panelId:t,minDims:r,boundsHighlighted:l,addBoundsHighlightLock:i}}},[t,e,l,i]);return fr.default.createElement(SP.Provider,{value:o},a)},mn=X51});var e7,kP,Y51,J51,fn,Eu=x(()=>{"use strict";P1();f1();M2();e7=I(G());c1();r7();I0();H2();b4();Y51=B.div(kP||(kP=V(["\n cursor: move;\n"]))),J51=t=>{let a=D4(),c=(0,e7.useRef)(a);c.current=a;let[r,e]=z1(null),l=(0,e7.useMemo)(()=>({debugName:"PanelDragZone",lockCursorTo:"move",onDragStart(){let h=c.current,v,g=a.addBoundsHighlightLock();return{onDrag(s,d){let z=D(S({},h.dims),{top:b1(h.dims.top+d,0,window.innerHeight-S3),left:b1(h.dims.left+s,-h.dims.width+S3,window.innerWidth-S3)}),u=dt(z,{width:window.innerWidth,height:window.innerHeight});v==null||v.discard(),v=T().tempTransaction(({stateEditors:f})=>{f.studio.historic.panelPositions.setPanelPosition({position:u,panelId:h.panelId})})},onDragEnd(s){g(),s?v==null||v.commit():v==null||v.discard()}}}}),[]),[i]=S1(e,l);s2(i,"dragging","move");let[o,n]=(0,e7.useMemo)(()=>{let h;return[function(){if(h){let g=h;h=void 0,g()}h=a.addBoundsHighlightLock()},function(){if(h){let g=h;h=void 0,g()}}]},[]);return e7.default.createElement(Y51,D(S({},t),{ref:r,onMouseEnter:o,onMouseLeave:n}))},fn=J51});var st,RP,jP,bP,qP,FP,NP,IP,t61,PP,a61,GP,UP,TP,c61,ZP,r61,OP,Mn,EP,e61,DP,l61,WP,i61,_P,o61,n61,AP,h61,y5,KP=x(()=>{"use strict";P1();f1();M2();R0();st=I(G());c1();r7();G1();H2();b4();jP=B.div(RP||(RP=V(["\n position: absolute;\n ",";\n &:after {\n position: absolute;\n inset: -5px;\n display: block;\n content: ' ';\n }\n\n opacity: 0;\n background-color: #478698;\n\n &.isHighlighted {\n opacity: 0.7;\n }\n\n &.isDragging {\n opacity: 1;\n /* background-color: ","; */\n }\n\n &:hover {\n opacity: 1;\n }\n"])),C1,R6(.2,"#478698")),qP=B(jP)(bP||(bP=V(["\n /**\n The horizintal/vertical resize handles have z-index:-1 and are offset 1px outside of the panel\n to make sure they don't occlude any element that pops out of the panel (like the Playhead in SequenceEditorPanel).\n\n This means that panels will always need an extra 1px margin for their resize handles to be visible, but that's not a problem\n that we have to deal with right now (if it is at all a problem).\n \n */\n z-index: -1;\n"]))),NP=B(qP)(FP||(FP=V(["\n left: 0px;\n right: 0px;\n height: 1px;\n"]))),t61=B(NP)(IP||(IP=V(["\n top: -1px;\n"]))),a61=B(NP)(PP||(PP=V(["\n bottom: -1px;\n"]))),UP=B(qP)(GP||(GP=V(["\n z-index: -1;\n top: -1px;\n bottom: -1px;\n width: 1px;\n"]))),c61=B(UP)(TP||(TP=V(["\n left: -1px;\n"]))),r61=B(UP)(ZP||(ZP=V(["\n right: -1px;\n"]))),Mn=B(jP)(OP||(OP=V(["\n // The angles have z-index: 10 to make sure they _do_ occlude other elements in the panel.\n z-index: 10;\n width: 8px;\n height: 8px;\n"]))),e61=B(Mn)(EP||(EP=V(["\n top: 0;\n left: 0;\n"]))),l61=B(Mn)(DP||(DP=V(["\n top: 0;\n right: 0;\n"]))),i61=B(Mn)(WP||(WP=V(["\n bottom: 0;\n left: 0;\n"]))),o61=B(Mn)(_P||(_P=V(["\n bottom: 0;\n right: 0;\n"]))),n61={Top:t61,TopLeft:e61,TopRight:l61,Bottom:a61,BottomLeft:i61,BottomRight:o61,Left:c61,Right:r61},AP={Top:"ns-resize",Bottom:"ns-resize",Left:"ew-resize",Right:"ew-resize",TopLeft:"nw-resize",TopRight:"ne-resize",BottomLeft:"sw-resize",BottomRight:"se-resize"},h61=({which:t})=>{let a=D4(),c=(0,st.useRef)(a);c.current=a;let[r,e]=z1(null),l=(0,st.useMemo)(()=>({debugName:"PanelResizeHandle",lockCursorTo:AP[t],onDragStart(){let h,v=c.current,g=a.addBoundsHighlightLock();return{onDrag(s,d){let z=S({},v.dims);if(t.startsWith("Bottom"))z.height=Math.max(z.height+d,v.minDims.height);else if(t.startsWith("Top")){let f=z.top+z.height,p=b1(z.top+d,0,Math.min(f-v.minDims.height,window.innerHeight-S3)),m=f-p;z.height=m,z.top=p}if(t.endsWith("Left")){let f=z.left+z.width,p=Math.min(z.left+s,Math.min(f-v.minDims.width,window.innerWidth-S3)),m=f-p;z.width=m,z.left=p}else t.endsWith("Right")&&(z.width=Math.max(z.width+s,Math.max(v.minDims.width,S3-v.dims.left)));let u=dt(z,{width:window.innerWidth,height:window.innerHeight});h==null||h.discard(),h=T().tempTransaction(({stateEditors:f})=>{f.studio.historic.panelPositions.setPanelPosition({position:u,panelId:v.panelId})})},onDragEnd(s){g(),s?h==null||h.commit():h==null||h.discard()}}}}),[t]),[i]=S1(e,l),o=n61[t],n=t.length<=6;return st.default.createElement(o,{ref:r,className:[i?"isDragging":"",a.boundsHighlighted&&n?"isHighlighted":""].join(" "),style:{cursor:AP[t]}})},y5=h61});var i4,v61,$P,QP=x(()=>{"use strict";i4=I(G());KP();v61=t=>i4.default.createElement(i4.default.Fragment,null,i4.default.createElement(y5,{which:"Bottom"}),i4.default.createElement(y5,{which:"Top"}),i4.default.createElement(y5,{which:"Left"}),i4.default.createElement(y5,{which:"Right"}),i4.default.createElement(y5,{which:"TopLeft"}),i4.default.createElement(y5,{which:"TopRight"}),i4.default.createElement(y5,{which:"BottomLeft"}),i4.default.createElement(y5,{which:"BottomRight"})),$P=v61});var xn,XP,g61,d61,Cn,Du=x(()=>{"use strict";G1();xn=I(G());c1();r7();QP();g61=B.div(XP||(XP=V(["\n position: absolute;\n user-select: none;\n box-sizing: border-box;\n ",";\n /* box-shadow: 1px 2px 10px -5px black; */\n\n z-index: 1000;\n"])),C1),d61=xn.default.forwardRef((t,a)=>{let c=D4(),i=t,{style:r,children:e}=i,l=m4(i,["style","children"]);return xn.default.createElement(g61,D(S({ref:a},l),{style:S({width:c.dims.width+"px",height:c.dims.height+"px",top:c.dims.top+"px",left:c.dims.left+"px"},r!=null?r:{})}),xn.default.createElement($P,null),e)}),Cn=d61});var JP=L1((Ln,YP)=>{(function(t,a){typeof Ln=="object"&&typeof YP!="undefined"?a(Ln,G()):typeof define=="function"&&define.amd?define(["exports","react"],a):(t=typeof globalThis!="undefined"?globalThis:t||self,a(t.ReactErrorBoundary={},t.React))})(Ln,function(t,a){"use strict";function c(g){if(g&&g.__esModule)return g;var s=Object.create(null);return g&&Object.keys(g).forEach(function(d){if(d!=="default"){var z=Object.getOwnPropertyDescriptor(g,d);Object.defineProperty(s,d,z.get?z:{enumerable:!0,get:function(){return g[d]}})}}),s.default=g,Object.freeze(s)}var r=c(a);function e(g,s){return e=Object.setPrototypeOf||function(z,u){return z.__proto__=u,z},e(g,s)}function l(g,s){g.prototype=Object.create(s.prototype),g.prototype.constructor=g,e(g,s)}var i=function(s,d){return s===void 0&&(s=[]),d===void 0&&(d=[]),s.length!==d.length||s.some(function(z,u){return!Object.is(z,d[u])})},o={error:null},n=function(g){l(s,g);function s(){for(var z,u=arguments.length,f=new Array(u),p=0;p{"use strict";B2=I(G());c1();b4();r7();Eu();Du();iG=I(JP());K8();f1();b4();s61={edges:{left:{from:"screenLeft",distance:.3},right:{from:"screenRight",distance:.3},top:{from:"screenTop",distance:.3},bottom:{from:"screenBottom",distance:.3}}},z61={width:300,height:300},u61=({paneInstance:t})=>B2.default.createElement(mn,{panelId:"pane-".concat(t.instanceId),defaultPosition:s61,minDims:z61},B2.default.createElement(H61,{paneInstance:t})),p61=B(Cn)(tG||(tG=V(["\n display: flex;\n flex-direction: column;\n\n box-shadow: 0px 5px 12px -4px rgb(0 0 0 / 22%);\n z-index: ",";\n"])),M5.pluginPanes),m61=B.div(aG||(aG=V(["\n width: 100%;\n"]))),f61=B.div(cG||(cG=V(["\n display: flex;\n align-items: center;\n opacity: 1;\n position: absolute;\n right: 4px;\n top: 0;\n bottom: 0;\n"]))),M61=B.button(rG||(rG=V(["\n display: flex;\n align-items: center;\n justify-content: center;\n border-radius: 2px;\n font-size: 11px;\n height: 10px;\n width: 18px;\n color: #adadadb3;\n background: transparent;\n border: none;\n cursor: pointer;\n &:hover {\n color: white;\n }\n"]))),x61=B(YS)(eG||(eG=V(["\n position: relative;\n overflow: hidden;\n\n &:after {\n z-index: 10;\n position: absolute;\n inset: 0;\n display: block;\n content: ' ';\n pointer-events: none;\n\n #pointer-root:not(.normal) & {\n pointer-events: auto;\n }\n }\n"]))),C61=B.div(lG||(lG=V(["\n padding: 12px;\n\n & > pre {\n border: 1px solid #ff62624f;\n background-color: rgb(255 0 0 / 5%);\n margin: 8px 0;\n padding: 8px;\n font-family: monospace;\n overflow: scroll;\n color: #ff9896;\n }\n"]))),L61=t=>B2.default.createElement(C61,null,"An Error occurred rendering this pane. Open the console for more info.",B2.default.createElement("pre",null,JSON.stringify({message:t.error.message,stack:t.error.stack},null,2))),H61=({paneInstance:t})=>{let[a,c]=(0,B2.useState)(null),r=t.definition.mount;(0,B2.useLayoutEffect)(()=>{if(!a)return;let l=r({paneId:t.instanceId,node:a});if(typeof l=="function")return l},[a,r,t.instanceId]);let e=(0,B2.useCallback)(()=>{T().paneManager.destroyPane(t.instanceId)},[t]);return B2.default.createElement(p61,{"data-testid":"theatre-pane-wrapper-".concat(t.instanceId)},B2.default.createElement(fn,null,B2.default.createElement(oo,null,B2.default.createElement(f61,null,B2.default.createElement(M61,{onClick:e,title:"Close Pane"},B2.default.createElement(AA,null))),B2.default.createElement(m61,null,t.instanceId))),B2.default.createElement(iG.ErrorBoundary,{FallbackComponent:L61},B2.default.createElement(x61,{"data-testid":"theatre-pane-content-".concat(t.instanceId),ref:c})))},oG=u61});var Hn,Vn,Wu=x(()=>{"use strict";Hn=require("@theatre/dataverse"),Vn=(t,a)=>{let c=Hn.prism.memo(t,()=>new Hn.Atom(a),[]);return c.set(a),c}});function wn(t,a){(0,hG.useLayoutEffect)(()=>{if(!t||a.type!=="propWithChildren"&&a.type!=="primitiveProp"&&a.type!=="sheetObject")return;let c=null,r=D(S({},a.sheetObject.address),{pathToProp:a.type==="sheetObject"?[]:a.pathToProp});function e(){c=tt.replaceLock(r,()=>{})}function l(){c==null||c()}return t.addEventListener("mouseenter",e),t.addEventListener("mouseleave",l),()=>{c==null||c(),t.removeEventListener("mouseenter",e),t.removeEventListener("mouseleave",l)}},[t])}var hG,_u=x(()=>{"use strict";hG=I(G());Qo()});var S5,vG,ju,gG,qu,dG,pG,sG,V61,zG,w61,uG,B61,y61,zt,Mr=x(()=>{"use strict";G1();S5=I(G());K8();c1();N6();_u();ju=B.li(vG||(vG=V(["\n --depth: ",";\n margin: 0;\n padding: 0;\n list-style: none;\n"])),t=>t.depth),qu=B.div(gG||(gG=V(["\n border-bottom: 1px solid #7695b705;\n"]))),pG=B(qu)(dG||(dG=V(["\n padding-left: calc(8px + var(--depth) * 20px);\n\n display: flex;\n align-items: stretch;\n color: ",";\n\n box-sizing: border-box;\n\n ",";\n"])),Z6.panel.body.compoudThing.label.color,t=>t.isSelected&&"background: blue"),V61=B.span(sG||(sG=V(["\n ",";\n overflow-x: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n padding-right: 4px;\n line-height: 26px;\n flex-wrap: nowrap;\n\n ",":hover & {\n color: #ccc;\n }\n"])),T0,pG),w61=B.span(zG||(zG=V(["\n width: 12px;\n padding: 8px;\n font-size: 9px;\n display: flex;\n align-items: center;\n\n transition: transform 0.05s ease-out, color 0.1s ease-out;\n transform: rotateZ(","deg);\n color: #66686a;\n\n &:hover {\n transform: rotateZ(","deg);\n color: #c0c4c9;\n }\n"])),t=>t.isCollapsed?0:90,t=>t.isCollapsed?15:75),B61=B.ul(uG||(uG=V(["\n margin: 0;\n padding: 0;\n list-style: none;\n"]))),y61=({leaf:t,label:a,children:c,isSelectable:r,isSelected:e,toggleSelect:l,toggleCollapsed:i,isCollapsed:o})=>{let n=Array.isArray(c)&&c.length>0,h=(0,S5.useRef)(null);return wn(h.current,t),t.shouldRender?S5.default.createElement(ju,{depth:t.depth},S5.default.createElement(pG,{ref:h,style:{height:t.nodeHeight+"px"},isSelectable:r===!0,isSelected:e===!0,onClick:l,isEven:t.n%2===0},S5.default.createElement(w61,{isCollapsed:o,onClick:i},S5.default.createElement(Co,null)),S5.default.createElement(V61,null,a)),n&&S5.default.createElement(B61,null,c)):null},zt=y61});function mG(t,a){return a.every((c,r)=>c===t[r])}function fG(t,a){if(t.length!==a.length)return!1;for(let c=0;c{let e=()=>({debugName:"FocusRangeZone/focusRangeCreationGestureHandlers",onDragStart(i){let o,n=(0,v8.val)(t.clippedSpace.toUnitSpace),h=(0,v8.val)(t.scaledSpace.toUnitSpace),v=(0,v8.val)(t.sheet),g=v.getSequence(),d=i.target.getBoundingClientRect(),z=n(i.clientX-d.left),u=h(L2.rangeStripMinWidth);return{onDrag(f){let p=h(f),m=z,M=z+p;[m,M]=[b1(m,0,g.length),b1(M,0,g.length)].map(w=>g.closestGridPosition(w)),M