swf2js 0.1.2 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +81 -14
- package/package.json +11 -7
- package/studio/actionscript-roundtrip.test.js +54 -0
- package/studio/actionscript-scripts.test.js +169 -0
- package/studio/animated-image.test.js +137 -0
- package/studio/arithmetic.test.js +16 -0
- package/studio/as3-import.test.js +110 -0
- package/studio/audio-info.test.js +44 -0
- package/studio/components.test.js +152 -0
- package/studio/document-editing.test.js +92 -0
- package/studio/examples/01-space-mission.json +1628 -0
- package/studio/examples/02-clockwork-vault.json +1079 -0
- package/studio/examples/03-neon-synth.json +1364 -0
- package/studio/examples/04-kinetic-poster.json +923 -0
- package/studio/examples/05-signal-relay.json +1131 -0
- package/studio/examples/06-calculator.json +564 -0
- package/studio/frame-editing.test.js +129 -0
- package/studio/frame-events.test.js +117 -0
- package/studio/groups.test.js +88 -0
- package/studio/index.html +962 -0
- package/studio/interaction-triggers.test.js +37 -0
- package/studio/linked-actions.test.js +48 -0
- package/studio/lottie.test.js +208 -0
- package/studio/masks.test.js +43 -0
- package/studio/media-assets.test.js +62 -0
- package/studio/paint-tools.test.js +60 -0
- package/studio/playback.test.js +17 -0
- package/studio/project-io.test.js +405 -0
- package/studio/project-preview.test.js +475 -0
- package/studio/scene-transition.test.js +32 -0
- package/studio/server/archive-companions.js +27 -0
- package/studio/server/as3-library.js +91 -0
- package/studio/server/assets.js +162 -0
- package/studio/server/audio-info.js +82 -0
- package/studio/server/font-files.js +332 -0
- package/studio/server/http.js +135 -0
- package/studio/server/linked-actions.js +93 -0
- package/studio/server/png-decode.js +1 -0
- package/studio/server/project-movie.js +1164 -0
- package/studio/server/project-preview.js +152 -0
- package/studio/server/projects.js +370 -0
- package/studio/server/report.js +29 -0
- package/studio/server/routes.js +93 -0
- package/studio/server/swf-authoring.js +90 -0
- package/studio/server/swf-control-runtime.as +513 -0
- package/studio/server/swf-controls.js +119 -0
- package/studio/server/swf-export.js +293 -0
- package/studio/server/swf-import.js +1675 -0
- package/studio/server/swf-morphs.js +64 -0
- package/studio/server/swf-routes.js +42 -0
- package/studio/server/swf-streams.js +80 -0
- package/studio/server/swf-transition-runtime.as +52 -0
- package/studio/server/tween-recovery.js +106 -0
- package/studio/server-api.test.js +283 -0
- package/studio/server.js +320 -0
- package/studio/src/animated-image.js +423 -0
- package/studio/src/appearance-inspector.js +63 -0
- package/studio/src/arithmetic.js +50 -0
- package/studio/src/authored-controls.js +42 -0
- package/studio/src/busy.js +41 -0
- package/studio/src/canvas.js +430 -0
- package/studio/src/clipper-browser.js +2 -0
- package/studio/src/color-transform.js +38 -0
- package/studio/src/component-inspector.js +126 -0
- package/studio/src/components.js +268 -0
- package/studio/src/display-frame.js +262 -0
- package/studio/src/document-editing.js +69 -0
- package/studio/src/event-editor.js +150 -0
- package/studio/src/frame-editing.js +150 -0
- package/studio/src/frame-events.js +128 -0
- package/studio/src/frame-image.js +28 -0
- package/studio/src/groups.js +125 -0
- package/studio/src/handler-editor.js +122 -0
- package/studio/src/history.js +83 -0
- package/studio/src/imported-paths.js +99 -0
- package/studio/src/index.js +3582 -0
- package/studio/src/interaction-triggers.js +42 -0
- package/studio/src/json-patch.js +77 -0
- package/studio/src/layer-icons.js +25 -0
- package/studio/src/lottie-export.js +948 -0
- package/studio/src/lottie-import.js +1138 -0
- package/studio/src/masks.js +69 -0
- package/studio/src/media-assets.js +188 -0
- package/studio/src/media-library.js +193 -0
- package/studio/src/model.js +431 -0
- package/studio/src/numeric-fields.js +46 -0
- package/studio/src/object-list.js +57 -0
- package/studio/src/paint-tools.js +76 -0
- package/studio/src/placement-effects.js +74 -0
- package/studio/src/playback.js +10 -0
- package/studio/src/preview-audio.js +64 -0
- package/studio/src/preview-interactions.js +106 -0
- package/studio/src/preview-recorder.js +335 -0
- package/studio/src/preview-surface.js +338 -0
- package/studio/src/project-io.js +905 -0
- package/studio/src/project-session.js +375 -0
- package/studio/src/projects-dialog.js +319 -0
- package/studio/src/scene-transition.js +129 -0
- package/studio/src/script-editor.js +175 -0
- package/studio/src/script-references.js +74 -0
- package/studio/src/scripted-controls.js +146 -0
- package/studio/src/scripts.js +185 -0
- package/studio/src/stage-guides.js +101 -0
- package/studio/src/svg-animation.js +416 -0
- package/studio/src/svg-context.js +522 -0
- package/studio/src/svg-frame.js +413 -0
- package/studio/src/svg-import.js +1208 -0
- package/studio/src/swf-recording.js +104 -0
- package/studio/src/symbol-library.js +39 -0
- package/studio/src/symbols.js +62 -0
- package/studio/src/text-fields.js +58 -0
- package/studio/src/theme.js +43 -0
- package/studio/src/timeline.js +321 -0
- package/studio/src/vector-cut.js +103 -0
- package/studio/src/vector-geometry.js +254 -0
- package/studio/src/vector-style.js +146 -0
- package/studio/src/video-encode.js +84 -0
- package/studio/src/video-export.js +331 -0
- package/studio/src/video-mux.js +339 -0
- package/studio/src/video-playback.js +281 -0
- package/studio/src/workspace.js +344 -0
- package/studio/stroke-style.test.js +119 -0
- package/studio/styles.css +1547 -0
- package/studio/svg-export.test.js +162 -0
- package/studio/svg-import.test.js +318 -0
- package/studio/swf-authoring.test.js +140 -0
- package/studio/swf-export.test.js +324 -0
- package/studio/swf-import.test.js +489 -0
- package/studio/symbols.test.js +68 -0
- package/studio/tests/accessibility-interactions.mjs +138 -0
- package/studio/tests/appearance-interactions.mjs +103 -0
- package/studio/tests/control-interactions.mjs +60 -0
- package/studio/tests/event-interactions.mjs +117 -0
- package/studio/tests/external-resources.mjs +174 -0
- package/studio/tests/frame-image.mjs +71 -0
- package/studio/tests/html-export.mjs +68 -0
- package/studio/tests/import-files.mjs +131 -0
- package/studio/tests/lottie.mjs +125 -0
- package/studio/tests/mask-interactions.mjs +148 -0
- package/studio/tests/media-interactions.mjs +109 -0
- package/studio/tests/paint-interactions.mjs +64 -0
- package/studio/tests/project-interactions.mjs +244 -0
- package/studio/tests/script-interactions.mjs +178 -0
- package/studio/tests/scripted-control-interactions.mjs +107 -0
- package/studio/tests/svg-export.mjs +149 -0
- package/studio/tests/text-field-interactions.mjs +64 -0
- package/studio/tests/theme-interactions.mjs +53 -0
- package/studio/tests/timeline-browser.mjs +507 -0
- package/studio/tests/transition-interactions.mjs +94 -0
- package/studio/tests/trigger-interactions.mjs +93 -0
- package/studio/tests/video-export.mjs +243 -0
- package/studio/tests/workspace-interactions.mjs +226 -0
- package/studio/tween-recovery.test.js +31 -0
- package/studio/vector-style.test.js +56 -0
- package/studio/video-export.test.js +326 -0
- package/studiospec/actionscript.md +88 -0
- package/studiospec/architecture.md +378 -0
- package/studiospec/controls.md +100 -0
- package/studiospec/file-support.md +268 -0
- package/studiospec/lottie.md +69 -0
- package/studiospec/requirements.md +135 -0
- package/studiospec/stroke-style.md +95 -0
- package/studiospec/svg-export.md +83 -0
- package/studiospec/svg-import.md +139 -0
- package/studiospec/swooflib-integration.md +115 -0
- package/studiospec/tasks.md +573 -0
- package/studiospec/video-export.md +127 -0
- package/swf2js/__tests__/actionscript.test.js +1609 -0
- package/swf2js/__tests__/adpcm-audio.test.js +43 -0
- package/swf2js/__tests__/as2-compiler.test.js +153 -0
- package/swf2js/__tests__/as3-mixed-depth.test.js +498 -0
- package/swf2js/__tests__/authored-sprite-hit.test.js +118 -0
- package/swf2js/__tests__/authored-sprite-sizing.test.js +164 -0
- package/swf2js/__tests__/avm1-action-prefix.test.js +134 -0
- package/swf2js/__tests__/avm1-attach-movie.test.js +1151 -0
- package/swf2js/__tests__/avm1-boxhead-budget.test.js +73 -0
- package/swf2js/__tests__/avm1-cfg-bubble-tanks.test.js +101 -0
- package/swf2js/__tests__/avm1-cfg-mario-kart.test.js +184 -0
- package/swf2js/__tests__/avm1-cfg-mario.test.js +31 -0
- package/swf2js/__tests__/avm1-cfg-pacman.test.js +49 -0
- package/swf2js/__tests__/avm1-checkers-gameplay.test.js +122 -0
- package/swf2js/__tests__/avm1-clip-actions.test.js +2002 -0
- package/swf2js/__tests__/avm1-clone-drag.test.js +626 -0
- package/swf2js/__tests__/avm1-decompiler.test.js +102 -0
- package/swf2js/__tests__/avm1-dynamic-locals.test.js +159 -0
- package/swf2js/__tests__/avm1-formal-parameters.test.js +71 -0
- package/swf2js/__tests__/avm1-key-events.test.js +52 -0
- package/swf2js/__tests__/avm1-load-bitmap.test.js +75 -0
- package/swf2js/__tests__/avm1-loading-host-actions.test.js +764 -0
- package/swf2js/__tests__/avm1-multibyte-strings.test.js +63 -0
- package/swf2js/__tests__/avm1-pacman-gameplay.test.js +115 -0
- package/swf2js/__tests__/avm1-shape-hittest.test.js +311 -0
- package/swf2js/__tests__/avm1-shared-bodies.test.js +57 -0
- package/swf2js/__tests__/avm1-shared-runtime.test.js +1364 -0
- package/swf2js/__tests__/avm1-snake-gameplay.test.js +139 -0
- package/swf2js/__tests__/avm1-super.test.js +70 -0
- package/swf2js/__tests__/avm1-target-path.test.js +325 -0
- package/swf2js/__tests__/avm1-try.test.js +229 -0
- package/swf2js/__tests__/avm2-activation-closures.test.js +65 -0
- package/swf2js/__tests__/avm2-applytype.test.js +180 -0
- package/swf2js/__tests__/avm2-call-ops.test.js +232 -0
- package/swf2js/__tests__/avm2-callsuperid.test.js +231 -0
- package/swf2js/__tests__/avm2-class-initializer.test.js +219 -0
- package/swf2js/__tests__/avm2-custom-namespace.test.js +139 -0
- package/swf2js/__tests__/avm2-describe-type.test.js +96 -0
- package/swf2js/__tests__/avm2-dictionary.test.js +96 -0
- package/swf2js/__tests__/avm2-domain-memory.test.js +332 -0
- package/swf2js/__tests__/avm2-e4x.test.js +326 -0
- package/swf2js/__tests__/avm2-exceptions.test.js +81 -0
- package/swf2js/__tests__/avm2-findprop.test.js +110 -0
- package/swf2js/__tests__/avm2-getlex.test.js +166 -0
- package/swf2js/__tests__/avm2-global-slot.test.js +106 -0
- package/swf2js/__tests__/avm2-interface.test.js +95 -0
- package/swf2js/__tests__/avm2-multiname-precedence.test.js +148 -0
- package/swf2js/__tests__/avm2-named-namespace-types.test.js +106 -0
- package/swf2js/__tests__/avm2-optional-args.test.js +100 -0
- package/swf2js/__tests__/avm2-outer-scopes.test.js +101 -0
- package/swf2js/__tests__/avm2-package-internal-class.test.js +106 -0
- package/swf2js/__tests__/avm2-protected-namespace.test.js +105 -0
- package/swf2js/__tests__/avm2-protected.test.js +214 -0
- package/swf2js/__tests__/avm2-qwop-gameplay.test.js +116 -0
- package/swf2js/__tests__/avm2-runtime-namespaces.test.js +159 -0
- package/swf2js/__tests__/avm2-script-traits.test.js +89 -0
- package/swf2js/__tests__/avm2-shared-runtime.test.js +52 -0
- package/swf2js/__tests__/avm2-slot-ops.test.js +117 -0
- package/swf2js/__tests__/avm2-type-ops.test.js +224 -0
- package/swf2js/__tests__/bevel-filter.test.js +116 -0
- package/swf2js/__tests__/bitmap-button-mask.test.js +106 -0
- package/swf2js/__tests__/bitmap-data-draw.test.js +388 -0
- package/swf2js/__tests__/bitmap-decoder.test.js +108 -0
- package/swf2js/__tests__/bitmapdata-color-bounds.test.js +70 -0
- package/swf2js/__tests__/bitmapdata-copy-channel.test.js +91 -0
- package/swf2js/__tests__/bitmapdata-copy-pixels.test.js +136 -0
- package/swf2js/__tests__/bitmapdata-fill-compare.test.js +241 -0
- package/swf2js/__tests__/bitmapdata-filter.test.js +232 -0
- package/swf2js/__tests__/bitmapdata-hit-test.test.js +71 -0
- package/swf2js/__tests__/bitmapdata-merge.test.js +84 -0
- package/swf2js/__tests__/bitmapdata-palette-map.test.js +92 -0
- package/swf2js/__tests__/bitmapdata-pixels-io.test.js +198 -0
- package/swf2js/__tests__/bitmapdata-threshold.test.js +97 -0
- package/swf2js/__tests__/bitmapdata-vector.test.js +82 -0
- package/swf2js/__tests__/blur-filter.test.js +48 -0
- package/swf2js/__tests__/bundle-emitter.test.js +394 -0
- package/swf2js/__tests__/button-actions.test.js +370 -0
- package/swf2js/__tests__/button-color-transform.test.js +48 -0
- package/swf2js/__tests__/button-decoder.test.js +106 -0
- package/swf2js/__tests__/button-hit-test.test.js +825 -0
- package/swf2js/__tests__/button-scaling-grid.test.js +124 -0
- package/swf2js/__tests__/button-sound.test.js +105 -0
- package/swf2js/__tests__/bytearray-coercion.test.js +23 -0
- package/swf2js/__tests__/bytearray-object-serialization.test.js +380 -0
- package/swf2js/__tests__/cfg-switch-loop.test.js +103 -0
- package/swf2js/__tests__/clip-depth-mask.test.js +119 -0
- package/swf2js/__tests__/clipped-bitmap-fill.test.js +118 -0
- package/swf2js/__tests__/companion-swf.test.js +638 -0
- package/swf2js/__tests__/context-menu.test.js +149 -0
- package/swf2js/__tests__/convolution-filter.test.js +74 -0
- package/swf2js/__tests__/definefont4.test.js +280 -0
- package/swf2js/__tests__/display-displacement.test.js +161 -0
- package/swf2js/__tests__/display-list.test.js +80 -0
- package/swf2js/__tests__/display-mask-render.test.js +656 -0
- package/swf2js/__tests__/displayobject-stage.test.js +320 -0
- package/swf2js/__tests__/embedded-script-audio.test.js +131 -0
- package/swf2js/__tests__/embedded-swf.test.js +202 -0
- package/swf2js/__tests__/embedded-textfield.test.js +107 -0
- package/swf2js/__tests__/embedded-timeline-audio.test.js +182 -0
- package/swf2js/__tests__/embedded-timeline-input.test.js +420 -0
- package/swf2js/__tests__/embedded-timer-lifecycle.test.js +145 -0
- package/swf2js/__tests__/event-priority-order.test.js +125 -0
- package/swf2js/__tests__/event-weak-listeners.test.js +53 -0
- package/swf2js/__tests__/event-will-trigger.test.js +43 -0
- package/swf2js/__tests__/flash-text-engine-content.test.js +115 -0
- package/swf2js/__tests__/flash-text-engine-format.test.js +95 -0
- package/swf2js/__tests__/flash-text-engine-line.test.js +314 -0
- package/swf2js/__tests__/font-encoder.test.js +95 -0
- package/swf2js/__tests__/font-outline-text.test.js +659 -0
- package/swf2js/__tests__/glow-shadow-filter.test.js +68 -0
- package/swf2js/__tests__/graphics-bitmap-smoothing.test.js +32 -0
- package/swf2js/__tests__/graphics-fill-lifetime.test.js +36 -0
- package/swf2js/__tests__/graphics-gradient-matrix.test.js +53 -0
- package/swf2js/__tests__/graphics-stroke-hit-test.test.js +457 -0
- package/swf2js/__tests__/hit-test-primitives.test.js +414 -0
- package/swf2js/__tests__/input-events.test.js +714 -0
- package/swf2js/__tests__/integration/corpus.test.js +41 -0
- package/swf2js/__tests__/loader-embedded-swf.test.js +210 -0
- package/swf2js/__tests__/loader-info.test.js +81 -0
- package/swf2js/__tests__/local-connection.test.js +122 -0
- package/swf2js/__tests__/morph-focal-gradient.test.js +51 -0
- package/swf2js/__tests__/morph-topology.test.js +267 -0
- package/swf2js/__tests__/movie-data-codec.test.js +128 -0
- package/swf2js/__tests__/nellymoser-audio.test.js +84 -0
- package/swf2js/__tests__/opaque-background-cache.test.js +352 -0
- package/swf2js/__tests__/path-stream.test.js +81 -0
- package/swf2js/__tests__/place-object-filters.test.js +88 -0
- package/swf2js/__tests__/place-object3-decoder.test.js +116 -0
- package/swf2js/__tests__/place-object3-image.test.js +85 -0
- package/swf2js/__tests__/player-version.test.js +46 -0
- package/swf2js/__tests__/root-textfield.test.js +287 -0
- package/swf2js/__tests__/scaling-grid.test.js +183 -0
- package/swf2js/__tests__/shape-decoder.test.js +361 -0
- package/swf2js/__tests__/shape-line-style2.test.js +138 -0
- package/swf2js/__tests__/shape-nonscaling-stroke.test.js +131 -0
- package/swf2js/__tests__/shape-pixel-hint.test.js +101 -0
- package/swf2js/__tests__/simplebutton-pointer.test.js +1477 -0
- package/swf2js/__tests__/socket-offline.test.js +67 -0
- package/swf2js/__tests__/sound-avm1-stop.test.js +99 -0
- package/swf2js/__tests__/sound-envelope.test.js +110 -0
- package/swf2js/__tests__/sound-extract.test.js +168 -0
- package/swf2js/__tests__/sound-id3.test.js +283 -0
- package/swf2js/__tests__/sound-load.test.js +259 -0
- package/swf2js/__tests__/sound-mixer-spectrum.test.js +261 -0
- package/swf2js/__tests__/sound-stream-sprite.test.js +624 -0
- package/swf2js/__tests__/sound-transform.test.js +104 -0
- package/swf2js/__tests__/speex-audio.test.js +77 -0
- package/swf2js/__tests__/stage-noscale.test.js +45 -0
- package/swf2js/__tests__/swf-encoder.test.js +134 -0
- package/swf2js/__tests__/swflib-assemble.test.js +20 -0
- package/swf2js/__tests__/textfield-html-text.test.js +368 -0
- package/swf2js/__tests__/textfield-line-layout.test.js +339 -0
- package/swf2js/__tests__/textfield-programmatic-overlay.test.js +2506 -0
- package/swf2js/__tests__/textfield-scroll.test.js +79 -0
- package/swf2js/__tests__/textfield-selection.test.js +383 -0
- package/swf2js/__tests__/timeline-effect-surfaces.test.js +295 -0
- package/swf2js/__tests__/timeline-named-anchor.test.js +139 -0
- package/swf2js/__tests__/timeline-scenes.test.js +1723 -0
- package/swf2js/__tests__/urlloader-http-status.test.js +236 -0
- package/{src → swf2js}/cli.js +43 -11
- package/swf2js/compiler/as2-classes.js +156 -0
- package/swf2js/compiler/as2-parser.js +598 -0
- package/swf2js/compiler/avm1-codegen.js +897 -0
- package/swf2js/compiler/index.js +28 -0
- package/{src → swf2js}/decoder/button-decoder.js +3 -1
- package/swf2js/decoder/png.js +114 -0
- package/{src → swf2js}/decoder/shape-decoder.js +20 -10
- package/{src → swf2js}/decoder/tag-decoder.js +5 -3
- package/{src → swf2js}/decoder/tag-types.js +4 -0
- package/swf2js/decompiler/avm1-decompiler.js +1138 -0
- package/{src → swf2js}/emitter/asset-encoder.js +66 -113
- package/{src → swf2js}/emitter/bundle-emitter.js +209 -78
- package/swf2js/emitter/external-resources.js +39 -0
- package/swf2js/emitter/movie-data-codec.js +91 -0
- package/swf2js/encoder/bit-writer.js +182 -0
- package/swf2js/encoder/shape-encoder.js +310 -0
- package/swf2js/encoder/swf-builder.js +639 -0
- package/swf2js/encoder/swf-writer.js +55 -0
- package/{src/runtime/swflib/assemble.js → swf2js/runtime/assemble-swooflib.js} +4 -3
- package/{src → swf2js}/runtime/avm1-runtime.js +102 -63
- package/{src → swf2js}/runtime/index.js +1 -1
- package/{src → swf2js}/runtime/movie-runtime.js +28 -2
- package/{src → swf2js}/transpiler/actionscript.js +82 -19
- package/{src → swf2js}/transpiler/avm1/avm1-opcodes.js +5 -3
- package/{src → swf2js}/transpiler/avm1/avm1-transpiler.js +69 -6
- package/{src → swf2js}/transpiler/avm2/avm2-transpiler.js +1 -1
- package/{src → swf2js}/transpiler/timeline/display-list.js +41 -22
- package/{src → swf2js}/transpiler/timeline/timeline-codegen.js +97 -36
- package/swooflib/README.md +569 -0
- package/swooflib/adpcm.js +147 -0
- package/{src/runtime/swflib → swooflib}/builtins.js +6 -0
- package/{src/runtime/swflib → swooflib}/context-menu.js +7 -1
- package/swooflib/control-definitions.js +42 -0
- package/swooflib/control-widget.js +763 -0
- package/swooflib/controls.js +300 -0
- package/{src/runtime/swflib → swooflib}/display.js +16 -10
- package/{src/runtime/swflib → swooflib}/events.js +11 -0
- package/{src/runtime/swflib → swooflib}/flash.js +6 -5
- package/{src/runtime/swflib → swooflib}/graphics.js +81 -19
- package/{src/runtime/swflib → swooflib}/input.js +12 -14
- package/{src/runtime/swflib → swooflib}/loader.js +52 -22
- package/swooflib/movie-network.js +86 -0
- package/swooflib/path-stream.js +169 -0
- package/{src/runtime/swflib → swooflib}/render.js +3 -13
- package/{src/runtime/swflib → swooflib}/sound.js +25 -2
- package/{src/runtime/swflib → swooflib}/stage.js +3 -3
- package/swooflib/stream-time.js +21 -0
- package/{src/runtime/swflib → swooflib}/system.js +88 -37
- package/{src/runtime/swflib → swooflib}/text-paint.js +14 -3
- package/{src/runtime/swflib → swooflib}/text.js +8 -0
- package/swooflib/xml-node.js +53 -0
- package/src/emitter/timeline-data-codec.js +0 -58
- /package/{src → swf2js}/decoder/symbol-table.js +0 -0
- /package/{src → swf2js}/emitter/embedded-swf.js +0 -0
- /package/{src → swf2js}/emitter/font-encoder.js +0 -0
- /package/{src → swf2js}/model/swf-document.js +0 -0
- /package/{src → swf2js}/model/transpile-result.js +0 -0
- /package/{src → swf2js}/parser/bit-reader.js +0 -0
- /package/{src → swf2js}/parser/decompressor.js +0 -0
- /package/{src → swf2js}/parser/swf-parser.js +0 -0
- /package/{src → swf2js}/pretty-printer/pretty-printer.js +0 -0
- /package/{src → swf2js}/runtime/avm2-runtime.js +0 -0
- /package/{src → swf2js}/runtime/embedded-movie-runtime.js +0 -0
- /package/{src → swf2js}/transpiler/avm1/avm1-ir.js +0 -0
- /package/{src → swf2js}/transpiler/avm1/avm1-rewrite.js +0 -0
- /package/{src → swf2js}/transpiler/avm2/abc-reader.js +0 -0
- /package/{src → swf2js}/transpiler/cfg-structurer.js +0 -0
- /package/{src → swf2js}/util/diagnostics.js +0 -0
- /package/{src → swf2js}/util/logger.js +0 -0
- /package/{src/runtime/swflib → swooflib}/bitmap-image.js +0 -0
- /package/{src/runtime/swflib → swooflib}/bitmap.js +0 -0
- /package/{src/runtime/swflib → swooflib}/bytearray.js +0 -0
- /package/{src/runtime/swflib → swooflib}/compiled-swf.js +0 -0
- /package/{src/runtime/swflib → swooflib}/cursor-flag.js +0 -0
- /package/{src/runtime/swflib → swooflib}/dictionary.js +0 -0
- /package/{src/runtime/swflib → swooflib}/filters.js +0 -0
- /package/{src/runtime/swflib → swooflib}/geom.js +0 -0
- /package/{src/runtime/swflib → swooflib}/glyph-metrics.js +0 -0
- /package/{src/runtime/swflib → swooflib}/host.js +0 -0
- /package/{src/runtime/swflib → swooflib}/inherit.js +0 -0
- /package/{src/runtime/swflib → swooflib}/marks.js +0 -0
- /package/{src/runtime/swflib → swooflib}/matrix3d.js +0 -0
- /package/{src/runtime/swflib → swooflib}/pointer-bridge.js +0 -0
- /package/{src/runtime/swflib → swooflib}/projection.js +0 -0
- /package/{src/runtime/swflib → swooflib}/sprite-drag.js +0 -0
- /package/{src/runtime/swflib → swooflib}/stage-ref.js +0 -0
- /package/{src/runtime/swflib → swooflib}/text-field.js +0 -0
- /package/{src/runtime/swflib → swooflib}/transform.js +0 -0
- /package/{src/runtime/swflib → swooflib}/xml.js +0 -0
|
@@ -0,0 +1,3582 @@
|
|
|
1
|
+
import { controlDefinitions, CONTROL_KINDS, defaultControlParameters } from '../../swooflib/control-definitions.js';
|
|
2
|
+
import { readControl } from './authored-controls.js';
|
|
3
|
+
import { bindPreviewInteractions } from './preview-interactions.js';
|
|
4
|
+
import { bindingKeys, isKeyTrigger } from './interaction-triggers.js';
|
|
5
|
+
import { createSceneTransition, createTransitionInspector } from './scene-transition.js';
|
|
6
|
+
import { setPoseAtFrame, setNumericPoseAtFrame, setStageNumber, setStartFrame, removeObjects, removeProjectScene } from './document-editing.js';
|
|
7
|
+
import { createMediaLibrary } from './media-library.js';
|
|
8
|
+
import { createProjectSession } from './project-session.js';
|
|
9
|
+
import { projectHasSound, swfPlayerReasons } from './video-playback.js';
|
|
10
|
+
import { createProjectsUi } from './projects-dialog.js';
|
|
11
|
+
import { createPreviewAudio } from './preview-audio.js';
|
|
12
|
+
import { decodeAsset } from './media-assets.js';
|
|
13
|
+
import { createEventEditor } from './event-editor.js';
|
|
14
|
+
import { applyScriptDrafts, createScriptEditor, editAttachedScript } from './script-editor.js';
|
|
15
|
+
import { scriptReferenceWarnings } from './script-references.js';
|
|
16
|
+
import { editorFieldFont, fieldText, isEditableText, materializeHtmlText, syncEmbeddedFonts } from './text-fields.js';
|
|
17
|
+
import { createHandlerEditor } from './handler-editor.js';
|
|
18
|
+
import { createEventDispatcher, objectAction } from './frame-events.js';
|
|
19
|
+
import { maskCandidates } from './masks.js';
|
|
20
|
+
import { createAppearanceInspector } from './appearance-inspector.js';
|
|
21
|
+
import { paintHints, anchor, isVector, eraseArtwork, fillEnclosedArea, gradientDrag, paintStroke } from './paint-tools.js';
|
|
22
|
+
import { hasVectorFill, readAppearance, shapePropertyValue } from './vector-style.js';
|
|
23
|
+
import { groupMembers, groupElements, ungroupElements, reorderElements, groupTransformSources, transformMembers } from './groups.js';
|
|
24
|
+
import { createSymbolLibrary } from './symbol-library.js';
|
|
25
|
+
import { scopedId } from './symbols.js';
|
|
26
|
+
import { renderObjects } from './object-list.js';
|
|
27
|
+
import {
|
|
28
|
+
createCanvasRenderer,
|
|
29
|
+
rotationHandleWorld,
|
|
30
|
+
stageUnitsPerCssPixel,
|
|
31
|
+
transformHandles,
|
|
32
|
+
} from './canvas.js';
|
|
33
|
+
import { layerIcon } from './layer-icons.js';
|
|
34
|
+
import { createTimeline } from './timeline.js';
|
|
35
|
+
import { createHistory } from './history.js';
|
|
36
|
+
import { startBusy } from './busy.js';
|
|
37
|
+
import { createComponentInspector } from './component-inspector.js';
|
|
38
|
+
import { startTrack, editTrack, keyLayer, resizeScene, editSceneFrame } from './frame-editing.js';
|
|
39
|
+
import { advancePlayhead } from './playback.js';
|
|
40
|
+
import {
|
|
41
|
+
projectDocument,
|
|
42
|
+
serializeProject,
|
|
43
|
+
parseProjectJson,
|
|
44
|
+
nextIdSequenceForProject,
|
|
45
|
+
validateButtonAction,
|
|
46
|
+
} from './project-io.js';
|
|
47
|
+
import {
|
|
48
|
+
poseAt,
|
|
49
|
+
ensureKeyframe,
|
|
50
|
+
visibleAt,
|
|
51
|
+
matrixComponents,
|
|
52
|
+
pointToLocal,
|
|
53
|
+
pointToWorld,
|
|
54
|
+
orderedSceneLayers,
|
|
55
|
+
orderedSceneElements,
|
|
56
|
+
selectionBounds,
|
|
57
|
+
findElementLayer,
|
|
58
|
+
isElementLocked,
|
|
59
|
+
addLayerToScene,
|
|
60
|
+
renameSceneLayer,
|
|
61
|
+
reorderSceneLayer,
|
|
62
|
+
removeSceneLayer,
|
|
63
|
+
moveElementToLayer,
|
|
64
|
+
} from './model.js';
|
|
65
|
+
|
|
66
|
+
const controlMenu = document.querySelector('.control-tools-menu');
|
|
67
|
+
for (const kind of CONTROL_KINDS) {
|
|
68
|
+
const button = document.createElement('button');
|
|
69
|
+
button.type = 'button';
|
|
70
|
+
button.dataset.tool = kind;
|
|
71
|
+
button.textContent = controlDefinitions[kind].label;
|
|
72
|
+
controlMenu.append(button);
|
|
73
|
+
}
|
|
74
|
+
const paintOptions = document.querySelector('#paint-options');
|
|
75
|
+
const paintColor = document.querySelector('#paint-color');
|
|
76
|
+
const paintSize = document.querySelector('#paint-size');
|
|
77
|
+
let sampledGradient = null;
|
|
78
|
+
paintColor.addEventListener('input', () => { sampledGradient = null; });
|
|
79
|
+
|
|
80
|
+
const history = createHistory();
|
|
81
|
+
const DEFAULT_DURATION = 120;
|
|
82
|
+
const project = {
|
|
83
|
+
stage: {
|
|
84
|
+
width: 800,
|
|
85
|
+
height: 450,
|
|
86
|
+
frameRate: 24,
|
|
87
|
+
background: '#101820',
|
|
88
|
+
},
|
|
89
|
+
scenes: [],
|
|
90
|
+
symbols: [],
|
|
91
|
+
assets: [],
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
let idSequence = 0;
|
|
95
|
+
let selectedSceneId = null;
|
|
96
|
+
let selectedLayerId = null;
|
|
97
|
+
let returnViews = [];
|
|
98
|
+
let preferredSymbol;
|
|
99
|
+
const symbolClocks = new Map();
|
|
100
|
+
const eventDispatcher = createEventDispatcher();
|
|
101
|
+
let previewOrigin;
|
|
102
|
+
let selectedElementIds = [];
|
|
103
|
+
let pendingLayerDeleteId = null;
|
|
104
|
+
let editingLayerId = null;
|
|
105
|
+
let playhead = 1;
|
|
106
|
+
let playing = false;
|
|
107
|
+
let previewMode = false;
|
|
108
|
+
let hoveredButtonId = null;
|
|
109
|
+
let pressedButtonId = null;
|
|
110
|
+
const previewHiddenIds = new Set();
|
|
111
|
+
let lastTick = null;
|
|
112
|
+
let timeAccumulator = 0;
|
|
113
|
+
let animationRequest = 0;
|
|
114
|
+
let dragState = null;
|
|
115
|
+
let pendingPath = null;
|
|
116
|
+
let activeTool = 'select';
|
|
117
|
+
let editingTextElementId = null;
|
|
118
|
+
let originalTextDuringEdit = null;
|
|
119
|
+
let statusTimeout = 0;
|
|
120
|
+
let sampleRequest;
|
|
121
|
+
|
|
122
|
+
const elements = {
|
|
123
|
+
undo: document.querySelector('#undo'),
|
|
124
|
+
redo: document.querySelector('#redo'),
|
|
125
|
+
canvas: document.querySelector('#stage'),
|
|
126
|
+
stageMat: document.querySelector('.stage-mat'),
|
|
127
|
+
sceneList: document.querySelector('#scene-list'),
|
|
128
|
+
layerList: document.querySelector('#layer-list'),
|
|
129
|
+
addLayer: document.querySelector('#add-layer'),
|
|
130
|
+
layerDeletePrompt: document.querySelector('#layer-delete-prompt'),
|
|
131
|
+
layerDeleteMessage: document.querySelector('#layer-delete-message'),
|
|
132
|
+
layerDeleteTarget: document.querySelector('#layer-delete-target'),
|
|
133
|
+
layerDeleteMove: document.querySelector('#layer-delete-move'),
|
|
134
|
+
layerDeleteAll: document.querySelector('#layer-delete-all'),
|
|
135
|
+
layerDeleteCancel: document.querySelector('#layer-delete-cancel'),
|
|
136
|
+
groupObjects: document.querySelector('#group-objects'),
|
|
137
|
+
ungroupObjects: document.querySelector('#ungroup-objects'),
|
|
138
|
+
raiseObjects: document.querySelector('#raise-objects'),
|
|
139
|
+
lowerObjects: document.querySelector('#lower-objects'),
|
|
140
|
+
objectHint: document.querySelector('#object-selection-hint'),
|
|
141
|
+
elementList: document.querySelector('#element-list'),
|
|
142
|
+
elementCount: document.querySelector('#element-count'),
|
|
143
|
+
emptyElements: document.querySelector('#empty-elements'),
|
|
144
|
+
emptyStage: document.querySelector('#empty-stage'),
|
|
145
|
+
sceneName: document.querySelector('#scene-name'),
|
|
146
|
+
sceneDuration: document.querySelector('#scene-duration'),
|
|
147
|
+
sceneLoop: document.querySelector('#scene-loop'),
|
|
148
|
+
inputText: document.querySelector('#input-text'),
|
|
149
|
+
sceneStartFrame: document.querySelector('#scene-start-frame'),
|
|
150
|
+
stageWidth: document.querySelector('#stage-width'),
|
|
151
|
+
stageHeight: document.querySelector('#stage-height'),
|
|
152
|
+
stageFps: document.querySelector('#stage-fps'),
|
|
153
|
+
stageBackground: document.querySelector('#stage-background'),
|
|
154
|
+
stageSizeLabel: document.querySelector('#stage-size-label'),
|
|
155
|
+
stageFpsLabel: document.querySelector('#stage-fps-label'),
|
|
156
|
+
stageSceneName: document.querySelector('#stage-scene-name'),
|
|
157
|
+
playhead: document.querySelector('#playhead'),
|
|
158
|
+
frameReadout: document.querySelector('#frame-readout'),
|
|
159
|
+
timelineRuler: document.querySelector('#timeline-ruler'),
|
|
160
|
+
timelineLanes: document.querySelector('#timeline-lanes'),
|
|
161
|
+
frameEdit: document.querySelector('#frame-edit'),
|
|
162
|
+
addKeyframe: document.querySelector('#add-keyframe'),
|
|
163
|
+
tweenEasing: document.querySelector('#tween-easing'),
|
|
164
|
+
closePath: document.querySelector('#close-path'),
|
|
165
|
+
finishPath: document.querySelector('#finish-path'),
|
|
166
|
+
editText: document.querySelector('#edit-text'),
|
|
167
|
+
textEditLayer: document.querySelector('#text-edit-layer'),
|
|
168
|
+
textEditInput: document.querySelector('#text-edit-input'),
|
|
169
|
+
textEditDone: document.querySelector('#text-edit-done'),
|
|
170
|
+
textEditCancel: document.querySelector('#text-edit-cancel'),
|
|
171
|
+
vectorStyleFields: document.querySelector('#vector-style-fields'),
|
|
172
|
+
textContentLabel: document.querySelector('#text-content-label'),
|
|
173
|
+
textStyleFields: document.querySelector('#text-style-fields'),
|
|
174
|
+
playButton: document.querySelector('#play-button'),
|
|
175
|
+
previewButton: document.querySelector('#preview-button'),
|
|
176
|
+
stopButton: document.querySelector('#stop-button'),
|
|
177
|
+
deleteElement: document.querySelector('#delete-element'),
|
|
178
|
+
deleteScene: document.querySelector('#delete-scene'),
|
|
179
|
+
previousFrame: document.querySelector('#previous-frame'),
|
|
180
|
+
nextFrame: document.querySelector('#next-frame'),
|
|
181
|
+
instanceSettings: document.querySelector('#instance-settings'),
|
|
182
|
+
instanceMode: document.querySelector('#instance-mode'),
|
|
183
|
+
instanceFirst: document.querySelector('#instance-first'),
|
|
184
|
+
elementForm: document.querySelector('#element-form'),
|
|
185
|
+
noSelection: document.querySelector('#no-selection'),
|
|
186
|
+
elementType: document.querySelector('#element-type'),
|
|
187
|
+
elementLayer: document.querySelector('#element-layer'),
|
|
188
|
+
maskSource: document.querySelector('#mask-source'),
|
|
189
|
+
maskUsage: document.querySelector('#mask-usage'),
|
|
190
|
+
elementLockedWarning: document.querySelector('#element-locked-warning'),
|
|
191
|
+
toolButtons: [...document.querySelectorAll('[data-tool]')],
|
|
192
|
+
previewBadge: document.querySelector('#preview-badge'),
|
|
193
|
+
status: document.querySelector('#status-message'),
|
|
194
|
+
importProject: document.querySelector('#import-project'),
|
|
195
|
+
exportProject: document.querySelector('#export-project'),
|
|
196
|
+
projectIoDialog: document.querySelector('#project-io-dialog'),
|
|
197
|
+
projectIoForm: document.querySelector('#project-io-form'),
|
|
198
|
+
projectIoTitle: document.querySelector('#project-io-title'),
|
|
199
|
+
projectIoDescription: document.querySelector('#project-io-description'),
|
|
200
|
+
projectIoTextarea: document.querySelector('#project-io-textarea'),
|
|
201
|
+
projectIoError: document.querySelector('#project-io-error'),
|
|
202
|
+
projectIoClose: document.querySelector('#project-io-close'),
|
|
203
|
+
projectIoCancel: document.querySelector('#project-io-cancel'),
|
|
204
|
+
projectIoCopy: document.querySelector('#project-io-copy'),
|
|
205
|
+
projectIoSubmit: document.querySelector('#project-io-submit'),
|
|
206
|
+
projectIoExamples: document.querySelector('#project-io-examples'),
|
|
207
|
+
elementIsButton: document.querySelector('#element-is-button'),
|
|
208
|
+
buttonTrigger: document.querySelector('#button-trigger'),
|
|
209
|
+
buttonKey: document.querySelector('#button-key'),
|
|
210
|
+
buttonSwipe: document.querySelector('#button-swipe'),
|
|
211
|
+
buttonActionFields: document.querySelector('#button-action-fields'),
|
|
212
|
+
buttonActionType: document.querySelector('#button-action-type'),
|
|
213
|
+
buttonTargetSceneWrap: document.querySelector('#button-target-scene-wrap'),
|
|
214
|
+
jumpPlay: document.querySelector('#jump-play'),
|
|
215
|
+
inputOperation: document.querySelector('#input-operation'),
|
|
216
|
+
insertValue: document.querySelector('#insert-value'),
|
|
217
|
+
buttonTargetScene: document.querySelector('#button-target-scene'),
|
|
218
|
+
buttonTargetFrameWrap: document.querySelector('#button-target-frame-wrap'),
|
|
219
|
+
buttonTargetFrame: document.querySelector('#button-target-frame'),
|
|
220
|
+
buttonTargetElementWrap: document.querySelector('#button-target-element-wrap'),
|
|
221
|
+
buttonTargetElement: document.querySelector('#button-target-element'),
|
|
222
|
+
buttonActionWarning: document.querySelector('#button-action-warning'),
|
|
223
|
+
};
|
|
224
|
+
|
|
225
|
+
const canvasRenderer = createCanvasRenderer(elements.canvas, document.querySelector('#preview-surface'));
|
|
226
|
+
elements.buttonKey.replaceChildren(...bindingKeys.map(key => new Option(key.replace('Arrow', 'Arrow '), key)));
|
|
227
|
+
const previewInteractions = bindPreviewInteractions({
|
|
228
|
+
mat: elements.stageMat, canvas: elements.canvas, renderer: canvasRenderer,
|
|
229
|
+
active: () => isInteractivePreview() && !sceneTransition.active,
|
|
230
|
+
point: pointerToStage, run: runButtonAction,
|
|
231
|
+
feedback(hover, press) {
|
|
232
|
+
if (hover === hoveredButtonId && press === pressedButtonId) return;
|
|
233
|
+
hoveredButtonId = hover;
|
|
234
|
+
pressedButtonId = press;
|
|
235
|
+
renderCanvas();
|
|
236
|
+
},
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
const sceneTransition = createSceneTransition(elements.canvas, document.querySelector('#preview-surface'), () => {
|
|
240
|
+
renderAll();
|
|
241
|
+
dispatchFrameEvents();
|
|
242
|
+
});
|
|
243
|
+
const transitionInspector = createTransitionInspector({
|
|
244
|
+
current: () => project.scenes.find(scene => scene.id === selectedSceneId),
|
|
245
|
+
locked: isInteractivePreview, commit: renderAll, report: showStatus,
|
|
246
|
+
});
|
|
247
|
+
|
|
248
|
+
function isInteractivePreview() {
|
|
249
|
+
return previewMode || playing;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function hasProjectId(id) {
|
|
253
|
+
return project.assets.some(asset => asset.id === id) || project.scripts?.some(script => script.id === id) || [...project.scenes, ...project.symbols].some(
|
|
254
|
+
scene =>
|
|
255
|
+
scene.id === id || scene.audioClips?.some(clip => clip.id === id) ||
|
|
256
|
+
scene.layers?.some(layer => layer.id === id) ||
|
|
257
|
+
scene.elements.some(element => element.id === id || element.groupId === id),
|
|
258
|
+
);
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function makeId(prefix) {
|
|
262
|
+
let candidate;
|
|
263
|
+
do {
|
|
264
|
+
idSequence += 1;
|
|
265
|
+
candidate = `${prefix}-${idSequence}`;
|
|
266
|
+
} while (hasProjectId(candidate));
|
|
267
|
+
return candidate;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
function makeScene(name, kind = 'scene') {
|
|
271
|
+
return {
|
|
272
|
+
id: makeId(kind),
|
|
273
|
+
name,
|
|
274
|
+
durationFrames: DEFAULT_DURATION,
|
|
275
|
+
startFrame: 1,
|
|
276
|
+
loop: false,
|
|
277
|
+
layers: [{ id: makeId('layer'), name: 'Layer 1', visible: true, locked: false, order: 0 }],
|
|
278
|
+
elements: [],
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function activeScene() {
|
|
283
|
+
return project.scenes.find(scene => scene.id === selectedSceneId) ??
|
|
284
|
+
project.symbols.find(symbol => symbol.id === selectedSceneId) ?? null;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
function workingStage() {
|
|
288
|
+
const timeline = activeScene();
|
|
289
|
+
return timeline?.width ? { ...project.stage, width: timeline.width, height: timeline.height } : project.stage;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function authoringView() {
|
|
293
|
+
return { selectedSceneId, selectedLayerId, selectedElementIds: [...selectedElementIds], playhead };
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
function restoreView(view) {
|
|
297
|
+
({ selectedSceneId, selectedLayerId, playhead } = view);
|
|
298
|
+
selectedElementIds = [...view.selectedElementIds];
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
function enterSymbol(id) {
|
|
302
|
+
if (!project.symbols.some(symbol => symbol.id === id) || id === selectedSceneId) return;
|
|
303
|
+
if (editingTextElementId) closeTextEditor(true);
|
|
304
|
+
if (pendingPath) cancelPendingPath();
|
|
305
|
+
returnViews.push(authoringView());
|
|
306
|
+
preferredSymbol = id;
|
|
307
|
+
selectScene(id);
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
const renderSymbolLibrary = createSymbolLibrary({
|
|
311
|
+
create() {
|
|
312
|
+
if (editingTextElementId) closeTextEditor(true);
|
|
313
|
+
if (pendingPath) cancelPendingPath();
|
|
314
|
+
const symbol = makeScene(`Symbol ${project.symbols.length + 1}`, 'symbol');
|
|
315
|
+
Object.assign(symbol, { width: 320, height: 200, durationFrames: 24, loop: true });
|
|
316
|
+
project.symbols.push(symbol);
|
|
317
|
+
enterSymbol(symbol.id);
|
|
318
|
+
elements.sceneName.focus();
|
|
319
|
+
elements.sceneName.select();
|
|
320
|
+
},
|
|
321
|
+
edit: enterSymbol,
|
|
322
|
+
scripts(id) {
|
|
323
|
+
const symbol = project.symbols.find(item => item.id === id);
|
|
324
|
+
if (symbol) openHandlers(symbol, symbol.button ? 'button' : 'symbol');
|
|
325
|
+
},
|
|
326
|
+
place(id) {
|
|
327
|
+
const symbol = project.symbols.find(item => item.id === id);
|
|
328
|
+
if (!symbol) return;
|
|
329
|
+
if (editingTextElementId) closeTextEditor(true);
|
|
330
|
+
if (pendingPath) cancelPendingPath();
|
|
331
|
+
createShape('symbol', { width: symbol.width, height: symbol.height, symbol });
|
|
332
|
+
},
|
|
333
|
+
back() {
|
|
334
|
+
if (editingTextElementId) closeTextEditor(true);
|
|
335
|
+
if (pendingPath) cancelPendingPath();
|
|
336
|
+
preferredSymbol = selectedSceneId;
|
|
337
|
+
restoreView(returnViews.pop());
|
|
338
|
+
pendingLayerDeleteId = editingLayerId = null;
|
|
339
|
+
renderAll();
|
|
340
|
+
},
|
|
341
|
+
});
|
|
342
|
+
|
|
343
|
+
function activeLayer() {
|
|
344
|
+
const scene = activeScene();
|
|
345
|
+
if (!scene) return null;
|
|
346
|
+
return scene.layers.find(layer => layer.id === selectedLayerId) ?? orderedSceneLayers(scene).at(-1) ?? null;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
function selectedElement() {
|
|
350
|
+
const scene = activeScene();
|
|
351
|
+
return selectedElementIds.length === 1 ? scene?.elements.find(element => element.id === selectedElementIds[0]) : null;
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
function formatNumber(value) {
|
|
355
|
+
return Number.isInteger(value) ? String(value) : String(Number(value.toFixed(2)));
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
function updatePoseProperty(element, property, value) {
|
|
359
|
+
if (property === 'text') materializeHtmlText(element);
|
|
360
|
+
setPoseAtFrame(element, playhead, property, value);
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
function showStatus(message, isError = false) {
|
|
364
|
+
window.clearTimeout(statusTimeout);
|
|
365
|
+
document.querySelector('#preview-error-script').hidden = true;
|
|
366
|
+
elements.status.textContent = message;
|
|
367
|
+
elements.status.title = message;
|
|
368
|
+
const status = document.getElementById('status-announcement');
|
|
369
|
+
const alert = document.getElementById('error-announcement');
|
|
370
|
+
(isError ? status : alert).replaceChildren();
|
|
371
|
+
(isError ? alert : status).replaceChildren(document.createTextNode(message));
|
|
372
|
+
elements.status.classList.toggle('is-error', isError);
|
|
373
|
+
elements.status.classList.add('is-visible');
|
|
374
|
+
statusTimeout = window.setTimeout(() => {
|
|
375
|
+
elements.status.classList.remove('is-visible');
|
|
376
|
+
}, 2200);
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
const scriptEditorContext = { project, commit: () => renderAll(), editScript: createScriptEditor({ project }), makeId };
|
|
380
|
+
const openEventEditor = createEventEditor(scriptEditorContext);
|
|
381
|
+
const openHandlers = createHandlerEditor(scriptEditorContext);
|
|
382
|
+
|
|
383
|
+
function movieBuildError(response, body) {
|
|
384
|
+
const error = new Error(body.error?.message ?? body.message ?? `The server answered ${response.status}`);
|
|
385
|
+
if (body.error?.code === 'script_error') error.diagnostic = body.error;
|
|
386
|
+
return error;
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
function showScriptErrorLink(selector, diagnostic) {
|
|
390
|
+
const index = project.scripts?.findIndex(script => script.id === diagnostic?.script);
|
|
391
|
+
if (index == null || index < 0) return;
|
|
392
|
+
const script = project.scripts[index];
|
|
393
|
+
const button = document.querySelector(selector);
|
|
394
|
+
button.hidden = false;
|
|
395
|
+
button.onclick = async () => {
|
|
396
|
+
if (project.scripts?.[index] !== script) { button.hidden = true; return; }
|
|
397
|
+
if (elements.projectIoDialog.open) elements.projectIoDialog.close();
|
|
398
|
+
const edit = await scriptEditorContext.editScript(script, script.name || script.id, diagnostic);
|
|
399
|
+
if (edit && project.scripts[index] === script) {
|
|
400
|
+
project.scripts[index] = { ...script, code: edit.code };
|
|
401
|
+
renderAll();
|
|
402
|
+
showStatus('Script updated');
|
|
403
|
+
button.hidden = true;
|
|
404
|
+
}
|
|
405
|
+
};
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
const previewAudio = createPreviewAudio(message => showStatus(message, true));
|
|
409
|
+
const projectSession = createProjectSession({
|
|
410
|
+
getDocument: () => JSON.parse(serializeProject(project, 0)),
|
|
411
|
+
liveAssets: () => project.assets,
|
|
412
|
+
report: showStatus,
|
|
413
|
+
onState({ name, dirty, saving, served, journalFailed }) {
|
|
414
|
+
const save = document.getElementById('save-project');
|
|
415
|
+
save.dataset.dirty = String(dirty);
|
|
416
|
+
save.dataset.failed = String(journalFailed);
|
|
417
|
+
save.disabled = saving;
|
|
418
|
+
const state = `${served ? name : 'Untitled project'}${dirty ? ', unsaved changes' : served ? ', saved' : ''}`;
|
|
419
|
+
document.getElementById('project-state').textContent = state;
|
|
420
|
+
document.title = `${dirty ? '• ' : ''}${served ? name + ' — ' : ''}Swoof Studio`;
|
|
421
|
+
},
|
|
422
|
+
});
|
|
423
|
+
const mediaLibrary = createMediaLibrary({ project, makeId, report: showStatus, commit: () => renderAll(),
|
|
424
|
+
upload: (file, onProgress) => projectSession.upload(file, onProgress),
|
|
425
|
+
dropTargets: [
|
|
426
|
+
{ element: document.getElementById('library-panel') },
|
|
427
|
+
{ element: document.getElementById('stage'), onDrop(assets, event) {
|
|
428
|
+
const rect = elements.canvas.getBoundingClientRect();
|
|
429
|
+
const inside = event.clientX >= rect.left && event.clientX <= rect.right && event.clientY >= rect.top && event.clientY <= rect.bottom;
|
|
430
|
+
const point = inside ? pointerToStage(event) : undefined;
|
|
431
|
+
for (const asset of assets) mediaLibrary.place(asset, point);
|
|
432
|
+
} },
|
|
433
|
+
],
|
|
434
|
+
state: () => ({ timeline: activeScene(), frame: playhead, locked: isInteractivePreview(),
|
|
435
|
+
layerLocked: activeLayer()?.locked || activeLayer()?.visible === false }),
|
|
436
|
+
placeBitmap(asset, image, point) {
|
|
437
|
+
const stage = workingStage();
|
|
438
|
+
const scale = Math.min(1, stage.width / image.naturalWidth, stage.height / image.naturalHeight);
|
|
439
|
+
createShape('bitmap', { asset, width: Math.max(1, image.naturalWidth * scale), height: Math.max(1, image.naturalHeight * scale), ...point });
|
|
440
|
+
},
|
|
441
|
+
});
|
|
442
|
+
|
|
443
|
+
function previewNavigation(target) {
|
|
444
|
+
previewInteractions.reset();
|
|
445
|
+
if (target.transition && target.id !== selectedSceneId) {
|
|
446
|
+
renderCanvas();
|
|
447
|
+
sceneTransition.begin(target.transition, project.stage.frameRate);
|
|
448
|
+
lastTick = null;
|
|
449
|
+
timeAccumulator = 0;
|
|
450
|
+
}
|
|
451
|
+
previewAudio.reset();
|
|
452
|
+
previewHiddenIds.clear();
|
|
453
|
+
symbolClocks.clear();
|
|
454
|
+
eventDispatcher.reset();
|
|
455
|
+
hoveredButtonId = pressedButtonId = null;
|
|
456
|
+
returnViews = [];
|
|
457
|
+
selectedSceneId = target.id;
|
|
458
|
+
selectedLayerId = orderedSceneLayers(target).at(-1)?.id ?? null;
|
|
459
|
+
selectedElementIds = [];
|
|
460
|
+
playhead = target.startFrame ?? 1;
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
function rememberPreviewOrigin() {
|
|
464
|
+
previewAudio.unlock(project.assets);
|
|
465
|
+
if (!previewOrigin) {
|
|
466
|
+
previewOrigin = { ...authoringView(), returnViews: [...returnViews] };
|
|
467
|
+
elements.canvas.focus({ preventScroll: true });
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
function updateClock(ctx, frame, play) {
|
|
472
|
+
const id = scopedId(ctx.scope.slice(0, -1), ctx.scope.at(-1));
|
|
473
|
+
symbolClocks.set(id, { anchor: ctx.parentFrame, lastFrame: ctx.parentFrame, frame, play });
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
function executeFrameAction(action, ctx) {
|
|
477
|
+
// Scripts run only on the swf2js player (studiospec/actionscript.md).
|
|
478
|
+
if (action.type === 'script') return;
|
|
479
|
+
if (objectAction(action.type)) {
|
|
480
|
+
const id = scopedId(ctx.scope, action.target);
|
|
481
|
+
if (action.type === 'hide' || (action.type === 'toggleVisibility' && !previewHiddenIds.has(id))) previewHiddenIds.add(id);
|
|
482
|
+
else previewHiddenIds.delete(id);
|
|
483
|
+
return;
|
|
484
|
+
}
|
|
485
|
+
if (action.type === 'gotoScene') {
|
|
486
|
+
previewNavigation(project.scenes.find(scene => scene.id === action.target));
|
|
487
|
+
playing = Boolean(action.play);
|
|
488
|
+
return;
|
|
489
|
+
}
|
|
490
|
+
const jump = action.type === 'gotoFrame';
|
|
491
|
+
const play = action.type === 'play' || (jump && Boolean(action.play));
|
|
492
|
+
if (jump) eventDispatcher.reenter(ctx.scope);
|
|
493
|
+
if (jump) previewAudio.reset(ctx.scope);
|
|
494
|
+
if (ctx.scope.length) updateClock(ctx, jump ? action.target : ctx.frame, play);
|
|
495
|
+
else {
|
|
496
|
+
if (jump) playhead = action.target;
|
|
497
|
+
playing = play;
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
function schedulePlayback() {
|
|
502
|
+
if (playing && !sceneTransition.active && !animationRequest) animationRequest = requestAnimationFrame(playbackTick);
|
|
503
|
+
if (!playing || sceneTransition.active) {
|
|
504
|
+
if (animationRequest) cancelAnimationFrame(animationRequest);
|
|
505
|
+
animationRequest = 0;
|
|
506
|
+
lastTick = null;
|
|
507
|
+
timeAccumulator = 0;
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
function dispatchFrameEvents(tick = false) {
|
|
512
|
+
if (tick) eventDispatcher.tick(canvasRenderer.previewTimelines());
|
|
513
|
+
try {
|
|
514
|
+
if (eventDispatcher.settle(() => sceneTransition.active ? [] : canvasRenderer.previewTimelines(), executeFrameAction, renderCanvas)) renderAll();
|
|
515
|
+
} catch (error) {
|
|
516
|
+
playing = false;
|
|
517
|
+
renderAll();
|
|
518
|
+
showStatus(error.message, true);
|
|
519
|
+
}
|
|
520
|
+
schedulePlayback();
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
function setFrame(frame) {
|
|
524
|
+
const scene = activeScene();
|
|
525
|
+
if (!scene) return;
|
|
526
|
+
if (editingTextElementId) closeTextEditor(true);
|
|
527
|
+
playhead = Math.max(1, Math.min(scene.durationFrames, Math.round(frame)));
|
|
528
|
+
renderAll();
|
|
529
|
+
if (isInteractivePreview()) dispatchFrameEvents();
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
function clearPreviewState() {
|
|
533
|
+
previewInteractions.reset();
|
|
534
|
+
sceneTransition.cancel();
|
|
535
|
+
if (previewOrigin) {
|
|
536
|
+
const at = selectedSceneId === previewOrigin.selectedSceneId ? playhead : previewOrigin.playhead;
|
|
537
|
+
restoreView(previewOrigin);
|
|
538
|
+
returnViews = previewOrigin.returnViews;
|
|
539
|
+
playhead = at;
|
|
540
|
+
}
|
|
541
|
+
previewOrigin = null;
|
|
542
|
+
eventDispatcher.reset();
|
|
543
|
+
previewMode = false;
|
|
544
|
+
hoveredButtonId = null;
|
|
545
|
+
pressedButtonId = null;
|
|
546
|
+
previewHiddenIds.clear();
|
|
547
|
+
symbolClocks.clear();
|
|
548
|
+
hideSwfPlayer();
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
// Projects whose behavior is ActionScript play on the swf2js runtime (studiospec/actionscript.md
|
|
552
|
+
// §3). The server builds a movie from the project as it is now, unsaved edits included.
|
|
553
|
+
let swfPlayer = null;
|
|
554
|
+
let previewRequest = 0;
|
|
555
|
+
let previewKeepAlive;
|
|
556
|
+
function usesSwfPlayer() {
|
|
557
|
+
return swfPlayerReasons(project).length > 0;
|
|
558
|
+
}
|
|
559
|
+
// The Preview movie with a recorder in it, for video export of projects on the swf2js player.
|
|
560
|
+
async function buildRecordingPreview() {
|
|
561
|
+
const response = await fetch('/api/preview', {
|
|
562
|
+
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
|
563
|
+
body: JSON.stringify({ project: projectDocument(project), projectId: projectSession.served ? projectSession.id : null,
|
|
564
|
+
externalResources: document.querySelector('#preview-network').value, record: true }),
|
|
565
|
+
});
|
|
566
|
+
const body = await response.json().catch(() => ({}));
|
|
567
|
+
if (!response.ok) throw movieBuildError(response, body);
|
|
568
|
+
return body.url;
|
|
569
|
+
}
|
|
570
|
+
async function showSwfPlayer() {
|
|
571
|
+
const request = ++previewRequest;
|
|
572
|
+
rememberPreviewOrigin();
|
|
573
|
+
previewMode = true;
|
|
574
|
+
renderAll();
|
|
575
|
+
showStatus('Building the preview…');
|
|
576
|
+
const stopBusy = startBusy('Building the preview…');
|
|
577
|
+
let url, notes = [];
|
|
578
|
+
try {
|
|
579
|
+
const response = await fetch('/api/preview', {
|
|
580
|
+
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
|
581
|
+
body: JSON.stringify({ project: projectDocument(project), projectId: projectSession.served ? projectSession.id : null,
|
|
582
|
+
externalResources: document.querySelector('#preview-network').value }),
|
|
583
|
+
});
|
|
584
|
+
const body = await response.json().catch(() => ({}));
|
|
585
|
+
if (!response.ok) throw movieBuildError(response, body);
|
|
586
|
+
url = body.url;
|
|
587
|
+
notes = Array.isArray(body.notes) ? body.notes.filter(note => typeof note === 'string') : [];
|
|
588
|
+
} catch (error) {
|
|
589
|
+
stopBusy();
|
|
590
|
+
if (request !== previewRequest) return false;
|
|
591
|
+
clearPreviewState();
|
|
592
|
+
renderAll();
|
|
593
|
+
showStatus(`Preview could not be built: ${error.message}`, true);
|
|
594
|
+
showScriptErrorLink('#preview-error-script', error.diagnostic);
|
|
595
|
+
return false;
|
|
596
|
+
}
|
|
597
|
+
if (request !== previewRequest || !previewMode) {
|
|
598
|
+
stopBusy();
|
|
599
|
+
return false;
|
|
600
|
+
}
|
|
601
|
+
if (!swfPlayer) {
|
|
602
|
+
swfPlayer = document.createElement('iframe');
|
|
603
|
+
swfPlayer.id = 'swf-player';
|
|
604
|
+
swfPlayer.className = 'swf-player';
|
|
605
|
+
swfPlayer.title = 'Movie preview with ActionScript';
|
|
606
|
+
swfPlayer.setAttribute('allow', 'autoplay');
|
|
607
|
+
swfPlayer.addEventListener('load', () => {
|
|
608
|
+
if (!swfPlayer.hidden) swfPlayer.contentWindow?.focus();
|
|
609
|
+
});
|
|
610
|
+
// Over the stage itself, so the movie takes exactly the stage's place and zoom: the player
|
|
611
|
+
// letterboxes a movie in any larger box, which showed as black margins.
|
|
612
|
+
document.querySelector('.stage-mat').append(swfPlayer);
|
|
613
|
+
}
|
|
614
|
+
swfPlayer.style.background = project.stage.background ?? '#111';
|
|
615
|
+
swfPlayer.hidden = false;
|
|
616
|
+
// Keep the indicator up while the player loads the movie data, with a fallback.
|
|
617
|
+
swfPlayer.addEventListener('load', stopBusy, { once: true });
|
|
618
|
+
setTimeout(stopBusy, 20000);
|
|
619
|
+
swfPlayer.src = url;
|
|
620
|
+
clearInterval(previewKeepAlive);
|
|
621
|
+
previewKeepAlive = setInterval(() => fetch(url, { method: 'HEAD' }).catch(() => {}), 5 * 60 * 1000);
|
|
622
|
+
// Parts of the project that do not run in this preview (swipes, nested masks, …).
|
|
623
|
+
showStatus(notes.length ? `Previewing with ActionScript. Not in this preview: ${notes.join('; ')}.` : 'Previewing with ActionScript.');
|
|
624
|
+
return true;
|
|
625
|
+
}
|
|
626
|
+
function hideSwfPlayer() {
|
|
627
|
+
clearInterval(previewKeepAlive);
|
|
628
|
+
previewRequest++;
|
|
629
|
+
if (!swfPlayer || swfPlayer.hidden) return;
|
|
630
|
+
swfPlayer.hidden = true;
|
|
631
|
+
swfPlayer.src = 'about:blank'; // Stops the movie and its sound.
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
function stopPlayback(reset = false) {
|
|
635
|
+
playing = false;
|
|
636
|
+
lastTick = null;
|
|
637
|
+
timeAccumulator = 0;
|
|
638
|
+
if (animationRequest) cancelAnimationFrame(animationRequest);
|
|
639
|
+
animationRequest = 0;
|
|
640
|
+
if (reset) {
|
|
641
|
+
clearPreviewState();
|
|
642
|
+
playhead = activeScene()?.startFrame ?? 1;
|
|
643
|
+
}
|
|
644
|
+
renderAll();
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
function leavePreview() {
|
|
648
|
+
clearPreviewState();
|
|
649
|
+
stopPlayback();
|
|
650
|
+
elements.canvas.focus({ preventScroll: true });
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
function togglePreviewMode() {
|
|
654
|
+
if (previewMode) {
|
|
655
|
+
leavePreview();
|
|
656
|
+
return;
|
|
657
|
+
}
|
|
658
|
+
if (editingTextElementId) closeTextEditor(true);
|
|
659
|
+
if (pendingPath) cancelPendingPath();
|
|
660
|
+
if (usesSwfPlayer()) {
|
|
661
|
+
showSwfPlayer();
|
|
662
|
+
return;
|
|
663
|
+
}
|
|
664
|
+
previewHiddenIds.clear();
|
|
665
|
+
symbolClocks.clear();
|
|
666
|
+
hoveredButtonId = null;
|
|
667
|
+
pressedButtonId = null;
|
|
668
|
+
rememberPreviewOrigin();
|
|
669
|
+
previewMode = true;
|
|
670
|
+
playhead = activeScene()?.startFrame ?? 1;
|
|
671
|
+
renderAll();
|
|
672
|
+
showStatus('Preview mode active');
|
|
673
|
+
// Preview plays the movie, as Flash's Test Movie does; Pause stops it at the current frame.
|
|
674
|
+
// The stored preference `swoof-studio.preview-autoplay = off` opens Preview on a still frame.
|
|
675
|
+
if (previewAutoplay()) playFrom(playhead);
|
|
676
|
+
else dispatchFrameEvents();
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
function previewAutoplay() {
|
|
680
|
+
try {
|
|
681
|
+
return localStorage.getItem('swoof-studio.preview-autoplay') !== 'off';
|
|
682
|
+
} catch {
|
|
683
|
+
return true;
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
// Time one playback tick may spend catching up on late frames before it drops the rest.
|
|
688
|
+
const CATCH_UP_BUDGET_MS = 12;
|
|
689
|
+
|
|
690
|
+
function playbackTick(now) {
|
|
691
|
+
animationRequest = 0;
|
|
692
|
+
if (!playing) return;
|
|
693
|
+
if (lastTick === null) lastTick = now;
|
|
694
|
+
timeAccumulator += Math.min(250, now - lastTick);
|
|
695
|
+
lastTick = now;
|
|
696
|
+
const scene = activeScene();
|
|
697
|
+
if (!scene) {
|
|
698
|
+
stopPlayback();
|
|
699
|
+
return;
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
const frameDuration = 1000 / project.stage.frameRate;
|
|
703
|
+
const steps = Math.floor(timeAccumulator / frameDuration);
|
|
704
|
+
if (steps > 0) {
|
|
705
|
+
timeAccumulator -= steps * frameDuration;
|
|
706
|
+
const hasEvents = [...project.scenes, ...project.symbols].some(owner => owner.events?.length);
|
|
707
|
+
// Frame events must see every frame, so a late tick catches up frame by frame. Catching up
|
|
708
|
+
// stops once this tick has used its budget: a heavy movie then slows down, as Flash Player
|
|
709
|
+
// does, instead of rendering a growing backlog and never letting the page paint or answer
|
|
710
|
+
// input. Light movies still catch up exactly.
|
|
711
|
+
const increment = hasEvents ? 1 : steps;
|
|
712
|
+
const tickStart = performance.now();
|
|
713
|
+
for (let step = 0; step < steps && playing && !sceneTransition.active; step += increment) {
|
|
714
|
+
if (step > 0 && performance.now() - tickStart > CATCH_UP_BUDGET_MS) break;
|
|
715
|
+
const current = activeScene();
|
|
716
|
+
const next = advancePlayhead(current, playhead, increment);
|
|
717
|
+
if (next.finished) {
|
|
718
|
+
playhead = next.frame;
|
|
719
|
+
stopPlayback();
|
|
720
|
+
return;
|
|
721
|
+
}
|
|
722
|
+
if (current.loop && playhead + increment > current.durationFrames) {
|
|
723
|
+
symbolClocks.clear();
|
|
724
|
+
previewAudio.reset();
|
|
725
|
+
eventDispatcher.reenter([]);
|
|
726
|
+
}
|
|
727
|
+
playhead = next.frame;
|
|
728
|
+
renderCanvas();
|
|
729
|
+
if (hasEvents) dispatchFrameEvents(true);
|
|
730
|
+
}
|
|
731
|
+
timeline.readout(playhead);
|
|
732
|
+
if (selectedElementIds.length) renderInspector();
|
|
733
|
+
}
|
|
734
|
+
schedulePlayback();
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
function startPlayback() {
|
|
738
|
+
if (sceneTransition.active) return;
|
|
739
|
+
if (playing) {
|
|
740
|
+
stopPlayback();
|
|
741
|
+
return;
|
|
742
|
+
}
|
|
743
|
+
if (usesSwfPlayer()) {
|
|
744
|
+
if (swfPlayer && !swfPlayer.hidden) leavePreview();
|
|
745
|
+
else showSwfPlayer();
|
|
746
|
+
return;
|
|
747
|
+
}
|
|
748
|
+
if (editingTextElementId) closeTextEditor(true);
|
|
749
|
+
if (pendingPath) {
|
|
750
|
+
const minimum = pendingPath.kind === 'polygon' ? 3 : 2;
|
|
751
|
+
if (pendingPath.points.length < minimum) {
|
|
752
|
+
showStatus(`Finish the drawing or add ${minimum - pendingPath.points.length} more point${minimum - pendingPath.points.length === 1 ? '' : 's'} before preview`, true);
|
|
753
|
+
return;
|
|
754
|
+
}
|
|
755
|
+
finishPendingPath(pendingPath.kind === 'polygon');
|
|
756
|
+
}
|
|
757
|
+
const scene = activeScene();
|
|
758
|
+
if (!scene) return;
|
|
759
|
+
if (playhead >= scene.durationFrames) eventDispatcher.reenter([]);
|
|
760
|
+
playFrom(playhead >= scene.durationFrames ? scene.startFrame ?? 1 : playhead);
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
function playFrom(frame) {
|
|
764
|
+
rememberPreviewOrigin();
|
|
765
|
+
if (animationRequest) cancelAnimationFrame(animationRequest);
|
|
766
|
+
animationRequest = 0;
|
|
767
|
+
playhead = frame;
|
|
768
|
+
previewMode = true;
|
|
769
|
+
playing = true;
|
|
770
|
+
lastTick = null;
|
|
771
|
+
timeAccumulator = 0;
|
|
772
|
+
renderAll();
|
|
773
|
+
dispatchFrameEvents();
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
function createShape(type, geometry = {}) {
|
|
777
|
+
const scene = activeScene();
|
|
778
|
+
const layer = activeLayer();
|
|
779
|
+
if (!scene || !layer) return;
|
|
780
|
+
if (layer.locked) {
|
|
781
|
+
showStatus('Unlock the active layer before drawing on it', true);
|
|
782
|
+
return;
|
|
783
|
+
}
|
|
784
|
+
stopPlayback();
|
|
785
|
+
const isCircle = type === 'circle';
|
|
786
|
+
const width = geometry.width ?? (isCircle ? 96 : type === 'line' || type === 'curve' ? 160 : 140);
|
|
787
|
+
const height = geometry.height ?? (isCircle ? 96 : type === 'line' || type === 'curve' ? 100 : 110);
|
|
788
|
+
const label = ({
|
|
789
|
+
roundedRectangle: 'Rounded rectangle',
|
|
790
|
+
hexagon: 'Hexagon',
|
|
791
|
+
ellipse: 'Ellipse',
|
|
792
|
+
})[type] || `${type[0].toUpperCase()}${type.slice(1)}`;
|
|
793
|
+
const element = {
|
|
794
|
+
id: makeId('element'),
|
|
795
|
+
name: `${label} ${scene.elements.length + 1}`,
|
|
796
|
+
type,
|
|
797
|
+
layerId: layer.id,
|
|
798
|
+
x: geometry.x ?? workingStage().width / 2,
|
|
799
|
+
y: geometry.y ?? workingStage().height / 2,
|
|
800
|
+
width,
|
|
801
|
+
height,
|
|
802
|
+
scaleX: 1,
|
|
803
|
+
scaleY: 1,
|
|
804
|
+
rotation: geometry.rotation ?? 0,
|
|
805
|
+
skew: 0,
|
|
806
|
+
opacity: 1,
|
|
807
|
+
fill: ['circle', 'star'].includes(type) ? '#f2b85c' : type === 'ellipse' ? '#7f9cff' : '#56d4ad',
|
|
808
|
+
stroke: '#e8f3ef',
|
|
809
|
+
strokeWidth: 2,
|
|
810
|
+
text: '',
|
|
811
|
+
fontFamily: 'Arial',
|
|
812
|
+
fontSize: 32,
|
|
813
|
+
textColor: '#f4f6fb',
|
|
814
|
+
textAlign: 'center',
|
|
815
|
+
bold: false,
|
|
816
|
+
buttonAction: null,
|
|
817
|
+
keyframes: [],
|
|
818
|
+
};
|
|
819
|
+
if (type === 'control') {
|
|
820
|
+
element.control = geometry.control;
|
|
821
|
+
element.parameters = defaultControlParameters(element.control);
|
|
822
|
+
const prefix = element.control[0].toLowerCase() + element.control.slice(1);
|
|
823
|
+
let index = 1;
|
|
824
|
+
while (scene.elements.some(item => item.name === prefix + index)) index++;
|
|
825
|
+
element.name = prefix + index;
|
|
826
|
+
if (element.control === 'RadioButton') element.parameters.data = element.name;
|
|
827
|
+
}
|
|
828
|
+
if (type === 'bitmap') {
|
|
829
|
+
element.assetId = geometry.asset.id;
|
|
830
|
+
element.fit = 'contain';
|
|
831
|
+
element.name = geometry.asset.name.slice(0, 48);
|
|
832
|
+
}
|
|
833
|
+
if (type === 'symbol') {
|
|
834
|
+
element.symbolId = geometry.symbol.id;
|
|
835
|
+
element.name = geometry.symbol.name;
|
|
836
|
+
}
|
|
837
|
+
startTrack(element, playhead);
|
|
838
|
+
scene.elements.push(element);
|
|
839
|
+
selectedElementIds = [element.id];
|
|
840
|
+
activeTool = 'select';
|
|
841
|
+
renderAll();
|
|
842
|
+
showStatus(`${element.name} created`);
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
function createText(geometry = {}) {
|
|
846
|
+
const scene = activeScene();
|
|
847
|
+
const layer = activeLayer();
|
|
848
|
+
if (!scene || !layer) return;
|
|
849
|
+
if (layer.locked) {
|
|
850
|
+
showStatus('Unlock the active layer before drawing on it', true);
|
|
851
|
+
return;
|
|
852
|
+
}
|
|
853
|
+
stopPlayback();
|
|
854
|
+
const element = {
|
|
855
|
+
id: makeId('element'),
|
|
856
|
+
name: `Text ${scene.elements.length + 1}`,
|
|
857
|
+
type: 'text',
|
|
858
|
+
layerId: layer.id,
|
|
859
|
+
text: 'Type your text',
|
|
860
|
+
fontFamily: 'Arial',
|
|
861
|
+
fontSize: 32,
|
|
862
|
+
textColor: '#f4f6fb',
|
|
863
|
+
textAlign: 'center',
|
|
864
|
+
bold: false,
|
|
865
|
+
x: geometry.x ?? workingStage().width / 2,
|
|
866
|
+
y: geometry.y ?? workingStage().height / 2,
|
|
867
|
+
width: geometry.width ?? 280,
|
|
868
|
+
height: geometry.height ?? 72,
|
|
869
|
+
scaleX: 1,
|
|
870
|
+
scaleY: 1,
|
|
871
|
+
rotation: 0,
|
|
872
|
+
skew: 0,
|
|
873
|
+
opacity: 1,
|
|
874
|
+
fill: '#f4f6fb',
|
|
875
|
+
stroke: '#f4f6fb',
|
|
876
|
+
strokeWidth: 0,
|
|
877
|
+
buttonAction: null,
|
|
878
|
+
keyframes: [],
|
|
879
|
+
};
|
|
880
|
+
startTrack(element, playhead);
|
|
881
|
+
scene.elements.push(element);
|
|
882
|
+
selectedElementIds = [element.id];
|
|
883
|
+
activeTool = 'select';
|
|
884
|
+
renderAll();
|
|
885
|
+
openTextEditor(element);
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
function updateTextEditorPosition() {
|
|
889
|
+
const element = activeScene()?.elements.find(item => item.id === editingTextElementId);
|
|
890
|
+
if (!element) {
|
|
891
|
+
elements.textEditLayer.hidden = true;
|
|
892
|
+
return;
|
|
893
|
+
}
|
|
894
|
+
elements.textEditLayer.hidden = false;
|
|
895
|
+
const pose = poseAt(element, playhead);
|
|
896
|
+
const canvasRect = elements.canvas.getBoundingClientRect();
|
|
897
|
+
const layerRect = elements.textEditLayer.getBoundingClientRect();
|
|
898
|
+
const input = elements.textEditInput;
|
|
899
|
+
const { a, b, c, d } = matrixComponents(pose);
|
|
900
|
+
input.style.left = `${canvasRect.left - layerRect.left + (pose.x / workingStage().width) * canvasRect.width}px`;
|
|
901
|
+
input.style.top = `${canvasRect.top - layerRect.top + (pose.y / workingStage().height) * canvasRect.height}px`;
|
|
902
|
+
input.style.width = `${(pose.width / workingStage().width) * canvasRect.width}px`;
|
|
903
|
+
input.style.height = `${(pose.height / workingStage().height) * canvasRect.height}px`;
|
|
904
|
+
input.style.transform = `translate(-50%, -50%) matrix(${a}, ${b}, ${c}, ${d}, 0, 0)`;
|
|
905
|
+
input.style.fontFamily = editorFieldFont(element, pose);
|
|
906
|
+
input.style.fontSize = `${pose.fontSize * canvasRect.width / workingStage().width}px`;
|
|
907
|
+
input.style.fontWeight = pose.bold ? '700' : '400';
|
|
908
|
+
input.style.textAlign = pose.textAlign;
|
|
909
|
+
input.style.color = pose.textColor;
|
|
910
|
+
input.style.opacity = '1';
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
function openTextEditor(element) {
|
|
914
|
+
const scene = activeScene();
|
|
915
|
+
if (element.type !== 'text' || !visibleAt(element, playhead)) return;
|
|
916
|
+
if (isElementLocked(scene, element)) {
|
|
917
|
+
showStatus('Unlock the layer to edit this text', true);
|
|
918
|
+
return;
|
|
919
|
+
}
|
|
920
|
+
if (editingTextElementId && editingTextElementId !== element.id) closeTextEditor(true);
|
|
921
|
+
if (playing) stopPlayback();
|
|
922
|
+
selectedElementIds = [element.id];
|
|
923
|
+
activeTool = 'select';
|
|
924
|
+
editingTextElementId = element.id;
|
|
925
|
+
originalTextDuringEdit = { text: element.text, keyframes: structuredClone(element.keyframes), field: structuredClone(element.field) };
|
|
926
|
+
elements.textEditInput.value = fieldText(element, poseAt(element, playhead));
|
|
927
|
+
renderAll();
|
|
928
|
+
updateTextEditorPosition();
|
|
929
|
+
elements.textEditInput.focus();
|
|
930
|
+
elements.textEditInput.select();
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
function closeTextEditor(commit) {
|
|
934
|
+
const element = activeScene()?.elements.find(item => item.id === editingTextElementId);
|
|
935
|
+
if (element && !commit) Object.assign(element, originalTextDuringEdit);
|
|
936
|
+
editingTextElementId = null;
|
|
937
|
+
originalTextDuringEdit = null;
|
|
938
|
+
elements.textEditLayer.hidden = true;
|
|
939
|
+
renderAll();
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
function finishPendingPath(closed = false) {
|
|
943
|
+
if (!pendingPath) return;
|
|
944
|
+
const drawing = pendingPath;
|
|
945
|
+
const scene = activeScene();
|
|
946
|
+
const layer = activeLayer();
|
|
947
|
+
if (!scene || !layer) {
|
|
948
|
+
pendingPath = null;
|
|
949
|
+
showStatus('No active scene is available for this path', true);
|
|
950
|
+
renderAll();
|
|
951
|
+
return;
|
|
952
|
+
}
|
|
953
|
+
if (layer.locked) {
|
|
954
|
+
pendingPath = null;
|
|
955
|
+
showStatus('Unlock the active layer before drawing on it', true);
|
|
956
|
+
renderAll();
|
|
957
|
+
return;
|
|
958
|
+
}
|
|
959
|
+
const isClosed = closed || drawing.kind === 'polygon';
|
|
960
|
+
if (drawing.points.length < (isClosed ? 3 : 2)) {
|
|
961
|
+
renderAll();
|
|
962
|
+
showStatus(isClosed ? 'A closed shape needs at least three points' : 'A path needs at least two points', true);
|
|
963
|
+
return;
|
|
964
|
+
}
|
|
965
|
+
pendingPath = null;
|
|
966
|
+
|
|
967
|
+
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
|
|
968
|
+
for (const contour of [drawing.points, ...(drawing.subpaths ?? [])]) {
|
|
969
|
+
for (const point of contour) {
|
|
970
|
+
minX = Math.min(minX, point.x, point.x + point.handleIn.x, point.x + point.handleOut.x);
|
|
971
|
+
maxX = Math.max(maxX, point.x, point.x + point.handleIn.x, point.x + point.handleOut.x);
|
|
972
|
+
minY = Math.min(minY, point.y, point.y + point.handleIn.y, point.y + point.handleOut.y);
|
|
973
|
+
maxY = Math.max(maxY, point.y, point.y + point.handleIn.y, point.y + point.handleOut.y);
|
|
974
|
+
}
|
|
975
|
+
}
|
|
976
|
+
const centerX = (minX + maxX) / 2;
|
|
977
|
+
const centerY = (minY + maxY) / 2;
|
|
978
|
+
const element = {
|
|
979
|
+
id: makeId('element'),
|
|
980
|
+
name: `${({ polygon: 'Polygon', brush: 'Brush', pencil: 'Pencil', bucket: 'Fill' })[drawing.kind] ?? 'Path'} ${(scene?.elements.length ?? 0) + 1}`,
|
|
981
|
+
type: 'path',
|
|
982
|
+
layerId: layer.id,
|
|
983
|
+
points: drawing.points.map(point => ({
|
|
984
|
+
x: point.x - centerX,
|
|
985
|
+
y: point.y - centerY,
|
|
986
|
+
handleIn: { x: point.handleIn.x, y: point.handleIn.y },
|
|
987
|
+
handleOut: { x: point.handleOut.x, y: point.handleOut.y },
|
|
988
|
+
})),
|
|
989
|
+
closed: isClosed,
|
|
990
|
+
x: centerX,
|
|
991
|
+
y: centerY,
|
|
992
|
+
width: Math.max(1, maxX - minX),
|
|
993
|
+
height: Math.max(1, maxY - minY),
|
|
994
|
+
scaleX: 1,
|
|
995
|
+
scaleY: 1,
|
|
996
|
+
rotation: 0,
|
|
997
|
+
skew: 0,
|
|
998
|
+
opacity: 1,
|
|
999
|
+
fill: '#7f9cff',
|
|
1000
|
+
stroke: '#e8f3ef',
|
|
1001
|
+
strokeWidth: 3,
|
|
1002
|
+
text: '',
|
|
1003
|
+
fontFamily: 'Arial',
|
|
1004
|
+
fontSize: 32,
|
|
1005
|
+
textColor: '#f4f6fb',
|
|
1006
|
+
textAlign: 'center',
|
|
1007
|
+
bold: false,
|
|
1008
|
+
buttonAction: null,
|
|
1009
|
+
keyframes: [],
|
|
1010
|
+
};
|
|
1011
|
+
if (['brush', 'pencil', 'bucket'].includes(drawing.kind)) {
|
|
1012
|
+
element.stroke = drawing.color;
|
|
1013
|
+
element.fill = drawing.color;
|
|
1014
|
+
element.strokeWidth = drawing.kind === 'pencil' ? drawing.size : 0;
|
|
1015
|
+
if (drawing.gradient) element.gradient = structuredClone(drawing.gradient);
|
|
1016
|
+
if (drawing.subpaths?.length) element.subpaths = drawing.subpaths.map(ring => ring.map(point =>
|
|
1017
|
+
({ ...point, x: point.x - centerX, y: point.y - centerY })));
|
|
1018
|
+
}
|
|
1019
|
+
startTrack(element, playhead);
|
|
1020
|
+
scene.elements.push(element);
|
|
1021
|
+
if (!['brush', 'pencil', 'bucket'].includes(drawing.kind)) activeTool = 'select';
|
|
1022
|
+
selectedElementIds = [element.id];
|
|
1023
|
+
renderAll();
|
|
1024
|
+
showStatus(`${element.name} created`);
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
function cancelPendingPath() {
|
|
1028
|
+
if (!pendingPath) return;
|
|
1029
|
+
pendingPath = null;
|
|
1030
|
+
renderAll();
|
|
1031
|
+
showStatus('Path drawing cancelled');
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
function removeSelectedElement() {
|
|
1035
|
+
const scene = activeScene();
|
|
1036
|
+
const members = selectedMembers(scene);
|
|
1037
|
+
if (!members.length || isInteractivePreview()) return;
|
|
1038
|
+
if (members.some(item => isElementLocked(scene, item))) {
|
|
1039
|
+
showStatus('Unlock the layer before deleting these objects', true);
|
|
1040
|
+
return;
|
|
1041
|
+
}
|
|
1042
|
+
if (editingTextElementId) closeTextEditor(true);
|
|
1043
|
+
removeObjects(scene, selectedElementIds);
|
|
1044
|
+
selectedElementIds = [];
|
|
1045
|
+
renderAll();
|
|
1046
|
+
reportObjectEdit(members.length === 1 ? 'Element deleted' : `${members.length} elements deleted`, members);
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
function reportObjectEdit(message, previousObjects) {
|
|
1050
|
+
const references = scriptReferenceWarnings(project, previousObjects);
|
|
1051
|
+
showStatus([message, ...references].join('. '), references.length > 0);
|
|
1052
|
+
if (references.length) window.clearTimeout(statusTimeout);
|
|
1053
|
+
}
|
|
1054
|
+
|
|
1055
|
+
function selectScene(sceneId) {
|
|
1056
|
+
if (playing || previewMode) stopPlayback(true);
|
|
1057
|
+
if (editingTextElementId) closeTextEditor(true);
|
|
1058
|
+
if (pendingPath) cancelPendingPath();
|
|
1059
|
+
if (project.scenes.some(item => item.id === sceneId)) returnViews = [];
|
|
1060
|
+
selectedSceneId = sceneId;
|
|
1061
|
+
selectedLayerId = orderedSceneLayers(activeScene()).at(-1)?.id ?? null;
|
|
1062
|
+
pendingLayerDeleteId = null;
|
|
1063
|
+
editingLayerId = null;
|
|
1064
|
+
selectedElementIds = [];
|
|
1065
|
+
playhead = activeScene()?.startFrame ?? 1;
|
|
1066
|
+
renderAll();
|
|
1067
|
+
}
|
|
1068
|
+
|
|
1069
|
+
function addScene() {
|
|
1070
|
+
if (playing || previewMode) stopPlayback(true);
|
|
1071
|
+
if (editingTextElementId) closeTextEditor(true);
|
|
1072
|
+
if (pendingPath) cancelPendingPath();
|
|
1073
|
+
const scene = makeScene(`Scene ${project.scenes.length + 1}`);
|
|
1074
|
+
returnViews = [];
|
|
1075
|
+
project.scenes.push(scene);
|
|
1076
|
+
selectedSceneId = scene.id;
|
|
1077
|
+
selectedLayerId = scene.layers[0].id;
|
|
1078
|
+
pendingLayerDeleteId = null;
|
|
1079
|
+
editingLayerId = null;
|
|
1080
|
+
selectedElementIds = [];
|
|
1081
|
+
playhead = 1;
|
|
1082
|
+
renderAll();
|
|
1083
|
+
elements.sceneName.focus();
|
|
1084
|
+
elements.sceneName.select();
|
|
1085
|
+
showStatus(`${scene.name} added`);
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
function deleteScene() {
|
|
1089
|
+
if (returnViews.length) return;
|
|
1090
|
+
if (editingTextElementId) closeTextEditor(true);
|
|
1091
|
+
if (pendingPath) cancelPendingPath();
|
|
1092
|
+
let result;
|
|
1093
|
+
try {
|
|
1094
|
+
result = removeProjectScene(project, selectedSceneId);
|
|
1095
|
+
} catch (error) {
|
|
1096
|
+
showStatus(error.message, true);
|
|
1097
|
+
return;
|
|
1098
|
+
}
|
|
1099
|
+
const { removed, next } = result;
|
|
1100
|
+
selectedSceneId = next.id;
|
|
1101
|
+
selectedLayerId = orderedSceneLayers(next).at(-1)?.id ?? null;
|
|
1102
|
+
pendingLayerDeleteId = null;
|
|
1103
|
+
editingLayerId = null;
|
|
1104
|
+
selectedElementIds = [];
|
|
1105
|
+
stopPlayback(true);
|
|
1106
|
+
reportObjectEdit(`${removed.name} deleted`, removed.elements);
|
|
1107
|
+
}
|
|
1108
|
+
|
|
1109
|
+
function renderSceneList() {
|
|
1110
|
+
elements.sceneList.replaceChildren();
|
|
1111
|
+
project.scenes.forEach((scene, index) => {
|
|
1112
|
+
const button = document.createElement('button');
|
|
1113
|
+
button.type = 'button';
|
|
1114
|
+
button.className = `scene-entry${scene.id === selectedSceneId ? ' is-active' : ''}`;
|
|
1115
|
+
button.setAttribute('aria-current', scene.id === selectedSceneId ? 'true' : 'false');
|
|
1116
|
+
button.addEventListener('click', () => selectScene(scene.id));
|
|
1117
|
+
|
|
1118
|
+
const number = document.createElement('span');
|
|
1119
|
+
number.className = 'scene-index';
|
|
1120
|
+
number.textContent = String(index + 1).padStart(2, '0');
|
|
1121
|
+
const label = document.createElement('span');
|
|
1122
|
+
label.className = 'entry-label';
|
|
1123
|
+
label.textContent = scene.name;
|
|
1124
|
+
button.append(number, label);
|
|
1125
|
+
elements.sceneList.append(button);
|
|
1126
|
+
});
|
|
1127
|
+
elements.deleteScene.disabled = project.scenes.length <= 1 || isInteractivePreview();
|
|
1128
|
+
}
|
|
1129
|
+
|
|
1130
|
+
function renderLayerDeletePrompt(scene) {
|
|
1131
|
+
const layer = pendingLayerDeleteId
|
|
1132
|
+
? scene?.layers?.find(item => item.id === pendingLayerDeleteId)
|
|
1133
|
+
: null;
|
|
1134
|
+
if (!scene || !layer || scene.layers.length <= 1) {
|
|
1135
|
+
pendingLayerDeleteId = null;
|
|
1136
|
+
elements.layerDeletePrompt.hidden = true;
|
|
1137
|
+
return;
|
|
1138
|
+
}
|
|
1139
|
+
const count = scene.elements.filter(element => element.layerId === layer.id).length;
|
|
1140
|
+
if (count === 0) {
|
|
1141
|
+
pendingLayerDeleteId = null;
|
|
1142
|
+
elements.layerDeletePrompt.hidden = true;
|
|
1143
|
+
return;
|
|
1144
|
+
}
|
|
1145
|
+
elements.layerDeletePrompt.hidden = false;
|
|
1146
|
+
elements.layerDeleteMessage.textContent = `"${layer.name}" contains ${count} element${count === 1 ? '' : 's'}. Choose what to do with them:`;
|
|
1147
|
+
elements.layerDeleteTarget.replaceChildren();
|
|
1148
|
+
orderedSceneLayers(scene)
|
|
1149
|
+
.filter(item => item.id !== layer.id)
|
|
1150
|
+
.forEach(item => {
|
|
1151
|
+
const option = document.createElement('option');
|
|
1152
|
+
option.value = item.id;
|
|
1153
|
+
option.textContent = item.name;
|
|
1154
|
+
elements.layerDeleteTarget.append(option);
|
|
1155
|
+
});
|
|
1156
|
+
}
|
|
1157
|
+
|
|
1158
|
+
const collapsedLayers = new WeakSet();
|
|
1159
|
+
// Large scenes (imported movies can have thousands of objects) open with their layers collapsed,
|
|
1160
|
+
// so the timeline builds one summary row per layer instead of one lane per object. A layer the
|
|
1161
|
+
// author expands, or one holding the selection, shows its lanes.
|
|
1162
|
+
const LARGE_SCENE = 200;
|
|
1163
|
+
const expandedLayers = new WeakSet();
|
|
1164
|
+
function isLayerCollapsed(scene, layer, largeTimeline) {
|
|
1165
|
+
if (collapsedLayers.has(layer)) return true;
|
|
1166
|
+
if (!largeTimeline || expandedLayers.has(layer)) return false;
|
|
1167
|
+
return !selectedElementIds.some(id => scene.elements.find(element => element.id === id)?.layerId === layer.id);
|
|
1168
|
+
}
|
|
1169
|
+
|
|
1170
|
+
function renderLayerList() {
|
|
1171
|
+
const scene = activeScene();
|
|
1172
|
+
const focused = document.activeElement;
|
|
1173
|
+
const focusedRow = focused.closest('.layer-controls')?.closest('.layer-entry');
|
|
1174
|
+
const layerId = focusedRow?.dataset.id;
|
|
1175
|
+
const actionIndex = focusedRow ? [...focusedRow.querySelectorAll('.layer-controls button')].indexOf(focused) : -1;
|
|
1176
|
+
elements.layerList.replaceChildren();
|
|
1177
|
+
if (!scene) {
|
|
1178
|
+
elements.layerDeletePrompt.hidden = true;
|
|
1179
|
+
return;
|
|
1180
|
+
}
|
|
1181
|
+
const currentLayer = activeLayer();
|
|
1182
|
+
selectedLayerId = currentLayer?.id ?? null;
|
|
1183
|
+
const lockedUi = isInteractivePreview();
|
|
1184
|
+
const layersTopDown = [...orderedSceneLayers(scene)].reverse();
|
|
1185
|
+
const largeTimeline = scene.elements.length > LARGE_SCENE || scene.elements.some(element => element.keyframes.length > LARGE_SCENE);
|
|
1186
|
+
|
|
1187
|
+
layersTopDown.forEach((layer, topIndex) => {
|
|
1188
|
+
const row = document.createElement('div');
|
|
1189
|
+
row.className = `layer-entry${layer.id === selectedLayerId ? ' is-active' : ''}${layer.visible === false ? ' is-hidden-layer' : ''}`;
|
|
1190
|
+
row.setAttribute('role', 'listitem');
|
|
1191
|
+
row.dataset.id = layer.id;
|
|
1192
|
+
const controls = document.createElement('div');
|
|
1193
|
+
controls.className = 'layer-controls';
|
|
1194
|
+
const tracks = document.createElement('div');
|
|
1195
|
+
tracks.className = 'layer-tracks';
|
|
1196
|
+
tracks.id = 'tracks-' + layer.id;
|
|
1197
|
+
const overview = document.createElement('div');
|
|
1198
|
+
overview.className = 'layer-overview';
|
|
1199
|
+
overview.setAttribute('aria-hidden', 'true');
|
|
1200
|
+
const fold = document.createElement('button');
|
|
1201
|
+
fold.className = 'layer-fold';
|
|
1202
|
+
fold.type = 'button';
|
|
1203
|
+
fold.setAttribute('aria-controls', tracks.id);
|
|
1204
|
+
function updateFold() {
|
|
1205
|
+
tracks.hidden = isLayerCollapsed(scene, layer, largeTimeline);
|
|
1206
|
+
fold.setAttribute('aria-expanded', String(!tracks.hidden));
|
|
1207
|
+
fold.title = (tracks.hidden ? 'Expand ' : 'Collapse ') + layer.name;
|
|
1208
|
+
fold.setAttribute('aria-label', fold.title);
|
|
1209
|
+
}
|
|
1210
|
+
fold.onclick = () => {
|
|
1211
|
+
if (tracks.hidden) {
|
|
1212
|
+
collapsedLayers.delete(layer);
|
|
1213
|
+
expandedLayers.add(layer);
|
|
1214
|
+
} else {
|
|
1215
|
+
collapsedLayers.add(layer);
|
|
1216
|
+
expandedLayers.delete(layer);
|
|
1217
|
+
}
|
|
1218
|
+
updateFold();
|
|
1219
|
+
// Collapsed layers have no lanes built; build them now.
|
|
1220
|
+
timeline.render(activeScene(), selectedElementIds, playhead, isInteractivePreview(), false);
|
|
1221
|
+
};
|
|
1222
|
+
updateFold();
|
|
1223
|
+
|
|
1224
|
+
const main = document.createElement('div');
|
|
1225
|
+
main.className = 'layer-entry-main';
|
|
1226
|
+
if (editingLayerId === layer.id && !lockedUi) {
|
|
1227
|
+
const input = document.createElement('input');
|
|
1228
|
+
input.type = 'text';
|
|
1229
|
+
input.className = 'layer-rename-input';
|
|
1230
|
+
input.maxLength = 48;
|
|
1231
|
+
input.value = layer.name;
|
|
1232
|
+
input.setAttribute('aria-label', `Rename ${layer.name}`);
|
|
1233
|
+
const commit = () => {
|
|
1234
|
+
if (editingLayerId !== layer.id) return;
|
|
1235
|
+
editingLayerId = null;
|
|
1236
|
+
try {
|
|
1237
|
+
renameSceneLayer(scene, layer.id, input.value);
|
|
1238
|
+
} catch (error) {
|
|
1239
|
+
showStatus(error.message, true);
|
|
1240
|
+
}
|
|
1241
|
+
renderAll();
|
|
1242
|
+
};
|
|
1243
|
+
input.addEventListener('keydown', event => {
|
|
1244
|
+
if (event.key === 'Enter') {
|
|
1245
|
+
event.preventDefault();
|
|
1246
|
+
commit();
|
|
1247
|
+
} else if (event.key === 'Escape') {
|
|
1248
|
+
event.preventDefault();
|
|
1249
|
+
editingLayerId = null;
|
|
1250
|
+
renderAll();
|
|
1251
|
+
}
|
|
1252
|
+
});
|
|
1253
|
+
input.addEventListener('blur', commit);
|
|
1254
|
+
main.append(input);
|
|
1255
|
+
queueMicrotask(() => {
|
|
1256
|
+
input.focus();
|
|
1257
|
+
input.select();
|
|
1258
|
+
});
|
|
1259
|
+
} else {
|
|
1260
|
+
const selectBtn = document.createElement('button');
|
|
1261
|
+
selectBtn.type = 'button';
|
|
1262
|
+
selectBtn.className = 'layer-select-btn';
|
|
1263
|
+
selectBtn.textContent = layer.name;
|
|
1264
|
+
selectBtn.dataset.layerId = layer.id;
|
|
1265
|
+
selectBtn.disabled = lockedUi;
|
|
1266
|
+
selectBtn.setAttribute('aria-pressed', String(selectedLayerId === layer.id));
|
|
1267
|
+
selectBtn.title = `${layer.name} (F2 or double-click to rename)`;
|
|
1268
|
+
selectBtn.setAttribute('aria-keyshortcuts', 'F2');
|
|
1269
|
+
selectBtn.addEventListener('click', () => {
|
|
1270
|
+
if (selectedLayerId === layer.id) return;
|
|
1271
|
+
if (editingTextElementId) closeTextEditor(true);
|
|
1272
|
+
selectedLayerId = layer.id;
|
|
1273
|
+
selectedElementIds = [];
|
|
1274
|
+
// Keep the layer button mounted for focus and double-click rename.
|
|
1275
|
+
for (const entry of elements.layerList.children) {
|
|
1276
|
+
const active = entry.querySelector('[data-layer-id]')?.dataset.layerId === layer.id;
|
|
1277
|
+
entry.classList.toggle('is-active', active);
|
|
1278
|
+
entry.querySelector('.layer-select-btn')?.setAttribute('aria-pressed', String(active));
|
|
1279
|
+
}
|
|
1280
|
+
renderElementList();
|
|
1281
|
+
renderInspector();
|
|
1282
|
+
renderControls();
|
|
1283
|
+
renderCanvas();
|
|
1284
|
+
timeline.render(scene, selectedElementIds, playhead, false, false);
|
|
1285
|
+
renderSymbolLibrary(project.symbols, scene, !!returnViews.length, false, layer.locked);
|
|
1286
|
+
updateHistoryControls();
|
|
1287
|
+
});
|
|
1288
|
+
const beginRename = () => {
|
|
1289
|
+
if (isInteractivePreview()) return;
|
|
1290
|
+
editingLayerId = layer.id;
|
|
1291
|
+
renderAll();
|
|
1292
|
+
};
|
|
1293
|
+
selectBtn.addEventListener('dblclick', beginRename);
|
|
1294
|
+
selectBtn.addEventListener('keydown', event => {
|
|
1295
|
+
if (event.key === 'F2') {
|
|
1296
|
+
event.preventDefault();
|
|
1297
|
+
beginRename();
|
|
1298
|
+
}
|
|
1299
|
+
});
|
|
1300
|
+
main.append(selectBtn);
|
|
1301
|
+
}
|
|
1302
|
+
|
|
1303
|
+
const actions = document.createElement('div');
|
|
1304
|
+
actions.className = 'layer-actions';
|
|
1305
|
+
|
|
1306
|
+
const makeAction = (label, title, onClick, { disabled = false, active = false } = {}) => {
|
|
1307
|
+
const btn = document.createElement('button');
|
|
1308
|
+
btn.type = 'button';
|
|
1309
|
+
btn.className = `layer-action-btn${active ? ' is-on' : ''}`;
|
|
1310
|
+
btn.textContent = label;
|
|
1311
|
+
btn.title = title;
|
|
1312
|
+
btn.setAttribute('aria-label', title + ' · ' + layer.name);
|
|
1313
|
+
btn.disabled = lockedUi || disabled;
|
|
1314
|
+
btn.addEventListener('click', onClick);
|
|
1315
|
+
return btn;
|
|
1316
|
+
};
|
|
1317
|
+
|
|
1318
|
+
const upBtn = makeAction('↑', 'Move layer up', () => {
|
|
1319
|
+
reorderSceneLayer(scene, layer.id, 'up');
|
|
1320
|
+
renderAll();
|
|
1321
|
+
}, { disabled: topIndex === 0 });
|
|
1322
|
+
|
|
1323
|
+
const downBtn = makeAction('↓', 'Move layer down', () => {
|
|
1324
|
+
reorderSceneLayer(scene, layer.id, 'down');
|
|
1325
|
+
renderAll();
|
|
1326
|
+
}, { disabled: topIndex === layersTopDown.length - 1 });
|
|
1327
|
+
|
|
1328
|
+
const visBtn = makeAction('', layer.visible === false ? 'Show layer' : 'Hide layer', () => {
|
|
1329
|
+
layer.visible = layer.visible === false;
|
|
1330
|
+
if (!layer.visible && selectedMembers(scene).some(item => item.layerId === layer.id)) {
|
|
1331
|
+
selectedElementIds = [];
|
|
1332
|
+
}
|
|
1333
|
+
renderAll();
|
|
1334
|
+
}, { active: layer.visible === false });
|
|
1335
|
+
visBtn.append(layerIcon(layer.visible === false ? 'hidden' : 'visible'));
|
|
1336
|
+
visBtn.classList.add(layer.visible === false ? 'layer-show' : 'layer-hide');
|
|
1337
|
+
visBtn.setAttribute('aria-pressed', String(layer.visible === false));
|
|
1338
|
+
|
|
1339
|
+
const lockBtn = makeAction('', layer.locked ? 'Unlock layer' : 'Lock layer', () => {
|
|
1340
|
+
layer.locked = !layer.locked;
|
|
1341
|
+
if (layer.locked && editingTextElementId) {
|
|
1342
|
+
const editing = scene.elements.find(item => item.id === editingTextElementId);
|
|
1343
|
+
if (editing?.layerId === layer.id) closeTextEditor(true);
|
|
1344
|
+
}
|
|
1345
|
+
renderAll();
|
|
1346
|
+
}, { active: layer.locked });
|
|
1347
|
+
lockBtn.append(layerIcon(layer.locked ? 'locked' : 'unlocked'));
|
|
1348
|
+
lockBtn.classList.add(layer.locked ? 'layer-unlock' : 'layer-lock');
|
|
1349
|
+
lockBtn.setAttribute('aria-pressed', String(layer.locked));
|
|
1350
|
+
|
|
1351
|
+
const delBtn = makeAction('×', 'Delete layer', () => {
|
|
1352
|
+
if (scene.layers.length <= 1) {
|
|
1353
|
+
showStatus('A scene must keep at least one layer', true);
|
|
1354
|
+
return;
|
|
1355
|
+
}
|
|
1356
|
+
const hasElements = scene.elements.some(element => element.layerId === layer.id);
|
|
1357
|
+
if (hasElements) {
|
|
1358
|
+
pendingLayerDeleteId = layer.id;
|
|
1359
|
+
renderLayerDeletePrompt(scene);
|
|
1360
|
+
elements.layerDeleteTarget.focus();
|
|
1361
|
+
return;
|
|
1362
|
+
}
|
|
1363
|
+
removeSceneLayer(scene, layer.id);
|
|
1364
|
+
if (selectedLayerId === layer.id) {
|
|
1365
|
+
selectedLayerId = orderedSceneLayers(scene).at(-1)?.id ?? null;
|
|
1366
|
+
}
|
|
1367
|
+
renderAll();
|
|
1368
|
+
showStatus(`${layer.name} deleted`);
|
|
1369
|
+
}, { disabled: scene.layers.length <= 1 });
|
|
1370
|
+
|
|
1371
|
+
actions.append(upBtn, downBtn, visBtn, lockBtn, delBtn);
|
|
1372
|
+
controls.append(fold, main, actions);
|
|
1373
|
+
row.append(controls, overview, tracks);
|
|
1374
|
+
elements.layerList.append(row);
|
|
1375
|
+
});
|
|
1376
|
+
|
|
1377
|
+
if (layerId && !editingLayerId) {
|
|
1378
|
+
const row = [...elements.layerList.children].find(entry => entry.dataset.id === layerId);
|
|
1379
|
+
const action = row?.querySelectorAll('.layer-controls button')[actionIndex];
|
|
1380
|
+
const next = action && !action.disabled ? action : (row ?? elements.layerList.querySelector('.is-active'))?.querySelector('.layer-select-btn');
|
|
1381
|
+
next?.focus();
|
|
1382
|
+
}
|
|
1383
|
+
elements.addLayer.disabled = lockedUi;
|
|
1384
|
+
renderLayerDeletePrompt(scene);
|
|
1385
|
+
}
|
|
1386
|
+
|
|
1387
|
+
function selectedMembers(scene = activeScene()) {
|
|
1388
|
+
return scene?.elements.filter(item => selectedElementIds.includes(item.id)) ?? [];
|
|
1389
|
+
}
|
|
1390
|
+
|
|
1391
|
+
function selectObjects(items, extend) {
|
|
1392
|
+
const first = extend && selectedMembers()[0];
|
|
1393
|
+
if (first && items.some(item => item.layerId !== first.layerId)) {
|
|
1394
|
+
showStatus('Select objects on the same layer', true);
|
|
1395
|
+
return;
|
|
1396
|
+
}
|
|
1397
|
+
const ids = items.map(item => item.id);
|
|
1398
|
+
if (!extend) selectedElementIds = ids;
|
|
1399
|
+
else if (ids.every(id => selectedElementIds.includes(id))) selectedElementIds = selectedElementIds.filter(id => !ids.includes(id));
|
|
1400
|
+
else selectedElementIds = [...new Set([...selectedElementIds, ...ids])];
|
|
1401
|
+
if (items.length) selectedLayerId = items[0].layerId;
|
|
1402
|
+
if (selectedElementIds.length === 1) preferredSymbol = selectedElement()?.symbolId;
|
|
1403
|
+
}
|
|
1404
|
+
|
|
1405
|
+
function renderElementList() {
|
|
1406
|
+
const scene = activeScene();
|
|
1407
|
+
const members = selectedMembers(scene);
|
|
1408
|
+
const locked = isInteractivePreview() || !members.length || isElementLocked(scene, members[0]);
|
|
1409
|
+
const wholeGroup = members[0]?.groupId && members.every(item => item.groupId === members[0].groupId) &&
|
|
1410
|
+
groupMembers(scene, members[0]).length === members.length;
|
|
1411
|
+
elements.groupObjects.disabled = locked || members.length < 2 || wholeGroup;
|
|
1412
|
+
elements.ungroupObjects.disabled = locked || !members.some(item => item.groupId);
|
|
1413
|
+
elements.raiseObjects.disabled = elements.lowerObjects.disabled = locked;
|
|
1414
|
+
elements.objectHint.hidden = scene.elements.length < 2;
|
|
1415
|
+
elements.elementCount.textContent = String(scene.elements.length);
|
|
1416
|
+
elements.emptyElements.hidden = scene.elements.length > 0;
|
|
1417
|
+
// The list holds a row per object (thousands in an imported movie): for large scenes, build it
|
|
1418
|
+
// only while its tab is open. Opening the tab builds it (see objectsPanelObserver).
|
|
1419
|
+
if (objectsPanel.hidden && scene.elements.length > LARGE_SCENE) return;
|
|
1420
|
+
renderObjects(elements.elementList, project, scene, selectedElementIds, (items, extend) => {
|
|
1421
|
+
selectObjects(items, extend);
|
|
1422
|
+
renderAll();
|
|
1423
|
+
}, isInteractivePreview());
|
|
1424
|
+
}
|
|
1425
|
+
const objectsPanel = document.querySelector('#objects-panel');
|
|
1426
|
+
const objectsPanelObserver = new MutationObserver(() => { if (!objectsPanel.hidden) renderElementList(); });
|
|
1427
|
+
objectsPanelObserver.observe(objectsPanel, { attributeFilter: ['hidden'] });
|
|
1428
|
+
|
|
1429
|
+
function arrangeObjects(operation) {
|
|
1430
|
+
if (isInteractivePreview() || dragState) return;
|
|
1431
|
+
if (editingTextElementId) closeTextEditor(true);
|
|
1432
|
+
const scene = activeScene();
|
|
1433
|
+
const members = selectedMembers(scene);
|
|
1434
|
+
if (!members.length) return;
|
|
1435
|
+
if (operation === 'group' && elements.groupObjects.disabled) return;
|
|
1436
|
+
try {
|
|
1437
|
+
if (operation === 'group') groupElements(scene, members, makeId('group'));
|
|
1438
|
+
else if (operation === 'ungroup') ungroupElements(scene, members);
|
|
1439
|
+
else if (!reorderElements(scene, members, operation === 'forward' ? 1 : -1)) {
|
|
1440
|
+
showStatus('Already at the edge of the stacking order');
|
|
1441
|
+
return;
|
|
1442
|
+
}
|
|
1443
|
+
renderAll();
|
|
1444
|
+
} catch (error) {
|
|
1445
|
+
showStatus(error.message, true);
|
|
1446
|
+
}
|
|
1447
|
+
}
|
|
1448
|
+
|
|
1449
|
+
function renderButtonInspector(element, scene, locked) {
|
|
1450
|
+
const action = element.buttonAction;
|
|
1451
|
+
elements.inputText.checked = isEditableText(element);
|
|
1452
|
+
elements.inputText.disabled = locked || Boolean(action);
|
|
1453
|
+
elements.elementIsButton.disabled = locked || isEditableText(element);
|
|
1454
|
+
elements.elementIsButton.checked = Boolean(action);
|
|
1455
|
+
elements.buttonActionFields.hidden = !action;
|
|
1456
|
+
if (!action) {
|
|
1457
|
+
elements.buttonActionWarning.hidden = true;
|
|
1458
|
+
return;
|
|
1459
|
+
}
|
|
1460
|
+
|
|
1461
|
+
elements.buttonTrigger.value = action.trigger;
|
|
1462
|
+
elements.buttonKey.closest('label').hidden = !isKeyTrigger(action.trigger);
|
|
1463
|
+
elements.buttonKey.value = action.key ?? 'Enter';
|
|
1464
|
+
elements.buttonSwipe.closest('label').hidden = action.trigger !== 'swipe';
|
|
1465
|
+
elements.buttonSwipe.value = action.direction ?? 'left';
|
|
1466
|
+
elements.buttonActionType.value = action.type;
|
|
1467
|
+
const scriptButton = document.querySelector('#button-edit-script');
|
|
1468
|
+
scriptButton.hidden = action.type !== 'script';
|
|
1469
|
+
scriptButton.disabled = locked;
|
|
1470
|
+
elements.buttonTargetSceneWrap.hidden = action.type !== 'gotoScene';
|
|
1471
|
+
elements.buttonTargetFrameWrap.hidden = action.type !== 'gotoFrame';
|
|
1472
|
+
const editsInput = action.type === 'editInput';
|
|
1473
|
+
elements.buttonTargetElementWrap.hidden = action.type !== 'toggleVisibility' && !editsInput;
|
|
1474
|
+
elements.jumpPlay.closest('label').hidden = !['gotoScene', 'gotoFrame'].includes(action.type);
|
|
1475
|
+
elements.jumpPlay.checked = Boolean(action.play);
|
|
1476
|
+
elements.inputOperation.closest('label').hidden = !editsInput;
|
|
1477
|
+
elements.inputOperation.value = action.operation || 'insert';
|
|
1478
|
+
elements.insertValue.closest('label').hidden = !editsInput || action.operation !== 'insert';
|
|
1479
|
+
elements.insertValue.value = action.value ?? '';
|
|
1480
|
+
|
|
1481
|
+
elements.buttonTargetScene.replaceChildren();
|
|
1482
|
+
const emptySceneOption = document.createElement('option');
|
|
1483
|
+
emptySceneOption.value = '';
|
|
1484
|
+
emptySceneOption.textContent = '-- Select scene --';
|
|
1485
|
+
elements.buttonTargetScene.append(emptySceneOption);
|
|
1486
|
+
project.scenes.forEach(item => {
|
|
1487
|
+
const option = document.createElement('option');
|
|
1488
|
+
option.value = item.id;
|
|
1489
|
+
option.textContent = item.name;
|
|
1490
|
+
elements.buttonTargetScene.append(option);
|
|
1491
|
+
});
|
|
1492
|
+
if (action.type === 'gotoScene') {
|
|
1493
|
+
elements.buttonTargetScene.value = action.target || '';
|
|
1494
|
+
}
|
|
1495
|
+
|
|
1496
|
+
if (action.type === 'gotoFrame') {
|
|
1497
|
+
elements.buttonTargetFrame.max = String(scene.durationFrames);
|
|
1498
|
+
elements.buttonTargetFrame.value = action.target == null ? '' : String(action.target);
|
|
1499
|
+
}
|
|
1500
|
+
|
|
1501
|
+
elements.buttonTargetElement.replaceChildren();
|
|
1502
|
+
const emptyElOption = document.createElement('option');
|
|
1503
|
+
emptyElOption.value = '';
|
|
1504
|
+
emptyElOption.textContent = '-- Select element --';
|
|
1505
|
+
elements.buttonTargetElement.append(emptyElOption);
|
|
1506
|
+
(scene?.elements ?? []).filter(item => !editsInput || item.inputText).forEach(item => {
|
|
1507
|
+
const option = document.createElement('option');
|
|
1508
|
+
option.value = item.id;
|
|
1509
|
+
option.textContent = item.name;
|
|
1510
|
+
elements.buttonTargetElement.append(option);
|
|
1511
|
+
});
|
|
1512
|
+
if (action.type === 'toggleVisibility' || editsInput) {
|
|
1513
|
+
elements.buttonTargetElement.value = action.target || '';
|
|
1514
|
+
}
|
|
1515
|
+
|
|
1516
|
+
const check = validateButtonAction(action, scene, project);
|
|
1517
|
+
elements.buttonActionWarning.hidden = check.valid;
|
|
1518
|
+
elements.buttonActionWarning.textContent = check.message;
|
|
1519
|
+
if (locked) {
|
|
1520
|
+
elements.buttonActionType.disabled = true;
|
|
1521
|
+
elements.buttonTargetScene.disabled = true;
|
|
1522
|
+
elements.buttonTargetFrame.disabled = true;
|
|
1523
|
+
elements.buttonTargetElement.disabled = true;
|
|
1524
|
+
}
|
|
1525
|
+
}
|
|
1526
|
+
|
|
1527
|
+
const renderComponent = createComponentInspector(document.querySelector('#component-settings'), (name, value) => {
|
|
1528
|
+
const element = selectedElement();
|
|
1529
|
+
if (!element || isInteractivePreview() || isElementLocked(activeScene(), element)) return;
|
|
1530
|
+
if (element.type === 'control') {
|
|
1531
|
+
try {
|
|
1532
|
+
element.parameters = readControl({ ...element, parameters: { ...element.parameters, [name]: value } }, element.name).parameters;
|
|
1533
|
+
} catch (error) { showStatus(error.message, true); }
|
|
1534
|
+
} else if (element.component) element.component.parameters[name] = value;
|
|
1535
|
+
else return;
|
|
1536
|
+
renderAll();
|
|
1537
|
+
});
|
|
1538
|
+
const renderAppearance = createAppearanceInspector(elements.vectorStyleFields, (property, raw) => {
|
|
1539
|
+
const scene = activeScene();
|
|
1540
|
+
const element = selectedElement();
|
|
1541
|
+
if (!element || isInteractivePreview() || isElementLocked(scene, element) || !visibleAt(element, playhead)) return;
|
|
1542
|
+
try {
|
|
1543
|
+
updatePoseProperty(element, property, readAppearance(property, raw));
|
|
1544
|
+
} catch (error) {
|
|
1545
|
+
showStatus(error.message, true);
|
|
1546
|
+
}
|
|
1547
|
+
renderAll();
|
|
1548
|
+
});
|
|
1549
|
+
|
|
1550
|
+
let lastInspectedId;
|
|
1551
|
+
function renderInspector() {
|
|
1552
|
+
transitionInspector.render();
|
|
1553
|
+
const scene = activeScene();
|
|
1554
|
+
const element = selectedElement();
|
|
1555
|
+
const previewLocked = isInteractivePreview();
|
|
1556
|
+
if (scene) {
|
|
1557
|
+
elements.sceneLoop.checked = scene.loop;
|
|
1558
|
+
elements.sceneName.value = scene.name;
|
|
1559
|
+
elements.sceneDuration.value = String(scene.durationFrames);
|
|
1560
|
+
elements.sceneStartFrame.max = String(scene.durationFrames);
|
|
1561
|
+
elements.sceneStartFrame.value = String(scene.startFrame ?? 1);
|
|
1562
|
+
}
|
|
1563
|
+
elements.sceneLoop.disabled = previewLocked;
|
|
1564
|
+
elements.sceneName.disabled = previewLocked;
|
|
1565
|
+
elements.sceneDuration.disabled = previewLocked;
|
|
1566
|
+
elements.sceneStartFrame.disabled = previewLocked;
|
|
1567
|
+
elements.stageWidth.value = String(workingStage().width);
|
|
1568
|
+
elements.stageHeight.value = String(workingStage().height);
|
|
1569
|
+
elements.stageFps.value = String(project.stage.frameRate);
|
|
1570
|
+
elements.stageBackground.value = project.stage.background;
|
|
1571
|
+
elements.stageWidth.disabled = previewLocked;
|
|
1572
|
+
elements.stageHeight.disabled = previewLocked;
|
|
1573
|
+
elements.stageFps.disabled = previewLocked;
|
|
1574
|
+
elements.stageBackground.disabled = previewLocked;
|
|
1575
|
+
|
|
1576
|
+
const elementLocked = element ? isElementLocked(scene, element) : false;
|
|
1577
|
+
const trackLocked = previewLocked || elementLocked;
|
|
1578
|
+
const formLocked = trackLocked || (element && !visibleAt(element, playhead));
|
|
1579
|
+
if (lastInspectedId !== element?.id) {
|
|
1580
|
+
elements.buttonActionFields.closest('details').open = Boolean(element?.buttonAction);
|
|
1581
|
+
elements.maskSource.closest('details').open = Boolean(element?.maskId);
|
|
1582
|
+
lastInspectedId = element?.id;
|
|
1583
|
+
}
|
|
1584
|
+
elements.noSelection.hidden = selectedElementIds.length < 2;
|
|
1585
|
+
if (!elements.noSelection.hidden) {
|
|
1586
|
+
elements.noSelection.querySelector('strong').textContent = `${selectedElementIds.length} objects selected`;
|
|
1587
|
+
}
|
|
1588
|
+
elements.elementForm.hidden = !element;
|
|
1589
|
+
elements.deleteElement.disabled = previewLocked || !selectedElementIds.length || selectedMembers().some(item => isElementLocked(scene, item));
|
|
1590
|
+
elements.addKeyframe.disabled = !element || trackLocked;
|
|
1591
|
+
elements.frameEdit.disabled = previewLocked;
|
|
1592
|
+
for (const option of elements.frameEdit.options) {
|
|
1593
|
+
if (option.parentElement.label === 'Active layer') option.disabled = activeLayer()?.locked ?? true;
|
|
1594
|
+
if (option.parentElement.label === 'Selected track') option.disabled = !element || trackLocked;
|
|
1595
|
+
}
|
|
1596
|
+
|
|
1597
|
+
if (!element) return;
|
|
1598
|
+
const pose = poseAt(element, playhead);
|
|
1599
|
+
elements.elementType.textContent = element.type === 'control' ? controlDefinitions[element.control].label : element.type;
|
|
1600
|
+
elements.elementLayer.replaceChildren();
|
|
1601
|
+
[...orderedSceneLayers(scene)].reverse().forEach(layer => {
|
|
1602
|
+
const option = document.createElement('option');
|
|
1603
|
+
option.value = layer.id;
|
|
1604
|
+
option.textContent = layer.locked ? `${layer.name} (locked)` : layer.name;
|
|
1605
|
+
elements.elementLayer.append(option);
|
|
1606
|
+
});
|
|
1607
|
+
elements.elementLayer.value = element.layerId;
|
|
1608
|
+
const candidates = maskCandidates(scene, element);
|
|
1609
|
+
elements.maskSource.replaceChildren(new Option(candidates.length ? 'None' : 'Add a closed shape or symbol first', ''),
|
|
1610
|
+
...candidates.map(source => new Option(`${source.name} · ${findElementLayer(scene, source).name}`, source.id)));
|
|
1611
|
+
elements.maskSource.value = element.maskId ?? '';
|
|
1612
|
+
const masked = scene.elements.filter(item => item.maskId === element.id);
|
|
1613
|
+
elements.maskUsage.hidden = !masked.length;
|
|
1614
|
+
elements.maskUsage.textContent = masked.length ? `Mask for ${masked.map(item => item.name).join(', ')}. Only its outline is shown when selected.` : '';
|
|
1615
|
+
elements.elementLockedWarning.hidden = !elementLocked;
|
|
1616
|
+
elements.elementForm.elements.namedItem('element-name').value = element.name;
|
|
1617
|
+
for (const [property, value] of Object.entries(pose)) {
|
|
1618
|
+
const input = elements.elementForm.querySelector(`[data-property="${property}"]`);
|
|
1619
|
+
if (input) {
|
|
1620
|
+
input.value = typeof value === 'number' ? formatNumber(value) : String(value);
|
|
1621
|
+
}
|
|
1622
|
+
}
|
|
1623
|
+
for (const input of elements.elementForm.querySelectorAll('[data-shape-property]')) {
|
|
1624
|
+
const name = input.dataset.shapeProperty;
|
|
1625
|
+
const corner = name === 'cornerRadius';
|
|
1626
|
+
input.parentElement.hidden = element.type !== (corner ? 'roundedRectangle' : 'star');
|
|
1627
|
+
if (!input.parentElement.hidden) input.value = formatNumber(shapePropertyValue(name, pose));
|
|
1628
|
+
}
|
|
1629
|
+
const boldInput = elements.elementForm.querySelector('[data-property="bold"]');
|
|
1630
|
+
boldInput.checked = Boolean(pose.bold);
|
|
1631
|
+
for (const input of elements.elementForm.querySelectorAll('[data-element-style]')) {
|
|
1632
|
+
const name = input.dataset.elementStyle, value = element[name];
|
|
1633
|
+
if (input.type === 'checkbox') input.checked = Boolean(value);
|
|
1634
|
+
else if (name === 'strokeDash') input.value = value?.join(' ') ?? '';
|
|
1635
|
+
else input.value = value ?? (name === 'fillRule' ? '' : 'round');
|
|
1636
|
+
}
|
|
1637
|
+
const stroked = !['text', 'symbol', 'bitmap', 'control'].includes(element.type);
|
|
1638
|
+
document.querySelector('#stroke-style-row').hidden = !stroked;
|
|
1639
|
+
document.querySelector('#fill-rule-row').hidden = element.type !== 'path' || !element.closed;
|
|
1640
|
+
const isText = element.type === 'text';
|
|
1641
|
+
elements.instanceSettings.hidden = element.type !== 'symbol';
|
|
1642
|
+
if (element.type === 'symbol') {
|
|
1643
|
+
document.querySelector('#instance-scripts').disabled = formLocked;
|
|
1644
|
+
const definition = project.symbols.find(item => item.id === element.symbolId);
|
|
1645
|
+
elements.instanceMode.value = element.symbolMode ?? '';
|
|
1646
|
+
elements.instanceFirst.value = element.firstFrame ?? '';
|
|
1647
|
+
elements.instanceFirst.placeholder = String(definition.startFrame);
|
|
1648
|
+
elements.instanceFirst.max = String(definition.durationFrames);
|
|
1649
|
+
}
|
|
1650
|
+
const isControl = element.type === 'control';
|
|
1651
|
+
document.querySelector('#authored-control-settings').hidden = !isControl;
|
|
1652
|
+
if (isControl) {
|
|
1653
|
+
document.querySelector('#control-variable').value = element.variable ?? '';
|
|
1654
|
+
document.querySelector('#control-actions').disabled = formLocked || !controlDefinitions[element.control].events.length;
|
|
1655
|
+
}
|
|
1656
|
+
elements.buttonActionFields.closest('details').hidden = isControl;
|
|
1657
|
+
renderComponent(element,
|
|
1658
|
+
element.type === 'symbol' ? project.symbols.find(item => item.id === element.symbolId) : null, { locked: formLocked });
|
|
1659
|
+
const bitmap = element.type === 'bitmap';
|
|
1660
|
+
document.querySelector('#bitmap-settings').hidden = !bitmap;
|
|
1661
|
+
document.querySelector('#bitmap-crop').hidden = !bitmap || element.fit !== 'cover';
|
|
1662
|
+
if (bitmap) {
|
|
1663
|
+
document.querySelector('#bitmap-fit').value = element.fit;
|
|
1664
|
+
document.querySelector('#bitmap-crop-x').value = element.cropX ?? 50;
|
|
1665
|
+
document.querySelector('#bitmap-crop-y').value = element.cropY ?? 50;
|
|
1666
|
+
}
|
|
1667
|
+
elements.vectorStyleFields.hidden = isControl || bitmap || isText || element.type === 'symbol';
|
|
1668
|
+
if (!elements.vectorStyleFields.hidden) renderAppearance(element, pose);
|
|
1669
|
+
elements.textStyleFields.hidden = element.type === 'symbol' || !isText && !element.buttonAction && !pose.text;
|
|
1670
|
+
elements.inputText.closest('label').hidden = !isText;
|
|
1671
|
+
const settings = document.querySelector('#text-field-settings');
|
|
1672
|
+
settings.hidden = !isText;
|
|
1673
|
+
if (isText) {
|
|
1674
|
+
const field = element.field ?? {};
|
|
1675
|
+
for (const input of settings.querySelectorAll('[data-text-field]')) {
|
|
1676
|
+
const name = input.dataset.textField;
|
|
1677
|
+
if (input.type === 'checkbox') {
|
|
1678
|
+
input.checked = field[name] ?? (name === 'selectable' ? isEditableText(element) : ['multiline', 'wordWrap'].includes(name));
|
|
1679
|
+
} else input.value = field[name] ?? (name === 'maxLength' ? 0 : '');
|
|
1680
|
+
}
|
|
1681
|
+
elements.elementForm.querySelector('[data-property="text"]').value = fieldText(element, pose);
|
|
1682
|
+
}
|
|
1683
|
+
elements.textContentLabel.textContent = isText ? (element.field?.html ? 'HTML source' : 'Text') : 'Label';
|
|
1684
|
+
const keyframes = [...element.keyframes].sort((a, b) => a.frame - b.frame);
|
|
1685
|
+
const tweenKeyframe = [...keyframes].reverse().find(keyframe => keyframe.frame <= playhead);
|
|
1686
|
+
const nextKeyframe = keyframes.find(key => key.frame > playhead);
|
|
1687
|
+
const hasNextKeyframe = tweenKeyframe && nextKeyframe && !nextKeyframe.blank;
|
|
1688
|
+
elements.tweenEasing.value = tweenKeyframe?.tween || 'linear';
|
|
1689
|
+
elements.elementForm.querySelectorAll('input, textarea, select').forEach(input => {
|
|
1690
|
+
input.disabled = formLocked;
|
|
1691
|
+
});
|
|
1692
|
+
elements.maskSource.disabled = formLocked || !candidates.length;
|
|
1693
|
+
elements.tweenEasing.disabled = formLocked || !hasNextKeyframe;
|
|
1694
|
+
renderButtonInspector(element, scene, formLocked);
|
|
1695
|
+
}
|
|
1696
|
+
|
|
1697
|
+
const timeline = createTimeline(elements, {
|
|
1698
|
+
renderLayers: renderLayerList,
|
|
1699
|
+
seek: scrubFrame,
|
|
1700
|
+
clipName: clip => project.assets.find(asset => asset.id === clip.assetId).name,
|
|
1701
|
+
editClip: id => mediaLibrary.selectClip(id),
|
|
1702
|
+
editEvent: (frame, type) => openEventEditor(activeScene(), frame, type),
|
|
1703
|
+
select(id, frame) {
|
|
1704
|
+
const element = activeScene().elements.find(item => item.id === id);
|
|
1705
|
+
if (!element || isInteractivePreview()) return;
|
|
1706
|
+
if (editingTextElementId) closeTextEditor(true);
|
|
1707
|
+
preferredSymbol = element.symbolId;
|
|
1708
|
+
selectedElementIds = [id];
|
|
1709
|
+
selectedLayerId = element.layerId;
|
|
1710
|
+
if (frame !== undefined) playhead = frame;
|
|
1711
|
+
renderAll();
|
|
1712
|
+
},
|
|
1713
|
+
});
|
|
1714
|
+
|
|
1715
|
+
function scrubFrame(frame) {
|
|
1716
|
+
if (isInteractivePreview() || dragState || pendingPath) return;
|
|
1717
|
+
if (editingTextElementId) closeTextEditor(true);
|
|
1718
|
+
const scene = activeScene();
|
|
1719
|
+
const next = Math.max(1, Math.min(scene.durationFrames, Math.round(frame)));
|
|
1720
|
+
if (next === playhead) return;
|
|
1721
|
+
playhead = next;
|
|
1722
|
+
timeline.readout(playhead);
|
|
1723
|
+
renderInspector();
|
|
1724
|
+
renderControls();
|
|
1725
|
+
renderCanvas();
|
|
1726
|
+
history.updateView({ ...authoringView(), returnViews: [...returnViews] });
|
|
1727
|
+
}
|
|
1728
|
+
|
|
1729
|
+
function renderControls() {
|
|
1730
|
+
const locked = isInteractivePreview();
|
|
1731
|
+
mediaLibrary.render();
|
|
1732
|
+
const startFrame = activeScene()?.startFrame ?? 1;
|
|
1733
|
+
elements.playButton.disabled = sceneTransition.active;
|
|
1734
|
+
elements.playButton.classList.toggle('is-playing', playing);
|
|
1735
|
+
elements.playButton.textContent = playing ? 'Pause' : 'Play';
|
|
1736
|
+
elements.playButton.setAttribute('aria-label', playing ? 'Pause preview' : 'Play preview');
|
|
1737
|
+
elements.previewButton.classList.toggle('is-active', previewMode);
|
|
1738
|
+
elements.previewButton.setAttribute('aria-pressed', String(previewMode));
|
|
1739
|
+
elements.previewButton.textContent = previewMode ? 'Exit preview' : 'Preview';
|
|
1740
|
+
elements.stopButton.disabled = !playing && !previewMode && playhead === startFrame;
|
|
1741
|
+
elements.previewBadge.hidden = !locked;
|
|
1742
|
+
elements.previewBadge.textContent = playing ? 'PREVIEWING' : 'PREVIEW MODE';
|
|
1743
|
+
elements.deleteScene.disabled = project.scenes.length <= 1 || locked || !!returnViews.length;
|
|
1744
|
+
const canFinishPath = !locked && !!pendingPath && ['pen', 'polygon'].includes(activeTool) &&
|
|
1745
|
+
pendingPath.points.length >= (pendingPath.kind === 'polygon' ? 3 : 2);
|
|
1746
|
+
elements.finishPath.hidden = !canFinishPath;
|
|
1747
|
+
elements.finishPath.textContent = pendingPath?.kind === 'polygon' ? 'Finish shape' : 'Open path';
|
|
1748
|
+
elements.closePath.hidden = !(!locked && ['pen', 'polygon'].includes(activeTool) && pendingPath?.points.length >= 3);
|
|
1749
|
+
elements.closePath.textContent = pendingPath?.kind === 'polygon' ? 'Close shape' : 'Close path';
|
|
1750
|
+
const currentEl = selectedElement();
|
|
1751
|
+
const currentLocked = currentEl ? isElementLocked(activeScene(), currentEl) : false;
|
|
1752
|
+
elements.editText.disabled = locked || currentLocked || currentEl?.type !== 'text' || !visibleAt(currentEl, playhead) || !!editingTextElementId;
|
|
1753
|
+
paintOptions.hidden = locked || !['pencil', 'brush', 'eraser', 'bucket', 'ink'].includes(activeTool);
|
|
1754
|
+
paintColor.parentElement.hidden = activeTool === 'eraser';
|
|
1755
|
+
paintSize.parentElement.hidden = activeTool === 'bucket';
|
|
1756
|
+
elements.canvas.dataset.tool = activeTool;
|
|
1757
|
+
for (const button of elements.toolButtons) {
|
|
1758
|
+
const active = button.dataset.tool === activeTool;
|
|
1759
|
+
button.classList.toggle('is-active', active);
|
|
1760
|
+
button.setAttribute('aria-pressed', String(active));
|
|
1761
|
+
button.disabled = locked;
|
|
1762
|
+
}
|
|
1763
|
+
}
|
|
1764
|
+
|
|
1765
|
+
function showToolHint(tool) {
|
|
1766
|
+
if (paintHints[tool]) return showStatus(paintHints[tool]);
|
|
1767
|
+
if (Object.hasOwn(controlDefinitions, tool)) {
|
|
1768
|
+
showStatus(`Click to place a ${controlDefinitions[tool].label.toLowerCase()}, or drag to set its size.`);
|
|
1769
|
+
} else if (tool === 'pen') {
|
|
1770
|
+
showStatus(selectedElement()?.type === 'path'
|
|
1771
|
+
? 'Drag anchors or handles to edit this path; click empty stage to draw another.'
|
|
1772
|
+
: 'Click to add anchors, drag anchors for curves, then close or finish the path.');
|
|
1773
|
+
} else if (tool === 'polygon') {
|
|
1774
|
+
showStatus('Click to place polygon points; close it or choose Finish shape.');
|
|
1775
|
+
} else if (tool === 'ellipse') {
|
|
1776
|
+
showStatus('Drag to draw an ellipse; hold Shift for a circle. Click for a default size.');
|
|
1777
|
+
} else if (tool === 'text') {
|
|
1778
|
+
showStatus('Drag to set the text box size, or click for a default box. Text editing opens immediately.');
|
|
1779
|
+
} else if (['rectangle', 'roundedRectangle', 'triangle', 'diamond', 'pentagon', 'hexagon', 'star', 'curve', 'line'].includes(tool)) {
|
|
1780
|
+
const label = tool === 'roundedRectangle' ? 'rounded rectangle' : tool;
|
|
1781
|
+
showStatus(`Drag on the stage to draw a ${label}; click for a default size.`);
|
|
1782
|
+
}
|
|
1783
|
+
}
|
|
1784
|
+
|
|
1785
|
+
function setIfChanged(target, property, value) {
|
|
1786
|
+
if (target[property] !== value) target[property] = value;
|
|
1787
|
+
}
|
|
1788
|
+
|
|
1789
|
+
function renderCanvas() {
|
|
1790
|
+
const scene = activeScene();
|
|
1791
|
+
if (!scene) return;
|
|
1792
|
+
const stage = workingStage();
|
|
1793
|
+
const inPreview = isInteractivePreview();
|
|
1794
|
+
setIfChanged(elements.stageMat.style, 'aspectRatio', `${stage.width} / ${stage.height}`);
|
|
1795
|
+
canvasRenderer.render({
|
|
1796
|
+
stage, scene, assets: project.assets, symbols: project.symbols, clocks: symbolClocks, playhead, selection: selectedElement(),
|
|
1797
|
+
groupBounds: !inPreview && selectedElementIds.length > 1 ? selectionBounds(scene, selectedMembers(scene), playhead) : null,
|
|
1798
|
+
activeTool, editingTextElementId,
|
|
1799
|
+
inPreview, previewHiddenIds, pressedButtonId, hoveredButtonId, dragState, pendingPath,
|
|
1800
|
+
});
|
|
1801
|
+
previewAudio.sync(project.assets, canvasRenderer.previewTimelines(), project.stage.frameRate, playing && !sceneTransition.active && !document.hidden);
|
|
1802
|
+
// Written only when changed: same-value writes still invalidate layout on every played frame.
|
|
1803
|
+
setIfChanged(elements.canvas.style, 'cursor', inPreview && hoveredButtonId ? 'pointer' : '');
|
|
1804
|
+
setIfChanged(elements.emptyStage, 'hidden', scene.elements.length > 0 || dragState?.mode === 'draw' || !!pendingPath);
|
|
1805
|
+
setIfChanged(elements.stageSceneName, 'textContent', scene.name);
|
|
1806
|
+
setIfChanged(elements.stageSizeLabel, 'textContent', `${stage.width} x ${stage.height}`);
|
|
1807
|
+
setIfChanged(elements.stageFpsLabel, 'textContent', `${stage.frameRate} FPS`);
|
|
1808
|
+
}
|
|
1809
|
+
|
|
1810
|
+
function moveHistory(direction) {
|
|
1811
|
+
if (isInteractivePreview() || editingTextElementId || dragState || pendingPath) return;
|
|
1812
|
+
const state = history.move(direction);
|
|
1813
|
+
if (!state) return;
|
|
1814
|
+
Object.assign(project, state.project);
|
|
1815
|
+
restoreView(state);
|
|
1816
|
+
returnViews = [...state.returnViews];
|
|
1817
|
+
pendingLayerDeleteId = null;
|
|
1818
|
+
editingLayerId = null;
|
|
1819
|
+
renderAll();
|
|
1820
|
+
}
|
|
1821
|
+
|
|
1822
|
+
function renderAll() {
|
|
1823
|
+
syncEmbeddedFonts(project.scripts, renderCanvas);
|
|
1824
|
+
renderSceneList();
|
|
1825
|
+
document.querySelector('#timeline-kind').textContent = returnViews.length ? 'Symbol definition' : 'Active scene';
|
|
1826
|
+
document.querySelector('#artboard-title').textContent = returnViews.length ? 'Symbol artboard' : 'Stage';
|
|
1827
|
+
renderSymbolLibrary(project.symbols, activeScene(), !!returnViews.length,
|
|
1828
|
+
isInteractivePreview() || !!dragState, activeLayer()?.locked, preferredSymbol);
|
|
1829
|
+
preferredSymbol = null;
|
|
1830
|
+
renderElementList();
|
|
1831
|
+
renderInspector();
|
|
1832
|
+
timeline.render(activeScene(), selectedElementIds, playhead, isInteractivePreview());
|
|
1833
|
+
renderControls();
|
|
1834
|
+
renderCanvas();
|
|
1835
|
+
updateTextEditorPosition();
|
|
1836
|
+
updateHistoryControls();
|
|
1837
|
+
projectSession.changed(history.version);
|
|
1838
|
+
}
|
|
1839
|
+
|
|
1840
|
+
function updateHistoryControls() {
|
|
1841
|
+
const canRecord = !isInteractivePreview() && !editingTextElementId && !dragState && !pendingPath;
|
|
1842
|
+
if (canRecord) history.record(project, { ...authoringView(), returnViews: [...returnViews] });
|
|
1843
|
+
elements.undo.disabled = !canRecord || !history.canMove(-1);
|
|
1844
|
+
elements.redo.disabled = !canRecord || !history.canMove(1);
|
|
1845
|
+
}
|
|
1846
|
+
|
|
1847
|
+
function setPoseFromInput(input) {
|
|
1848
|
+
const property = input.dataset.property;
|
|
1849
|
+
const scene = activeScene();
|
|
1850
|
+
const element = selectedElement();
|
|
1851
|
+
if (!scene || !element || !property) return;
|
|
1852
|
+
if (isElementLocked(scene, element)) {
|
|
1853
|
+
showStatus('Unlock the layer before editing this element', true);
|
|
1854
|
+
renderAll();
|
|
1855
|
+
return;
|
|
1856
|
+
}
|
|
1857
|
+
if (property === 'name') {
|
|
1858
|
+
const name = input.value.trim();
|
|
1859
|
+
if (!name) {
|
|
1860
|
+
showStatus('Element name cannot be empty', true);
|
|
1861
|
+
renderAll();
|
|
1862
|
+
return;
|
|
1863
|
+
}
|
|
1864
|
+
if (name !== element.name) {
|
|
1865
|
+
const previous = { name: element.name };
|
|
1866
|
+
element.name = name;
|
|
1867
|
+
reportObjectEdit(`Renamed to ${name}`, [previous]);
|
|
1868
|
+
}
|
|
1869
|
+
} else if (property === 'bold') {
|
|
1870
|
+
updatePoseProperty(element, 'bold', input.checked);
|
|
1871
|
+
} else if (['fill', 'stroke', 'text', 'fontFamily', 'textColor', 'textAlign'].includes(property)) {
|
|
1872
|
+
updatePoseProperty(element, property, input.value);
|
|
1873
|
+
} else {
|
|
1874
|
+
try {
|
|
1875
|
+
setNumericPoseAtFrame(element, playhead, property, input.valueAsNumber, workingStage());
|
|
1876
|
+
} catch (error) {
|
|
1877
|
+
showStatus(error.message, true);
|
|
1878
|
+
}
|
|
1879
|
+
}
|
|
1880
|
+
renderAll();
|
|
1881
|
+
}
|
|
1882
|
+
|
|
1883
|
+
function updateStageProperty(input) {
|
|
1884
|
+
const property = input.dataset.stageProperty;
|
|
1885
|
+
if (!property) return;
|
|
1886
|
+
if (property === 'background') {
|
|
1887
|
+
project.stage.background = input.value;
|
|
1888
|
+
renderAll();
|
|
1889
|
+
return;
|
|
1890
|
+
}
|
|
1891
|
+
try {
|
|
1892
|
+
setStageNumber(project, activeScene(), property, input.valueAsNumber);
|
|
1893
|
+
} catch (error) {
|
|
1894
|
+
showStatus(error.message, true);
|
|
1895
|
+
}
|
|
1896
|
+
renderAll();
|
|
1897
|
+
}
|
|
1898
|
+
|
|
1899
|
+
function updateSceneProperty(input) {
|
|
1900
|
+
const scene = activeScene();
|
|
1901
|
+
if (!scene) return;
|
|
1902
|
+
if (input.id === 'scene-name') {
|
|
1903
|
+
const name = input.value.trim();
|
|
1904
|
+
if (!name) {
|
|
1905
|
+
showStatus('Timeline name cannot be empty', true);
|
|
1906
|
+
renderAll();
|
|
1907
|
+
return;
|
|
1908
|
+
}
|
|
1909
|
+
scene.name = name;
|
|
1910
|
+
} else if (input.id === 'scene-loop') {
|
|
1911
|
+
scene.loop = input.checked;
|
|
1912
|
+
} else if (input.id === 'scene-duration') {
|
|
1913
|
+
const duration = input.valueAsNumber;
|
|
1914
|
+
try {
|
|
1915
|
+
resizeScene(scene, duration, project);
|
|
1916
|
+
} catch (error) {
|
|
1917
|
+
showStatus(error.message, true);
|
|
1918
|
+
renderAll();
|
|
1919
|
+
return;
|
|
1920
|
+
}
|
|
1921
|
+
playhead = Math.min(playhead, duration);
|
|
1922
|
+
} else if (input.id === 'scene-start-frame') {
|
|
1923
|
+
try {
|
|
1924
|
+
setStartFrame(scene, input.valueAsNumber);
|
|
1925
|
+
} catch (error) {
|
|
1926
|
+
showStatus(error.message, true);
|
|
1927
|
+
}
|
|
1928
|
+
}
|
|
1929
|
+
renderAll();
|
|
1930
|
+
}
|
|
1931
|
+
|
|
1932
|
+
function editFrames(operation) {
|
|
1933
|
+
const scene = activeScene();
|
|
1934
|
+
if (!scene || isInteractivePreview()) return;
|
|
1935
|
+
if (editingTextElementId) closeTextEditor(true);
|
|
1936
|
+
try {
|
|
1937
|
+
if (operation === 'events') { openEventEditor(scene, playhead); return; }
|
|
1938
|
+
if (operation === 'insertFrame' || operation === 'removeFrame') {
|
|
1939
|
+
playhead = editSceneFrame(scene, playhead, operation === 'insertFrame', project);
|
|
1940
|
+
} else if (operation === 'layerKey' || operation === 'layerBlank') {
|
|
1941
|
+
keyLayer(scene, activeLayer(), playhead, operation === 'layerBlank');
|
|
1942
|
+
} else {
|
|
1943
|
+
playhead = editTrack(scene, selectedElement(), playhead, operation);
|
|
1944
|
+
}
|
|
1945
|
+
renderAll();
|
|
1946
|
+
} catch (error) {
|
|
1947
|
+
showStatus(error.message, true);
|
|
1948
|
+
}
|
|
1949
|
+
}
|
|
1950
|
+
|
|
1951
|
+
function updateTweenEasing() {
|
|
1952
|
+
const scene = activeScene();
|
|
1953
|
+
const element = selectedElement();
|
|
1954
|
+
if (!scene || !element || isElementLocked(scene, element)) return;
|
|
1955
|
+
const keyframes = [...element.keyframes].sort((a, b) => a.frame - b.frame);
|
|
1956
|
+
const keyframe = [...keyframes].reverse().find(item => item.frame <= playhead);
|
|
1957
|
+
if (!keyframe || !keyframes.some(item => item.frame > keyframe.frame)) return;
|
|
1958
|
+
keyframe.tween = elements.tweenEasing.value;
|
|
1959
|
+
renderAll();
|
|
1960
|
+
}
|
|
1961
|
+
|
|
1962
|
+
function pointerToStage(event) {
|
|
1963
|
+
const rect = elements.canvas.getBoundingClientRect();
|
|
1964
|
+
return {
|
|
1965
|
+
x: (event.clientX - rect.left) * workingStage().width / rect.width,
|
|
1966
|
+
y: (event.clientY - rect.top) * workingStage().height / rect.height,
|
|
1967
|
+
};
|
|
1968
|
+
}
|
|
1969
|
+
|
|
1970
|
+
function findScaleHandle(pose, point) {
|
|
1971
|
+
const unit = stageUnitsPerCssPixel(elements.canvas);
|
|
1972
|
+
let nearest;
|
|
1973
|
+
let distance = 7 * unit;
|
|
1974
|
+
for (const handle of transformHandles(pose, unit)) {
|
|
1975
|
+
const world = pointToWorld(handle, pose);
|
|
1976
|
+
const delta = Math.hypot(world.x - point.x, world.y - point.y);
|
|
1977
|
+
if (delta < distance) {
|
|
1978
|
+
nearest = handle;
|
|
1979
|
+
distance = delta;
|
|
1980
|
+
}
|
|
1981
|
+
}
|
|
1982
|
+
return nearest;
|
|
1983
|
+
}
|
|
1984
|
+
|
|
1985
|
+
function isRotationHandleHit(pose, point) {
|
|
1986
|
+
const unit = stageUnitsPerCssPixel(elements.canvas);
|
|
1987
|
+
const handle = rotationHandleWorld(pose, unit);
|
|
1988
|
+
return Math.hypot(handle.x - point.x, handle.y - point.y) < 8 * unit;
|
|
1989
|
+
}
|
|
1990
|
+
|
|
1991
|
+
function updateSelectionCursor(point) {
|
|
1992
|
+
const scene = activeScene();
|
|
1993
|
+
const element = selectedElement();
|
|
1994
|
+
let pose;
|
|
1995
|
+
if (selectedElementIds.length > 1) pose = selectionBounds(scene, selectedMembers(scene), playhead);
|
|
1996
|
+
else if (element && visibleAt(element, playhead) && findElementLayer(scene, element)?.visible !== false) {
|
|
1997
|
+
pose = poseAt(element, playhead);
|
|
1998
|
+
}
|
|
1999
|
+
let cursor = '';
|
|
2000
|
+
if (pose && !activeLayer()?.locked) {
|
|
2001
|
+
const handle = findScaleHandle(pose, point);
|
|
2002
|
+
if (isRotationHandleHit(pose, point)) cursor = 'crosshair';
|
|
2003
|
+
else if (handle) {
|
|
2004
|
+
const world = pointToWorld(handle, pose);
|
|
2005
|
+
const angle = Math.atan2(world.y - pose.y, world.x - pose.x);
|
|
2006
|
+
cursor = ['ew-resize', 'nwse-resize', 'ns-resize', 'nesw-resize'][(Math.round(angle / (Math.PI / 4)) + 4) % 4];
|
|
2007
|
+
}
|
|
2008
|
+
}
|
|
2009
|
+
if (!cursor && activeTool === 'select') {
|
|
2010
|
+
const hit = elementAt(scene, point);
|
|
2011
|
+
if (hit && !isElementLocked(scene, hit)) cursor = 'move';
|
|
2012
|
+
}
|
|
2013
|
+
elements.canvas.style.cursor = cursor;
|
|
2014
|
+
}
|
|
2015
|
+
|
|
2016
|
+
function findPathHandle(element, point) {
|
|
2017
|
+
const pose = poseAt(element, playhead);
|
|
2018
|
+
const threshold = 12 * stageUnitsPerCssPixel(elements.canvas);
|
|
2019
|
+
for (let index = 0; index < pose.points.length; index += 1) {
|
|
2020
|
+
const anchor = pose.points[index];
|
|
2021
|
+
const worldAnchor = pointToWorld(anchor, pose);
|
|
2022
|
+
if (Math.hypot(worldAnchor.x - point.x, worldAnchor.y - point.y) < threshold) {
|
|
2023
|
+
return { mode: 'path-anchor', index };
|
|
2024
|
+
}
|
|
2025
|
+
for (const side of ['in', 'out']) {
|
|
2026
|
+
const handle = anchor[`handle${side === 'in' ? 'In' : 'Out'}`];
|
|
2027
|
+
if (Math.hypot(handle.x, handle.y) < 0.5) continue;
|
|
2028
|
+
const worldHandle = pointToWorld({ x: anchor.x + handle.x, y: anchor.y + handle.y }, pose);
|
|
2029
|
+
if (Math.hypot(worldHandle.x - point.x, worldHandle.y - point.y) < threshold) {
|
|
2030
|
+
return { mode: `path-handle-${side}`, index };
|
|
2031
|
+
}
|
|
2032
|
+
}
|
|
2033
|
+
}
|
|
2034
|
+
return null;
|
|
2035
|
+
}
|
|
2036
|
+
|
|
2037
|
+
function commitDrawnObject(type, start, end, constrain) {
|
|
2038
|
+
const dx = end.x - start.x;
|
|
2039
|
+
const dy = end.y - start.y;
|
|
2040
|
+
const dragged = Math.hypot(dx, dy) > 4 * stageUnitsPerCssPixel(elements.canvas);
|
|
2041
|
+
if (Object.hasOwn(controlDefinitions, type)) {
|
|
2042
|
+
const { width, height } = controlDefinitions[type];
|
|
2043
|
+
createShape('control', { control: type, x: dragged ? (start.x + end.x) / 2 : start.x,
|
|
2044
|
+
y: dragged ? (start.y + end.y) / 2 : start.y, width: dragged ? Math.max(8, Math.abs(dx)) : width,
|
|
2045
|
+
height: dragged ? Math.max(8, Math.abs(dy)) : height });
|
|
2046
|
+
return;
|
|
2047
|
+
}
|
|
2048
|
+
if (type === 'text') {
|
|
2049
|
+
const width = dragged ? Math.max(80, Math.abs(dx)) : 280;
|
|
2050
|
+
const height = dragged ? Math.max(36, Math.abs(dy)) : 72;
|
|
2051
|
+
createText({ x: dragged ? (start.x + end.x) / 2 : start.x, y: dragged ? (start.y + end.y) / 2 : start.y, width, height });
|
|
2052
|
+
return;
|
|
2053
|
+
}
|
|
2054
|
+
|
|
2055
|
+
if (type === 'line') {
|
|
2056
|
+
const length = dragged ? Math.hypot(dx, dy) : 120;
|
|
2057
|
+
const rotation = dragged ? Math.atan2(dy, dx) * 180 / Math.PI : 0;
|
|
2058
|
+
createShape(type, {
|
|
2059
|
+
x: dragged ? (start.x + end.x) / 2 : start.x,
|
|
2060
|
+
y: dragged ? (start.y + end.y) / 2 : start.y,
|
|
2061
|
+
width: Math.max(1, length),
|
|
2062
|
+
height: 12,
|
|
2063
|
+
rotation,
|
|
2064
|
+
});
|
|
2065
|
+
return;
|
|
2066
|
+
}
|
|
2067
|
+
|
|
2068
|
+
let width = dragged ? Math.max(8, Math.abs(dx)) : 120;
|
|
2069
|
+
let height = dragged ? Math.max(8, Math.abs(dy)) : 84;
|
|
2070
|
+
if (constrain && type === 'ellipse') {
|
|
2071
|
+
width = Math.max(width, height);
|
|
2072
|
+
height = width;
|
|
2073
|
+
}
|
|
2074
|
+
createShape(type, {
|
|
2075
|
+
x: dragged ? (start.x + end.x) / 2 : start.x,
|
|
2076
|
+
y: dragged ? (start.y + end.y) / 2 : start.y,
|
|
2077
|
+
width,
|
|
2078
|
+
height,
|
|
2079
|
+
});
|
|
2080
|
+
}
|
|
2081
|
+
|
|
2082
|
+
function runButtonAction(entry) {
|
|
2083
|
+
if (!isInteractivePreview() || sceneTransition.active) return;
|
|
2084
|
+
const { element, timeline: scene, scope, frame } = entry;
|
|
2085
|
+
const action = element.buttonAction;
|
|
2086
|
+
if (!scene || !action) return;
|
|
2087
|
+
const check = validateButtonAction(action, scene, project);
|
|
2088
|
+
if (!check.valid) {
|
|
2089
|
+
showStatus(check.message, true);
|
|
2090
|
+
return;
|
|
2091
|
+
}
|
|
2092
|
+
|
|
2093
|
+
if (scope.length && ['gotoFrame', 'play', 'stop'].includes(action.type)) {
|
|
2094
|
+
const play = action.type === 'play' || (action.type === 'gotoFrame' && (playing || action.play));
|
|
2095
|
+
if (action.type === 'gotoFrame') {
|
|
2096
|
+
eventDispatcher.reenter(scope);
|
|
2097
|
+
previewAudio.reset(scope);
|
|
2098
|
+
}
|
|
2099
|
+
updateClock(entry, action.type === 'gotoFrame' ? action.target : frame, play);
|
|
2100
|
+
if (play && !playing) playFrom(playhead);
|
|
2101
|
+
else {
|
|
2102
|
+
renderCanvas();
|
|
2103
|
+
dispatchFrameEvents();
|
|
2104
|
+
}
|
|
2105
|
+
return;
|
|
2106
|
+
}
|
|
2107
|
+
if (action.type === 'gotoScene') {
|
|
2108
|
+
const targetScene = project.scenes.find(item => item.id === action.target);
|
|
2109
|
+
previewNavigation(targetScene);
|
|
2110
|
+
showStatus(`Switched to ${targetScene.name}`);
|
|
2111
|
+
if (playing || action.play) playFrom(playhead);
|
|
2112
|
+
else setFrame(playhead);
|
|
2113
|
+
} else if (action.type === 'gotoFrame') {
|
|
2114
|
+
previewAudio.reset();
|
|
2115
|
+
eventDispatcher.reenter([]);
|
|
2116
|
+
showStatus(`Jumped to frame ${action.target}`);
|
|
2117
|
+
if (playing || action.play) playFrom(action.target);
|
|
2118
|
+
else setFrame(action.target);
|
|
2119
|
+
} else if (action.type === 'play') {
|
|
2120
|
+
if (!playing) startPlayback();
|
|
2121
|
+
} else if (action.type === 'stop') {
|
|
2122
|
+
if (playing) stopPlayback(false);
|
|
2123
|
+
} else if (action.type === 'editInput') {
|
|
2124
|
+
const field = scene.elements.find(item => item.id === action.target);
|
|
2125
|
+
try {
|
|
2126
|
+
canvasRenderer.editInput({ ...action, target: scopedId(scope, field.id) }, poseAt(field, frame).text);
|
|
2127
|
+
renderCanvas();
|
|
2128
|
+
} catch (error) {
|
|
2129
|
+
showStatus(error.message, true);
|
|
2130
|
+
}
|
|
2131
|
+
} else if (action.type === 'toggleVisibility') {
|
|
2132
|
+
const id = scopedId(scope, action.target);
|
|
2133
|
+
if (previewHiddenIds.has(id)) previewHiddenIds.delete(id);
|
|
2134
|
+
else previewHiddenIds.add(id);
|
|
2135
|
+
renderCanvas();
|
|
2136
|
+
dispatchFrameEvents();
|
|
2137
|
+
}
|
|
2138
|
+
}
|
|
2139
|
+
|
|
2140
|
+
function elementAt(scene, point) {
|
|
2141
|
+
const current = selectedElement();
|
|
2142
|
+
if (current && canvasRenderer.hitSelectedMask(current.id, point)) return current;
|
|
2143
|
+
return orderedSceneElements(scene, { includeHidden: false, frame: playhead }).reverse()
|
|
2144
|
+
.find(item => canvasRenderer.hitTestElement(item.id, point));
|
|
2145
|
+
}
|
|
2146
|
+
|
|
2147
|
+
function beginSelectionTransform(scene, mode, point, pointerId) {
|
|
2148
|
+
const members = selectedMembers(scene);
|
|
2149
|
+
if (members.some(item => isElementLocked(scene, item))) return;
|
|
2150
|
+
const center = selectionBounds(scene, members, playhead);
|
|
2151
|
+
if (!center) return;
|
|
2152
|
+
dragState = { mode: 'selection', transform: mode, start: point, center, sources: groupTransformSources(members) };
|
|
2153
|
+
elements.canvas.setPointerCapture(pointerId);
|
|
2154
|
+
}
|
|
2155
|
+
|
|
2156
|
+
elements.stageMat.addEventListener('pointerdown', event => {
|
|
2157
|
+
if (isInteractivePreview() || event.target !== elements.canvas) return;
|
|
2158
|
+
const point = pointerToStage(event);
|
|
2159
|
+
if (event.button !== 0 || !event.isPrimary) return;
|
|
2160
|
+
elements.canvas.focus({ preventScroll: true });
|
|
2161
|
+
if (editingTextElementId) closeTextEditor(true);
|
|
2162
|
+
const scene = activeScene();
|
|
2163
|
+
if (event.shiftKey && activeTool === 'select') {
|
|
2164
|
+
const hit = elementAt(scene, point);
|
|
2165
|
+
if (hit) selectObjects(groupMembers(scene, hit), true);
|
|
2166
|
+
renderAll();
|
|
2167
|
+
return;
|
|
2168
|
+
}
|
|
2169
|
+
if (selectedElementIds.length > 1 && ['select', 'scale', 'rotate'].includes(activeTool)) {
|
|
2170
|
+
const bounds = selectionBounds(scene, selectedMembers(scene), playhead);
|
|
2171
|
+
if (bounds) {
|
|
2172
|
+
const rotate = isRotationHandleHit(bounds, point);
|
|
2173
|
+
if (rotate || findScaleHandle(bounds, point)) {
|
|
2174
|
+
beginSelectionTransform(scene, rotate ? 'rotate' : 'scale', point, event.pointerId);
|
|
2175
|
+
return;
|
|
2176
|
+
}
|
|
2177
|
+
}
|
|
2178
|
+
}
|
|
2179
|
+
const selected = selectedElement();
|
|
2180
|
+
const current = selected && visibleAt(selected, playhead) && findElementLayer(scene, selected)?.visible !== false ? selected : null;
|
|
2181
|
+
if (activeTool === 'pen' && current?.type === 'path') {
|
|
2182
|
+
const pathHandle = findPathHandle(current, point);
|
|
2183
|
+
if (pathHandle) {
|
|
2184
|
+
if (isElementLocked(scene, current)) {
|
|
2185
|
+
showStatus('Unlock the layer to edit this path', true);
|
|
2186
|
+
return;
|
|
2187
|
+
}
|
|
2188
|
+
dragState = { ...pathHandle, elementId: current.id, start: point };
|
|
2189
|
+
elements.canvas.setPointerCapture(event.pointerId);
|
|
2190
|
+
return;
|
|
2191
|
+
}
|
|
2192
|
+
}
|
|
2193
|
+
if (!['select', 'scale', 'rotate', 'eyedropper', 'bucket', 'ink', 'gradientTransform'].includes(activeTool)) {
|
|
2194
|
+
const layer = activeLayer();
|
|
2195
|
+
if (layer.locked || !layer.visible) {
|
|
2196
|
+
showStatus(`${layer.locked ? 'Unlock' : 'Show'} ${layer.name} before drawing on it`, true);
|
|
2197
|
+
return;
|
|
2198
|
+
}
|
|
2199
|
+
}
|
|
2200
|
+
if (Object.hasOwn(paintHints, activeTool)) {
|
|
2201
|
+
const size = paintSize.valueAsNumber;
|
|
2202
|
+
if (['pencil', 'brush', 'eraser', 'ink'].includes(activeTool) && (!paintSize.validity.valid || !Number.isFinite(size))) {
|
|
2203
|
+
paintSize.reportValidity();
|
|
2204
|
+
return;
|
|
2205
|
+
}
|
|
2206
|
+
if (['pencil', 'brush', 'eraser'].includes(activeTool)) {
|
|
2207
|
+
dragState = { mode: 'paint', type: activeTool, pointerId: event.pointerId, points: [point], size, color: paintColor.value };
|
|
2208
|
+
} else {
|
|
2209
|
+
const target = elementAt(scene, point);
|
|
2210
|
+
if (activeTool === 'eyedropper') {
|
|
2211
|
+
const pose = target && poseAt(target, playhead);
|
|
2212
|
+
if (isVector(target) && !target.bitmapFill) {
|
|
2213
|
+
const stroke = event.shiftKey || !hasVectorFill(target);
|
|
2214
|
+
paintColor.value = stroke ? pose.stroke : pose.fill;
|
|
2215
|
+
sampledGradient = stroke ? null : structuredClone(pose.gradient ?? null);
|
|
2216
|
+
if (stroke) paintSize.value = Math.max(1, pose.strokeWidth);
|
|
2217
|
+
activeTool = stroke ? 'ink' : 'bucket';
|
|
2218
|
+
} else {
|
|
2219
|
+
const rgb = elements.canvas.getContext('2d').getImageData(Math.floor(point.x), Math.floor(point.y), 1, 1).data;
|
|
2220
|
+
paintColor.value = '#' + Array.from(rgb.slice(0, 3), channel => channel.toString(16).padStart(2, '0')).join('');
|
|
2221
|
+
sampledGradient = null;
|
|
2222
|
+
activeTool = 'bucket';
|
|
2223
|
+
}
|
|
2224
|
+
renderAll();
|
|
2225
|
+
return;
|
|
2226
|
+
}
|
|
2227
|
+
if (!target && activeTool === 'bucket') {
|
|
2228
|
+
const layer = activeLayer();
|
|
2229
|
+
if (!layer || layer.locked || !layer.visible) return showStatus('Choose an unlocked, visible layer.');
|
|
2230
|
+
const [main, ...subpaths] = fillEnclosedArea(scene, layer, playhead, point);
|
|
2231
|
+
if (!main) return showStatus('Click inside an area enclosed by strokes on the active layer.');
|
|
2232
|
+
pendingPath = { kind: 'bucket', points: main, subpaths, color: paintColor.value, gradient: sampledGradient };
|
|
2233
|
+
finishPendingPath(true);
|
|
2234
|
+
return;
|
|
2235
|
+
}
|
|
2236
|
+
if (!isVector(target) || isElementLocked(scene, target)) return showStatus('Choose vector artwork on an unlocked layer.');
|
|
2237
|
+
if (activeTool === 'ink') {
|
|
2238
|
+
updatePoseProperty(target, 'stroke', paintColor.value);
|
|
2239
|
+
updatePoseProperty(target, 'strokeWidth', size);
|
|
2240
|
+
} else if (!hasVectorFill(target) || target.bitmapFill) {
|
|
2241
|
+
return showStatus('Choose a closed shape with a solid or gradient fill.');
|
|
2242
|
+
} else if (activeTool === 'bucket') {
|
|
2243
|
+
updatePoseProperty(target, 'fill', paintColor.value);
|
|
2244
|
+
updatePoseProperty(target, 'gradient', structuredClone(sampledGradient));
|
|
2245
|
+
} else {
|
|
2246
|
+
if (!poseAt(target, playhead).gradient) return showStatus('Choose a shape with a gradient fill.');
|
|
2247
|
+
dragState = { mode: 'paint', type: activeTool, pointerId: event.pointerId, points: [point], target, translate: event.shiftKey };
|
|
2248
|
+
}
|
|
2249
|
+
selectObjects([target], false);
|
|
2250
|
+
}
|
|
2251
|
+
if (dragState) elements.canvas.setPointerCapture(event.pointerId);
|
|
2252
|
+
renderAll();
|
|
2253
|
+
return;
|
|
2254
|
+
}
|
|
2255
|
+
if (activeTool === 'pen' || activeTool === 'polygon') {
|
|
2256
|
+
if (!pendingPath) pendingPath = { kind: activeTool, points: [], pointerId: null, dragOrigin: null, cursor: point };
|
|
2257
|
+
const first = pendingPath.points[0];
|
|
2258
|
+
if (
|
|
2259
|
+
pendingPath.points.length >= 3 &&
|
|
2260
|
+
first &&
|
|
2261
|
+
Math.hypot(first.x - point.x, first.y - point.y) < 12 * stageUnitsPerCssPixel(elements.canvas)
|
|
2262
|
+
) {
|
|
2263
|
+
finishPendingPath(true);
|
|
2264
|
+
return;
|
|
2265
|
+
}
|
|
2266
|
+
const anchor = { ...point, handleIn: { x: 0, y: 0 }, handleOut: { x: 0, y: 0 } };
|
|
2267
|
+
pendingPath.points.push(anchor);
|
|
2268
|
+
if (pendingPath.kind === 'pen') {
|
|
2269
|
+
pendingPath.pointerId = event.pointerId;
|
|
2270
|
+
pendingPath.dragOrigin = point;
|
|
2271
|
+
elements.canvas.setPointerCapture(event.pointerId);
|
|
2272
|
+
}
|
|
2273
|
+
selectedElementIds = [];
|
|
2274
|
+
renderAll();
|
|
2275
|
+
return;
|
|
2276
|
+
}
|
|
2277
|
+
|
|
2278
|
+
if (current && ['select', 'scale', 'rotate'].includes(activeTool) && isRotationHandleHit(poseAt(current, playhead), point)) {
|
|
2279
|
+
if (isElementLocked(scene, current)) {
|
|
2280
|
+
showStatus('Unlock the layer to transform this element', true);
|
|
2281
|
+
return;
|
|
2282
|
+
}
|
|
2283
|
+
const pose = poseAt(current, playhead);
|
|
2284
|
+
dragState = {
|
|
2285
|
+
mode: 'rotate',
|
|
2286
|
+
start: point,
|
|
2287
|
+
elementId: current.id,
|
|
2288
|
+
startPose: pose,
|
|
2289
|
+
startAngle: Math.atan2(point.y - pose.y, point.x - pose.x),
|
|
2290
|
+
};
|
|
2291
|
+
elements.canvas.setPointerCapture(event.pointerId);
|
|
2292
|
+
return;
|
|
2293
|
+
}
|
|
2294
|
+
if (current && ['select', 'scale', 'rotate'].includes(activeTool)) {
|
|
2295
|
+
const handle = findScaleHandle(poseAt(current, playhead), point);
|
|
2296
|
+
if (handle) {
|
|
2297
|
+
if (isElementLocked(scene, current)) {
|
|
2298
|
+
showStatus('Unlock the layer to transform this element', true);
|
|
2299
|
+
return;
|
|
2300
|
+
}
|
|
2301
|
+
dragState = { mode: 'scale', start: point, elementId: current.id, startPose: poseAt(current, playhead), handle };
|
|
2302
|
+
elements.canvas.setPointerCapture(event.pointerId);
|
|
2303
|
+
return;
|
|
2304
|
+
}
|
|
2305
|
+
}
|
|
2306
|
+
|
|
2307
|
+
if (Object.hasOwn(controlDefinitions, activeTool) || ['rectangle', 'roundedRectangle', 'ellipse', 'circle', 'triangle', 'diamond', 'pentagon', 'hexagon', 'star', 'line', 'curve', 'text'].includes(activeTool)) {
|
|
2308
|
+
dragState = { mode: 'draw', type: activeTool, start: point, current: point };
|
|
2309
|
+
elements.canvas.setPointerCapture(event.pointerId);
|
|
2310
|
+
renderCanvas();
|
|
2311
|
+
return;
|
|
2312
|
+
}
|
|
2313
|
+
|
|
2314
|
+
const hit = elementAt(scene, point);
|
|
2315
|
+
if (!hit) selectedElementIds = [];
|
|
2316
|
+
else if (!selectedElementIds.includes(hit.id) || selectedElementIds.length === 1) selectObjects(groupMembers(scene, hit), false);
|
|
2317
|
+
if (hit && selectedElementIds.length > 1) {
|
|
2318
|
+
if (activeTool === 'select') beginSelectionTransform(scene, 'move', point, event.pointerId);
|
|
2319
|
+
renderAll();
|
|
2320
|
+
return;
|
|
2321
|
+
}
|
|
2322
|
+
if (hit && activeTool === 'select') {
|
|
2323
|
+
if (isElementLocked(scene, hit)) {
|
|
2324
|
+
dragState = null;
|
|
2325
|
+
showStatus('Selected element is on a locked layer');
|
|
2326
|
+
} else {
|
|
2327
|
+
const pose = poseAt(hit, playhead);
|
|
2328
|
+
dragState = {
|
|
2329
|
+
mode: 'move',
|
|
2330
|
+
start: point,
|
|
2331
|
+
elementId: hit.id,
|
|
2332
|
+
offsetX: point.x - pose.x,
|
|
2333
|
+
offsetY: point.y - pose.y,
|
|
2334
|
+
};
|
|
2335
|
+
elements.canvas.setPointerCapture(event.pointerId);
|
|
2336
|
+
}
|
|
2337
|
+
} else {
|
|
2338
|
+
dragState = null;
|
|
2339
|
+
}
|
|
2340
|
+
renderAll();
|
|
2341
|
+
});
|
|
2342
|
+
|
|
2343
|
+
elements.stageMat.addEventListener('pointermove', event => {
|
|
2344
|
+
if (isInteractivePreview() || event.target !== elements.canvas) return;
|
|
2345
|
+
if (pendingPath?.pointerId === event.pointerId) {
|
|
2346
|
+
const point = pointerToStage(event);
|
|
2347
|
+
pendingPath.cursor = point;
|
|
2348
|
+
const anchor = pendingPath.points[pendingPath.points.length - 1];
|
|
2349
|
+
const dx = point.x - pendingPath.dragOrigin.x;
|
|
2350
|
+
const dy = point.y - pendingPath.dragOrigin.y;
|
|
2351
|
+
if (Math.hypot(dx, dy) > 3 * stageUnitsPerCssPixel(elements.canvas)) {
|
|
2352
|
+
anchor.handleOut = { x: dx, y: dy };
|
|
2353
|
+
anchor.handleIn = { x: -dx, y: -dy };
|
|
2354
|
+
}
|
|
2355
|
+
renderCanvas();
|
|
2356
|
+
return;
|
|
2357
|
+
}
|
|
2358
|
+
if (pendingPath && pendingPath.pointerId === null) {
|
|
2359
|
+
pendingPath.cursor = pointerToStage(event);
|
|
2360
|
+
renderCanvas();
|
|
2361
|
+
}
|
|
2362
|
+
const point = pointerToStage(event);
|
|
2363
|
+
if (!dragState) {
|
|
2364
|
+
if (['select', 'scale', 'rotate'].includes(activeTool)) updateSelectionCursor(point);
|
|
2365
|
+
return;
|
|
2366
|
+
}
|
|
2367
|
+
if (dragState.mode === 'paint') {
|
|
2368
|
+
if (event.pointerId !== dragState.pointerId) return;
|
|
2369
|
+
const last = dragState.points.at(-1);
|
|
2370
|
+
if (Math.hypot(point.x - last.x, point.y - last.y) >= .5 * stageUnitsPerCssPixel(elements.canvas)) {
|
|
2371
|
+
dragState.points.push(point);
|
|
2372
|
+
renderCanvas();
|
|
2373
|
+
}
|
|
2374
|
+
return;
|
|
2375
|
+
}
|
|
2376
|
+
if (dragState.mode === 'draw') {
|
|
2377
|
+
dragState.current = point;
|
|
2378
|
+
renderCanvas();
|
|
2379
|
+
return;
|
|
2380
|
+
}
|
|
2381
|
+
if (!dragState.moved) {
|
|
2382
|
+
const distance = Math.hypot(point.x - dragState.start.x, point.y - dragState.start.y);
|
|
2383
|
+
if (distance < 2 * stageUnitsPerCssPixel(elements.canvas)) return;
|
|
2384
|
+
dragState.moved = true;
|
|
2385
|
+
}
|
|
2386
|
+
if (dragState.mode === 'selection') {
|
|
2387
|
+
const { sources, start, center, transform } = dragState;
|
|
2388
|
+
const offset = { x: 0, y: 0 };
|
|
2389
|
+
let scale = 1, angle = 0;
|
|
2390
|
+
if (transform === 'move') {
|
|
2391
|
+
offset.x = Math.round(point.x - start.x);
|
|
2392
|
+
offset.y = Math.round(point.y - start.y);
|
|
2393
|
+
} else if (transform === 'scale') {
|
|
2394
|
+
const radius = Math.hypot(start.x - center.x, start.y - center.y);
|
|
2395
|
+
scale = Math.hypot(point.x - center.x, point.y - center.y) / (radius || 1);
|
|
2396
|
+
} else {
|
|
2397
|
+
angle = Math.atan2(point.y - center.y, point.x - center.x) - Math.atan2(start.y - center.y, start.x - center.x);
|
|
2398
|
+
}
|
|
2399
|
+
transformMembers(sources, center, offset, scale, angle, workingStage());
|
|
2400
|
+
renderCanvas();
|
|
2401
|
+
return;
|
|
2402
|
+
}
|
|
2403
|
+
const element = activeScene()?.elements.find(item => item.id === dragState.elementId);
|
|
2404
|
+
if (!element) return;
|
|
2405
|
+
if (dragState.mode === 'move') {
|
|
2406
|
+
updatePoseProperty(element, 'x', Math.round(point.x - dragState.offsetX));
|
|
2407
|
+
updatePoseProperty(element, 'y', Math.round(point.y - dragState.offsetY));
|
|
2408
|
+
} else if (dragState.mode === 'scale') {
|
|
2409
|
+
const local = pointToLocal(point, dragState.startPose);
|
|
2410
|
+
if (dragState.handle.axes.includes('x')) {
|
|
2411
|
+
updatePoseProperty(element, 'scaleX', Math.max(0.01, dragState.startPose.scaleX * Math.abs(local.x / dragState.handle.x)));
|
|
2412
|
+
}
|
|
2413
|
+
if (dragState.handle.axes.includes('y')) {
|
|
2414
|
+
updatePoseProperty(element, 'scaleY', Math.max(0.01, dragState.startPose.scaleY * Math.abs(local.y / dragState.handle.y)));
|
|
2415
|
+
}
|
|
2416
|
+
} else if (dragState.mode === 'rotate') {
|
|
2417
|
+
const angle = Math.atan2(point.y - dragState.startPose.y, point.x - dragState.startPose.x);
|
|
2418
|
+
const delta = angle - dragState.startAngle;
|
|
2419
|
+
updatePoseProperty(element, 'rotation', dragState.startPose.rotation + (delta * 180) / Math.PI);
|
|
2420
|
+
} else if (dragState.mode === 'path-anchor' || dragState.mode.startsWith('path-handle-')) {
|
|
2421
|
+
const local = pointToLocal(point, poseAt(element, playhead));
|
|
2422
|
+
const key = ensureKeyframe(element, playhead);
|
|
2423
|
+
key.points ??= structuredClone(element.points);
|
|
2424
|
+
const anchor = key.points[dragState.index];
|
|
2425
|
+
if (dragState.mode === 'path-anchor') {
|
|
2426
|
+
anchor.x = local.x;
|
|
2427
|
+
anchor.y = local.y;
|
|
2428
|
+
} else {
|
|
2429
|
+
const handle = { x: local.x - anchor.x, y: local.y - anchor.y };
|
|
2430
|
+
if (dragState.mode === 'path-handle-in') {
|
|
2431
|
+
anchor.handleIn = handle;
|
|
2432
|
+
anchor.handleOut = { x: -handle.x, y: -handle.y };
|
|
2433
|
+
} else {
|
|
2434
|
+
anchor.handleOut = handle;
|
|
2435
|
+
anchor.handleIn = { x: -handle.x, y: -handle.y };
|
|
2436
|
+
}
|
|
2437
|
+
}
|
|
2438
|
+
}
|
|
2439
|
+
renderCanvas();
|
|
2440
|
+
renderInspector();
|
|
2441
|
+
});
|
|
2442
|
+
|
|
2443
|
+
function endDrag(event, cancelled = false) {
|
|
2444
|
+
if (isInteractivePreview()) return;
|
|
2445
|
+
if (pendingPath?.pointerId === event.pointerId) {
|
|
2446
|
+
pendingPath.pointerId = null;
|
|
2447
|
+
pendingPath.dragOrigin = null;
|
|
2448
|
+
if (elements.canvas.hasPointerCapture(event.pointerId)) {
|
|
2449
|
+
elements.canvas.releasePointerCapture(event.pointerId);
|
|
2450
|
+
}
|
|
2451
|
+
return;
|
|
2452
|
+
}
|
|
2453
|
+
if (!dragState) return;
|
|
2454
|
+
if (dragState.mode === 'paint' && event.pointerId !== dragState.pointerId) return;
|
|
2455
|
+
const finishedDrag = dragState;
|
|
2456
|
+
dragState = null;
|
|
2457
|
+
if (cancelled && finishedDrag.mode === 'selection') {
|
|
2458
|
+
transformMembers(finishedDrag.sources, finishedDrag.center, { x: 0, y: 0 }, 1, 0, workingStage());
|
|
2459
|
+
}
|
|
2460
|
+
if (elements.canvas.hasPointerCapture(event.pointerId)) {
|
|
2461
|
+
elements.canvas.releasePointerCapture(event.pointerId);
|
|
2462
|
+
}
|
|
2463
|
+
if (finishedDrag.mode === 'paint' && !cancelled) {
|
|
2464
|
+
const { type, points, size, color, target, translate } = finishedDrag;
|
|
2465
|
+
const end = pointerToStage(event);
|
|
2466
|
+
if (end.x !== points.at(-1).x || end.y !== points.at(-1).y) points.push(end);
|
|
2467
|
+
if (type === 'gradientTransform') {
|
|
2468
|
+
try {
|
|
2469
|
+
const gradient = gradientDrag(target, poseAt(target, playhead), points[0], end, translate);
|
|
2470
|
+
if (gradient) updatePoseProperty(target, 'gradient', gradient);
|
|
2471
|
+
} catch (error) { showStatus(error.message, true); }
|
|
2472
|
+
} else if (type === 'eraser') {
|
|
2473
|
+
eraseArtwork(activeScene(), activeLayer(), playhead, points, size, updatePoseProperty);
|
|
2474
|
+
} else {
|
|
2475
|
+
const [main, ...subpaths] = type === 'brush' ? paintStroke(points, size) : [points.map(anchor)];
|
|
2476
|
+
if (main?.length >= (type === 'brush' ? 3 : 2)) {
|
|
2477
|
+
pendingPath = { kind: type, points: main, subpaths, size, color };
|
|
2478
|
+
finishPendingPath(type === 'brush');
|
|
2479
|
+
return;
|
|
2480
|
+
}
|
|
2481
|
+
}
|
|
2482
|
+
renderAll();
|
|
2483
|
+
return;
|
|
2484
|
+
}
|
|
2485
|
+
if (finishedDrag.mode === 'draw' && !cancelled) {
|
|
2486
|
+
commitDrawnObject(finishedDrag.type, finishedDrag.start, finishedDrag.current, event.shiftKey);
|
|
2487
|
+
} else {
|
|
2488
|
+
renderAll();
|
|
2489
|
+
}
|
|
2490
|
+
}
|
|
2491
|
+
elements.stageMat.addEventListener('pointerup', event => endDrag(event));
|
|
2492
|
+
elements.stageMat.addEventListener('pointercancel', event => endDrag(event, true));
|
|
2493
|
+
elements.canvas.addEventListener('dblclick', event => {
|
|
2494
|
+
if (isInteractivePreview() || activeTool !== 'select') return;
|
|
2495
|
+
const point = pointerToStage(event);
|
|
2496
|
+
const scene = activeScene();
|
|
2497
|
+
const hit = elementAt(scene, point);
|
|
2498
|
+
if (hit?.type === 'text') openTextEditor(hit);
|
|
2499
|
+
if (hit?.type === 'symbol') enterSymbol(hit.symbolId);
|
|
2500
|
+
});
|
|
2501
|
+
|
|
2502
|
+
elements.closePath.addEventListener('click', () => finishPendingPath(true));
|
|
2503
|
+
elements.finishPath.addEventListener('click', () => finishPendingPath(pendingPath?.kind === 'polygon'));
|
|
2504
|
+
elements.editText.addEventListener('click', () => {
|
|
2505
|
+
const element = selectedElement();
|
|
2506
|
+
if (element?.type === 'text') openTextEditor(element);
|
|
2507
|
+
});
|
|
2508
|
+
elements.textEditInput.addEventListener('input', () => {
|
|
2509
|
+
const element = activeScene()?.elements.find(item => item.id === editingTextElementId);
|
|
2510
|
+
if (!element) return;
|
|
2511
|
+
updatePoseProperty(element, 'text', elements.textEditInput.value);
|
|
2512
|
+
renderCanvas();
|
|
2513
|
+
});
|
|
2514
|
+
elements.textEditDone.addEventListener('click', () => closeTextEditor(true));
|
|
2515
|
+
elements.textEditCancel.addEventListener('click', () => closeTextEditor(false));
|
|
2516
|
+
elements.textEditInput.addEventListener('keydown', event => {
|
|
2517
|
+
if (event.key === 'Escape') {
|
|
2518
|
+
event.preventDefault();
|
|
2519
|
+
closeTextEditor(false);
|
|
2520
|
+
} else if (event.key === 'Enter' && (event.metaKey || event.ctrlKey)) {
|
|
2521
|
+
event.preventDefault();
|
|
2522
|
+
closeTextEditor(true);
|
|
2523
|
+
}
|
|
2524
|
+
});
|
|
2525
|
+
function closeProjectIoDialog() {
|
|
2526
|
+
mediaImportVersion++;
|
|
2527
|
+
sampleRequest?.abort();
|
|
2528
|
+
if (elements.projectIoDialog.open) elements.projectIoDialog.close();
|
|
2529
|
+
elements.projectIoError.hidden = true;
|
|
2530
|
+
elements.projectIoError.textContent = '';
|
|
2531
|
+
}
|
|
2532
|
+
|
|
2533
|
+
function downloadFile(blob, filename) {
|
|
2534
|
+
const url = URL.createObjectURL(blob);
|
|
2535
|
+
const link = document.createElement('a');
|
|
2536
|
+
link.href = url;
|
|
2537
|
+
link.download = filename;
|
|
2538
|
+
document.body.append(link);
|
|
2539
|
+
link.click();
|
|
2540
|
+
link.remove();
|
|
2541
|
+
setTimeout(() => URL.revokeObjectURL(url), 10000);
|
|
2542
|
+
}
|
|
2543
|
+
|
|
2544
|
+
async function downloadMovie(format) {
|
|
2545
|
+
const button = exportButton;
|
|
2546
|
+
if (button.disabled) return;
|
|
2547
|
+
button.disabled = true;
|
|
2548
|
+
const stop = startBusy(`Exporting ${format.toUpperCase()}…`);
|
|
2549
|
+
const notice = document.querySelector('#project-io-notice');
|
|
2550
|
+
notice.textContent = '';
|
|
2551
|
+
elements.projectIoError.hidden = true;
|
|
2552
|
+
document.querySelector('#export-error-script').hidden = true;
|
|
2553
|
+
try {
|
|
2554
|
+
const name = projectSession.name || 'movie';
|
|
2555
|
+
const response = await fetch(`/api/export/${format}`, {
|
|
2556
|
+
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
|
2557
|
+
body: JSON.stringify({ project: projectDocument(project), projectId: projectSession.served ? projectSession.id : null, name,
|
|
2558
|
+
externalResources: format === 'html' ? document.querySelector('#export-network').value : undefined }),
|
|
2559
|
+
});
|
|
2560
|
+
if (!response.ok) {
|
|
2561
|
+
const body = await response.json().catch(() => ({}));
|
|
2562
|
+
throw movieBuildError(response, body);
|
|
2563
|
+
}
|
|
2564
|
+
let blob, filename, version, report;
|
|
2565
|
+
if (format === 'html') {
|
|
2566
|
+
blob = await response.blob();
|
|
2567
|
+
const encoded = response.headers.get('Content-Disposition')?.match(/filename\*=UTF-8''([^;]+)/i)?.[1];
|
|
2568
|
+
filename = encoded ? decodeURIComponent(encoded) : 'movie.html';
|
|
2569
|
+
const notes = JSON.parse(decodeURIComponent(response.headers.get('X-Swoof-Notes') ?? '[]'));
|
|
2570
|
+
notice.textContent = notes.join('. ');
|
|
2571
|
+
} else {
|
|
2572
|
+
const body = await response.json();
|
|
2573
|
+
const bytes = Uint8Array.from(atob(body.swf), char => char.charCodeAt(0));
|
|
2574
|
+
blob = new Blob([bytes], { type: 'application/x-shockwave-flash' });
|
|
2575
|
+
filename = body.name;
|
|
2576
|
+
version = body.version;
|
|
2577
|
+
report = body.report;
|
|
2578
|
+
}
|
|
2579
|
+
downloadFile(blob, filename);
|
|
2580
|
+
showStatus(`Exported ${filename}${version ? ` (SWF ${version})` : ''}`);
|
|
2581
|
+
if (report?.entries?.length) {
|
|
2582
|
+
elements.projectIoDialog.close();
|
|
2583
|
+
projectsUi.showReport(report);
|
|
2584
|
+
}
|
|
2585
|
+
} catch (error) {
|
|
2586
|
+
elements.projectIoError.textContent = `Could not export ${format.toUpperCase()}: ${error.message}`;
|
|
2587
|
+
elements.projectIoError.hidden = false;
|
|
2588
|
+
showScriptErrorLink('#export-error-script', error.diagnostic);
|
|
2589
|
+
} finally {
|
|
2590
|
+
stop();
|
|
2591
|
+
button.disabled = false;
|
|
2592
|
+
}
|
|
2593
|
+
}
|
|
2594
|
+
|
|
2595
|
+
// Video export renders in this tab with WebCodecs (studiospec/video-export.md). The dialog is
|
|
2596
|
+
// modal, so the project cannot change while it records.
|
|
2597
|
+
let videoExport = null;
|
|
2598
|
+
const videoProgress = document.querySelector('#export-video-progress');
|
|
2599
|
+
|
|
2600
|
+
// Video formats this browser cannot encode are disabled in the Format menu. Probing starts the
|
|
2601
|
+
// browser's encoders, so it runs only once a video format is chosen.
|
|
2602
|
+
async function prepareVideoExport() {
|
|
2603
|
+
const field = document.querySelector('#export-video-field');
|
|
2604
|
+
delete field.dataset.ready;
|
|
2605
|
+
// Without audio clips there is nothing to include, so the dialog says so instead of offering a choice.
|
|
2606
|
+
showVideoSound();
|
|
2607
|
+
const { supportedFormats } = await import('./video-encode.js');
|
|
2608
|
+
const { supportedAnimatedFormats } = await import('./animated-image.js');
|
|
2609
|
+
const formats = [...await supportedFormats(project.stage).catch(() => []), ...supportedAnimatedFormats(), 'svg', 'lottie'];
|
|
2610
|
+
const select = document.querySelector('#export-video-format');
|
|
2611
|
+
for (const option of select.options) {
|
|
2612
|
+
option.disabled = !formats.includes(option.value);
|
|
2613
|
+
option.title = option.disabled ? 'This browser cannot encode this format' : '';
|
|
2614
|
+
}
|
|
2615
|
+
field.dataset.ready = 'true';
|
|
2616
|
+
if (!formats.some(format => format === 'mp4' || format === 'webm')) {
|
|
2617
|
+
document.querySelector('#project-io-notice').textContent = 'This browser cannot encode video (MP4 or WebM). Use a recent Chrome or Edge, or choose an animated image.';
|
|
2618
|
+
}
|
|
2619
|
+
if (select.selectedOptions[0]?.disabled) select.value = formats[0];
|
|
2620
|
+
showVideoSound();
|
|
2621
|
+
}
|
|
2622
|
+
|
|
2623
|
+
// Sound applies to MP4 and WebM; animated images are silent, and a project without audio has nothing to include.
|
|
2624
|
+
function showVideoSound() {
|
|
2625
|
+
const format = document.querySelector('#export-video-format').value;
|
|
2626
|
+
const animated = ['gif', 'apng', 'webp', 'svg', 'lottie'].includes(format);
|
|
2627
|
+
// Lottie is drawn at any size by its player: the stage size is written.
|
|
2628
|
+
document.querySelector('#export-video-scale').disabled = format === 'lottie';
|
|
2629
|
+
const hasAudio = projectHasSound(project);
|
|
2630
|
+
document.querySelector('#export-video-sound-field').hidden = animated || !hasAudio;
|
|
2631
|
+
document.querySelector('#export-video-no-sound').hidden = animated || hasAudio;
|
|
2632
|
+
document.querySelector('#export-video-silent').hidden = !animated;
|
|
2633
|
+
// SVG and Lottie can carry the project for an exact re-import; each format keeps its own choice.
|
|
2634
|
+
const embed = document.querySelector('#export-video-embed');
|
|
2635
|
+
document.querySelector('#export-video-embed-field').hidden = !(format in embedChoice);
|
|
2636
|
+
if (format in embedChoice) embed.checked = embedChoice[format];
|
|
2637
|
+
}
|
|
2638
|
+
// Lottie embeds by default (files are passed around between tools); SVG stays small by default.
|
|
2639
|
+
const embedChoice = { svg: false, lottie: true };
|
|
2640
|
+
document.querySelector('#export-video-format').addEventListener('change', showVideoSound);
|
|
2641
|
+
document.querySelector('#export-video-embed').addEventListener('change', event => {
|
|
2642
|
+
const format = document.querySelector('#export-video-format').value;
|
|
2643
|
+
if (format in embedChoice) embedChoice[format] = event.target.checked;
|
|
2644
|
+
});
|
|
2645
|
+
|
|
2646
|
+
async function downloadVideo(format) {
|
|
2647
|
+
if (videoExport) {
|
|
2648
|
+
videoExport.abort();
|
|
2649
|
+
return;
|
|
2650
|
+
}
|
|
2651
|
+
const notice = document.querySelector('#project-io-notice');
|
|
2652
|
+
notice.textContent = '';
|
|
2653
|
+
elements.projectIoError.hidden = true;
|
|
2654
|
+
document.querySelector('#export-error-script').hidden = true;
|
|
2655
|
+
const controller = new AbortController();
|
|
2656
|
+
videoExport = controller;
|
|
2657
|
+
exportButton.textContent = 'Cancel';
|
|
2658
|
+
videoProgress.value = 0;
|
|
2659
|
+
videoProgress.hidden = false;
|
|
2660
|
+
const fields = ['#export-format', '#export-video-format', '#export-video-scale', '#export-video-length', '#export-video-sound', '#export-video-embed'].map(id => document.querySelector(id));
|
|
2661
|
+
const wasDisabled = fields.map(field => field.disabled);
|
|
2662
|
+
for (const field of fields) field.disabled = true;
|
|
2663
|
+
try {
|
|
2664
|
+
const { exportVideo } = await import('./video-export.js');
|
|
2665
|
+
const maxSeconds = Number(fields[3].value);
|
|
2666
|
+
if (!Number.isFinite(maxSeconds) || maxSeconds < 1 || maxSeconds > 600) throw new Error('Choose a maximum length from 1 to 600 seconds');
|
|
2667
|
+
const result = await exportVideo(project, {
|
|
2668
|
+
format, scale: Number(fields[2].value), includeSound: fields[4].checked && !document.querySelector('#export-video-sound-field').hidden,
|
|
2669
|
+
maxSeconds, signal: controller.signal, recordPreview: buildRecordingPreview,
|
|
2670
|
+
studioData: format in embedChoice ? document.querySelector('#export-video-embed').checked : undefined,
|
|
2671
|
+
onProgress: (fraction, message) => {
|
|
2672
|
+
videoProgress.value = fraction;
|
|
2673
|
+
notice.textContent = message;
|
|
2674
|
+
},
|
|
2675
|
+
});
|
|
2676
|
+
if (controller.signal.aborted) throw new DOMException('cancelled', 'AbortError');
|
|
2677
|
+
const base = (projectSession.name || 'movie').replace(/[\\/:*?"<>|]+/g, '-').trim() || 'movie';
|
|
2678
|
+
const { ANIMATED_FORMATS } = await import('./animated-image.js');
|
|
2679
|
+
const filename = format === 'lottie' ? `${base}-lottie.json` : `${base}.${ANIMATED_FORMATS[format]?.extension ?? format}`;
|
|
2680
|
+
downloadFile(result.blob, filename);
|
|
2681
|
+
const ending = { stop: 'ends where the movie stops',
|
|
2682
|
+
repeat: format === 'svg' ? 'then loops from where the movie repeats'
|
|
2683
|
+
: format === 'lottie' ? `ends where the movie starts to repeat${result.loopFrom ? ' (its "loop" marker is where the repeat starts; players loop the whole file)' : ''}`
|
|
2684
|
+
: 'ends where the movie starts to repeat',
|
|
2685
|
+
length: 'reached the maximum length' }[result.ending];
|
|
2686
|
+
notice.textContent = `Exported ${filename}: ${result.width} × ${result.height}, ${result.seconds.toFixed(1)} s${result.audio ? ' with sound' : ''}; it ${ending}` +
|
|
2687
|
+
`${svgDetails(result.blob, result.fonts ?? [], result.notes ?? [])}.` +
|
|
2688
|
+
(result.audioUnavailable ? ' Sound was left out: this browser cannot encode it.' : '');
|
|
2689
|
+
showStatus(`Exported ${filename}`);
|
|
2690
|
+
} catch (error) {
|
|
2691
|
+
if (error.name === 'AbortError') {
|
|
2692
|
+
notice.textContent = 'Video export cancelled';
|
|
2693
|
+
} else {
|
|
2694
|
+
notice.textContent = '';
|
|
2695
|
+
elements.projectIoError.textContent = `Could not export video: ${error.message}`;
|
|
2696
|
+
elements.projectIoError.hidden = false;
|
|
2697
|
+
}
|
|
2698
|
+
} finally {
|
|
2699
|
+
videoExport = null;
|
|
2700
|
+
exportButton.textContent = 'Export';
|
|
2701
|
+
videoProgress.hidden = true;
|
|
2702
|
+
fields.forEach((field, i) => { field.disabled = wasDisabled[i]; });
|
|
2703
|
+
}
|
|
2704
|
+
}
|
|
2705
|
+
|
|
2706
|
+
// What an SVG export holds besides its size: file size, fonts its text needs, approximations.
|
|
2707
|
+
function svgDetails(blob, fonts, notes) {
|
|
2708
|
+
if (blob.type !== 'image/svg+xml' && blob.type !== 'application/json') return '';
|
|
2709
|
+
const size = blob.size >= 1e6 ? `${(blob.size / 1e6).toFixed(1)} MB` : `${Math.max(1, Math.round(blob.size / 1e3))} KB`;
|
|
2710
|
+
let text = `, ${size}`;
|
|
2711
|
+
if (fonts.length) text += `. Its text uses ${fonts.join(', ')}: viewers without these fonts show others`;
|
|
2712
|
+
if (notes.length) text += `. Not exactly as in Studio: ${notes.join('; ')}`;
|
|
2713
|
+
return text;
|
|
2714
|
+
}
|
|
2715
|
+
|
|
2716
|
+
// The frame on the stage, as Preview or the editor shows it, without editor overlays.
|
|
2717
|
+
async function downloadFrame(format) {
|
|
2718
|
+
const button = exportButton;
|
|
2719
|
+
const scene = activeScene();
|
|
2720
|
+
if (button.disabled || !scene) return;
|
|
2721
|
+
button.disabled = true;
|
|
2722
|
+
const notice = document.querySelector('#project-io-notice');
|
|
2723
|
+
notice.textContent = '';
|
|
2724
|
+
elements.projectIoError.hidden = true;
|
|
2725
|
+
document.querySelector('#export-error-script').hidden = true;
|
|
2726
|
+
try {
|
|
2727
|
+
const preview = isInteractivePreview();
|
|
2728
|
+
const options = { project, stage: workingStage(), scene, playhead, format, scale: Number(document.querySelector('#export-image-scale').value),
|
|
2729
|
+
hiddenIds: preview ? previewHiddenIds : new Set(), clocks: preview ? symbolClocks : new Map() };
|
|
2730
|
+
const { blob, width, height, notes = [], fonts = [] } = format === 'svg'
|
|
2731
|
+
? await (await import('./svg-frame.js')).renderFrameSvg(options)
|
|
2732
|
+
: await (await import('./frame-image.js')).renderFrameImage(options);
|
|
2733
|
+
const part = text => String(text).replace(/[\\/:*?"<>|]+/g, '-').trim();
|
|
2734
|
+
const filename = `${part(projectSession.name || 'movie') || 'movie'}-${part(scene.name) || 'scene'}-frame-${playhead}.${format === 'jpeg' ? 'jpg' : format}`;
|
|
2735
|
+
downloadFile(blob, filename);
|
|
2736
|
+
notice.textContent = `Exported ${filename}: ${width} × ${height}${svgDetails(blob, fonts, notes)}.`;
|
|
2737
|
+
showStatus(`Exported ${filename}`);
|
|
2738
|
+
} catch (error) {
|
|
2739
|
+
elements.projectIoError.textContent = `Could not export the frame: ${error.message}`;
|
|
2740
|
+
elements.projectIoError.hidden = false;
|
|
2741
|
+
} finally {
|
|
2742
|
+
button.disabled = false;
|
|
2743
|
+
}
|
|
2744
|
+
}
|
|
2745
|
+
|
|
2746
|
+
// The Export dialog: one Format menu, the options of that format, and one Export button.
|
|
2747
|
+
const exportButton = document.querySelector('#export-download');
|
|
2748
|
+
const exportFormatSelect = document.querySelector('#export-format');
|
|
2749
|
+
let exportFormat = 'html';
|
|
2750
|
+
function exportFrameLabel() {
|
|
2751
|
+
const timeline = activeScene();
|
|
2752
|
+
if (!timeline) return 'There is no scene to export.';
|
|
2753
|
+
return `${project.symbols.includes(timeline) ? 'Symbol' : 'Scene'} ${timeline.name}, frame ${playhead}, as on the stage, without selection or guides.`;
|
|
2754
|
+
}
|
|
2755
|
+
function showExportFormat() {
|
|
2756
|
+
const format = exportFormat = exportFormatSelect.value;
|
|
2757
|
+
const json = format === 'json';
|
|
2758
|
+
const notes = {
|
|
2759
|
+
json: 'The editable project with its media. Open it again with Import.',
|
|
2760
|
+
swf: 'A Flash movie with its scripts and media, for Flash Player, Ruffle or swf2js.',
|
|
2761
|
+
html: 'One HTML file that plays the movie offline, with its player and media.',
|
|
2762
|
+
video: 'A recording of the movie as Preview plays it, from the first scene, without input.',
|
|
2763
|
+
};
|
|
2764
|
+
const note = document.querySelector('#export-format-note');
|
|
2765
|
+
note.textContent = format === 'image' ? exportFrameLabel() : notes[format];
|
|
2766
|
+
elements.projectIoTextarea.hidden = !json || compactExportJson;
|
|
2767
|
+
elements.projectIoCopy.hidden = !json;
|
|
2768
|
+
document.querySelector('#export-network-field').hidden = format !== 'html';
|
|
2769
|
+
document.querySelector('#export-video-field').hidden = format !== 'video';
|
|
2770
|
+
document.querySelector('#export-image-field').hidden = format !== 'image';
|
|
2771
|
+
elements.projectIoError.hidden = true;
|
|
2772
|
+
document.querySelector('#export-error-script').hidden = true;
|
|
2773
|
+
document.querySelector('#project-io-notice').textContent = '';
|
|
2774
|
+
if (format === 'video') prepareVideoExport();
|
|
2775
|
+
}
|
|
2776
|
+
exportFormatSelect.addEventListener('change', showExportFormat);
|
|
2777
|
+
exportButton.addEventListener('click', () => {
|
|
2778
|
+
if (videoExport) return videoExport.abort();
|
|
2779
|
+
const format = exportFormatSelect.value;
|
|
2780
|
+
if (format === 'json') downloadJson();
|
|
2781
|
+
else if (format === 'swf' || format === 'html') downloadMovie(format);
|
|
2782
|
+
else if (format === 'video') downloadVideo(document.querySelector('#export-video-format').value);
|
|
2783
|
+
else downloadFrame(document.querySelector('#export-image-format').value);
|
|
2784
|
+
});
|
|
2785
|
+
|
|
2786
|
+
let exportJsonRequest;
|
|
2787
|
+
let compactExportJson = false;
|
|
2788
|
+
|
|
2789
|
+
function exportJsonText() {
|
|
2790
|
+
if (elements.projectIoTextarea.value) return Promise.resolve(elements.projectIoTextarea.value);
|
|
2791
|
+
const indent = compactExportJson ? 0 : 2;
|
|
2792
|
+
return exportJsonRequest ??= projectSession.exportDocument().then(doc => JSON.stringify(doc, null, indent));
|
|
2793
|
+
}
|
|
2794
|
+
|
|
2795
|
+
function showExportJsonError(error) {
|
|
2796
|
+
exportJsonRequest = undefined;
|
|
2797
|
+
elements.projectIoError.textContent = `Could not export project JSON: ${error.message}`;
|
|
2798
|
+
elements.projectIoError.hidden = false;
|
|
2799
|
+
}
|
|
2800
|
+
|
|
2801
|
+
function openProjectIoDialog(mode) {
|
|
2802
|
+
if (sceneTransition.active) leavePreview();
|
|
2803
|
+
mediaImportVersion++;
|
|
2804
|
+
sampleRequest?.abort();
|
|
2805
|
+
if (playing) stopPlayback();
|
|
2806
|
+
if (editingTextElementId) closeTextEditor(true);
|
|
2807
|
+
if (pendingPath) cancelPendingPath();
|
|
2808
|
+
elements.projectIoError.hidden = true;
|
|
2809
|
+
elements.projectIoError.textContent = '';
|
|
2810
|
+
document.querySelector('#export-error-script').hidden = true;
|
|
2811
|
+
document.querySelector('#project-io-notice').replaceChildren();
|
|
2812
|
+
|
|
2813
|
+
const isExport = mode === 'export';
|
|
2814
|
+
const isExamples = mode === 'examples';
|
|
2815
|
+
elements.projectIoDialog.dataset.mode = mode;
|
|
2816
|
+
elements.projectIoTitle.textContent = isExamples ? 'Open an example' : isExport ? 'Export project' : 'Import project';
|
|
2817
|
+
elements.projectIoDescription.textContent = isExport
|
|
2818
|
+
? 'Choose a format. Only its options are shown.'
|
|
2819
|
+
: isExamples ? 'Choose an editable project to open in Studio.'
|
|
2820
|
+
: 'Open a Studio project, a Lottie animation, a SWF movie or an SVG image: choose a file, drop it here, or paste JSON or SVG.';
|
|
2821
|
+
elements.projectIoExamples.hidden = isExport;
|
|
2822
|
+
// A game can contain hundreds of megabytes of formatted JSON. The HTML and
|
|
2823
|
+
// SWF buttons need neither the text layout nor a second embedded media copy.
|
|
2824
|
+
const mediaLength = isExport ? project.assets.reduce((total, asset) => total + (asset.data?.length ?? asset.bytes ?? 0), 0) : 0;
|
|
2825
|
+
compactExportJson = isExport && projectSession.savedDocumentLength + mediaLength > 1024 * 1024;
|
|
2826
|
+
exportJsonRequest = undefined;
|
|
2827
|
+
elements.projectIoTextarea.hidden = isExamples || compactExportJson;
|
|
2828
|
+
elements.projectIoTextarea.readOnly = isExport;
|
|
2829
|
+
elements.projectIoTextarea.placeholder = isExport
|
|
2830
|
+
? ''
|
|
2831
|
+
: 'Paste a Studio project, Lottie JSON or SVG';
|
|
2832
|
+
elements.projectIoTextarea.value = '';
|
|
2833
|
+
if (isExport && !compactExportJson && project.assets.every(asset => asset.data !== undefined)) {
|
|
2834
|
+
elements.projectIoTextarea.value = serializeProject(project);
|
|
2835
|
+
} else if (isExport && !compactExportJson) {
|
|
2836
|
+
elements.projectIoTextarea.placeholder = 'Embedding media…';
|
|
2837
|
+
const version = mediaImportVersion;
|
|
2838
|
+
exportJsonText().then(json => {
|
|
2839
|
+
if (version !== mediaImportVersion || !elements.projectIoDialog.open) return;
|
|
2840
|
+
elements.projectIoTextarea.value = json;
|
|
2841
|
+
elements.projectIoTextarea.select();
|
|
2842
|
+
}, error => {
|
|
2843
|
+
if (version === mediaImportVersion && elements.projectIoDialog.open) showExportJsonError(error);
|
|
2844
|
+
});
|
|
2845
|
+
}
|
|
2846
|
+
document.querySelector('#export-format-field').hidden = !isExport;
|
|
2847
|
+
document.querySelector('#export-format-note').hidden = !isExport;
|
|
2848
|
+
for (const id of ['#export-network-field', '#export-video-field', '#export-image-field']) document.querySelector(id).hidden = true;
|
|
2849
|
+
elements.projectIoCopy.hidden = true;
|
|
2850
|
+
if (isExport) {
|
|
2851
|
+
document.querySelector('#export-network').value = document.querySelector('#preview-network').value;
|
|
2852
|
+
exportFormatSelect.value = exportFormat;
|
|
2853
|
+
showExportFormat();
|
|
2854
|
+
}
|
|
2855
|
+
elements.projectIoSubmit.hidden = isExport || isExamples;
|
|
2856
|
+
elements.projectIoCancel.hidden = isExport || isExamples;
|
|
2857
|
+
elements.projectIoDialog.showModal();
|
|
2858
|
+
if (isExamples) elements.projectIoExamples.querySelector('button')?.focus();
|
|
2859
|
+
else if (isExport) exportFormatSelect.focus();
|
|
2860
|
+
else elements.projectIoTextarea.focus();
|
|
2861
|
+
}
|
|
2862
|
+
|
|
2863
|
+
async function copyExportedProject() {
|
|
2864
|
+
const version = mediaImportVersion;
|
|
2865
|
+
let json;
|
|
2866
|
+
try { json = await exportJsonText(); }
|
|
2867
|
+
catch (error) { if (version === mediaImportVersion) showExportJsonError(error); return; }
|
|
2868
|
+
if (version !== mediaImportVersion || !elements.projectIoDialog.open) return;
|
|
2869
|
+
try {
|
|
2870
|
+
if (!navigator.clipboard?.writeText) throw new Error('Clipboard API unavailable');
|
|
2871
|
+
await navigator.clipboard.writeText(json);
|
|
2872
|
+
document.querySelector('#project-io-notice').textContent = 'Animation JSON copied';
|
|
2873
|
+
} catch {
|
|
2874
|
+
elements.projectIoTextarea.hidden = false;
|
|
2875
|
+
elements.projectIoTextarea.value = json;
|
|
2876
|
+
elements.projectIoTextarea.focus();
|
|
2877
|
+
elements.projectIoTextarea.select();
|
|
2878
|
+
document.querySelector('#project-io-notice').textContent = 'Press Cmd/Ctrl+C to copy the selected JSON';
|
|
2879
|
+
}
|
|
2880
|
+
}
|
|
2881
|
+
|
|
2882
|
+
async function downloadJson() {
|
|
2883
|
+
const version = mediaImportVersion;
|
|
2884
|
+
try {
|
|
2885
|
+
const json = await exportJsonText();
|
|
2886
|
+
if (version === mediaImportVersion && elements.projectIoDialog.open) downloadFile(new Blob([json], { type: 'application/json' }), 'swoof-project.json');
|
|
2887
|
+
} catch (error) {
|
|
2888
|
+
if (version === mediaImportVersion) showExportJsonError(error);
|
|
2889
|
+
}
|
|
2890
|
+
}
|
|
2891
|
+
elements.projectIoDialog.addEventListener('close', () => {
|
|
2892
|
+
if (!elements.projectIoDialog.open) {
|
|
2893
|
+
videoExport?.abort();
|
|
2894
|
+
exportJsonRequest = undefined;
|
|
2895
|
+
elements.projectIoTextarea.value = '';
|
|
2896
|
+
}
|
|
2897
|
+
});
|
|
2898
|
+
|
|
2899
|
+
let mediaImportVersion = 0;
|
|
2900
|
+
function confirmDiscard() {
|
|
2901
|
+
projectSession.check();
|
|
2902
|
+
return !projectSession.dirty ||
|
|
2903
|
+
window.confirm(`Discard unsaved changes to ${projectSession.served ? projectSession.name : 'this project'}?`);
|
|
2904
|
+
}
|
|
2905
|
+
|
|
2906
|
+
// A Lottie animation (w, h, fr, op and layers), told from a Studio project without loading the
|
|
2907
|
+
// Lottie importer, so opening a project stays immediate.
|
|
2908
|
+
function lottieDocument(text) {
|
|
2909
|
+
if (!/"fr"\s*:/.test(text) || !/"layers"\s*:/.test(text)) return null;
|
|
2910
|
+
let value;
|
|
2911
|
+
try { value = JSON.parse(text); } catch { return null; }
|
|
2912
|
+
return value && value.format !== 'swoof-studio' && ['w', 'h', 'fr', 'op'].every(key => Number.isFinite(value[key])) && Array.isArray(value.layers) ? value : null;
|
|
2913
|
+
}
|
|
2914
|
+
|
|
2915
|
+
async function importProjectFromDialog(name) {
|
|
2916
|
+
const version = ++mediaImportVersion;
|
|
2917
|
+
try {
|
|
2918
|
+
// A Lottie animation becomes a project first; what it could not carry over is reported.
|
|
2919
|
+
let text = elements.projectIoTextarea.value, lottieNotes = null;
|
|
2920
|
+
const lottie = lottieDocument(text);
|
|
2921
|
+
if (lottie) {
|
|
2922
|
+
const [{ importLottie }, { studioTextLayout }] = await Promise.all([import('./lottie-import.js'), import('./lottie-export.js')]);
|
|
2923
|
+
const context = document.createElement('canvas').getContext('2d');
|
|
2924
|
+
const result = await importLottie(lottie, { layoutText: await studioTextLayout(),
|
|
2925
|
+
measure: (font, line) => { context.font = font; return context.measureText(line); } });
|
|
2926
|
+
if (version !== mediaImportVersion || !elements.projectIoDialog.open) return;
|
|
2927
|
+
text = result.json;
|
|
2928
|
+
lottieNotes = result.exact ? [] : result.notes;
|
|
2929
|
+
}
|
|
2930
|
+
if (!text.trim()) throw new Error('Choose a file, drop one here, or paste a Studio project, Lottie JSON or SVG');
|
|
2931
|
+
if (!lottie && !/^\uFEFF?\s*[{<]/.test(text)) throw new Error('This file is not a Studio project, Lottie animation, SWF movie or SVG image');
|
|
2932
|
+
// An SVG image becomes a one-frame project the same way.
|
|
2933
|
+
let source = lottie ? 'Lottie' : '';
|
|
2934
|
+
if (!lottie && /^\s*</.test(text)) {
|
|
2935
|
+
const [{ importSvg, isSvgText, rasterizeInBrowser }, { studioTextLayout }] = await Promise.all([import('./svg-import.js'), import('./lottie-export.js')]);
|
|
2936
|
+
if (!isSvgText(text)) throw new Error('This file is not a Studio project, Lottie animation, SWF movie or SVG image');
|
|
2937
|
+
const context = document.createElement('canvas').getContext('2d');
|
|
2938
|
+
const result = await importSvg(text, { layoutText: await studioTextLayout(), rasterize: rasterizeInBrowser,
|
|
2939
|
+
measure: (font, line) => { context.font = font; return context.measureText(line); },
|
|
2940
|
+
resolveColor: css => { context.fillStyle = '#000001'; context.fillStyle = css; return context.fillStyle === '#000001' ? '' : context.fillStyle; } });
|
|
2941
|
+
if (version !== mediaImportVersion || !elements.projectIoDialog.open) return;
|
|
2942
|
+
text = result.json;
|
|
2943
|
+
lottieNotes = result.exact ? [] : result.notes;
|
|
2944
|
+
source = 'SVG';
|
|
2945
|
+
}
|
|
2946
|
+
const imported = parseProjectJson(text);
|
|
2947
|
+
if (!confirmDiscard()) return;
|
|
2948
|
+
if (imported.assets?.length) {
|
|
2949
|
+
await Promise.all(imported.assets.map(decodeAsset));
|
|
2950
|
+
if (version !== mediaImportVersion || !elements.projectIoDialog.open) return;
|
|
2951
|
+
}
|
|
2952
|
+
closeProjectIoDialog();
|
|
2953
|
+
applyProjectDocument(imported);
|
|
2954
|
+
projectSession.detach(JSON.parse(serializeProject(project, 0)));
|
|
2955
|
+
projectsUi.resetReports();
|
|
2956
|
+
const opened = name ? `Opened ${name}` : `Imported ${project.scenes.length} scene${project.scenes.length === 1 ? '' : 's'}`;
|
|
2957
|
+
showStatus(lottieNotes?.length ? `${opened} from ${source}. Not exactly as in the file: ${lottieNotes.join('; ')}` : lottieNotes ? `${opened} from ${source}` : opened);
|
|
2958
|
+
} catch (error) {
|
|
2959
|
+
if (version !== mediaImportVersion || !elements.projectIoDialog.open) return;
|
|
2960
|
+
elements.projectIoError.textContent = error.message;
|
|
2961
|
+
elements.projectIoError.hidden = false;
|
|
2962
|
+
}
|
|
2963
|
+
}
|
|
2964
|
+
|
|
2965
|
+
/** Replace the open document with a validated project whose media is already decoded. */
|
|
2966
|
+
function applyProjectDocument(imported) {
|
|
2967
|
+
clearPreviewState();
|
|
2968
|
+
playing = false;
|
|
2969
|
+
schedulePlayback();
|
|
2970
|
+
project.assets = imported.assets ?? [];
|
|
2971
|
+
project.stage = imported.stage;
|
|
2972
|
+
project.scenes = imported.scenes;
|
|
2973
|
+
project.symbols = imported.symbols ?? [];
|
|
2974
|
+
project.scripts = imported.scripts ?? [];
|
|
2975
|
+
returnViews = [];
|
|
2976
|
+
idSequence = nextIdSequenceForProject(project);
|
|
2977
|
+
selectedSceneId = project.scenes[0].id;
|
|
2978
|
+
selectedLayerId = orderedSceneLayers(project.scenes[0]).at(-1)?.id ?? null;
|
|
2979
|
+
pendingLayerDeleteId = null;
|
|
2980
|
+
editingLayerId = null;
|
|
2981
|
+
selectedElementIds = [];
|
|
2982
|
+
playhead = project.scenes[0].startFrame ?? 1;
|
|
2983
|
+
activeTool = 'select';
|
|
2984
|
+
dragState = null;
|
|
2985
|
+
pendingPath = null;
|
|
2986
|
+
history.reset();
|
|
2987
|
+
renderAll();
|
|
2988
|
+
}
|
|
2989
|
+
|
|
2990
|
+
function prepareForDialog() {
|
|
2991
|
+
if (sceneTransition.active) leavePreview();
|
|
2992
|
+
if (playing) stopPlayback();
|
|
2993
|
+
if (editingTextElementId) closeTextEditor(true);
|
|
2994
|
+
if (pendingPath) cancelPendingPath();
|
|
2995
|
+
}
|
|
2996
|
+
|
|
2997
|
+
const projectsUi = createProjectsUi({
|
|
2998
|
+
session: projectSession,
|
|
2999
|
+
app: {
|
|
3000
|
+
getDocument: () => JSON.parse(serializeProject(project, 0)),
|
|
3001
|
+
report: showStatus,
|
|
3002
|
+
confirmDiscard,
|
|
3003
|
+
beforeDialog: prepareForDialog,
|
|
3004
|
+
async applyDocument(imported) {
|
|
3005
|
+
if (imported.assets?.length) await Promise.all(imported.assets.map(decodeAsset));
|
|
3006
|
+
applyProjectDocument(imported);
|
|
3007
|
+
},
|
|
3008
|
+
async mergeLibrary({ symbols, assets, scripts = [] }) {
|
|
3009
|
+
const current = JSON.parse(serializeProject(project, 0));
|
|
3010
|
+
const merged = parseProjectJson(JSON.stringify({
|
|
3011
|
+
...current,
|
|
3012
|
+
symbols: [...current.symbols ?? [], ...symbols],
|
|
3013
|
+
assets: [...current.assets ?? [], ...assets],
|
|
3014
|
+
scripts: [...current.scripts ?? [], ...scripts],
|
|
3015
|
+
}));
|
|
3016
|
+
const added = merged.assets?.slice(project.assets?.length ?? 0) ?? [];
|
|
3017
|
+
await Promise.all(added.map(decodeAsset));
|
|
3018
|
+
(project.assets ??= []).push(...added);
|
|
3019
|
+
(project.symbols ??= []).push(...merged.symbols.slice(project.symbols.length));
|
|
3020
|
+
if (merged.scripts?.length) project.scripts = merged.scripts;
|
|
3021
|
+
idSequence = Math.max(idSequence, nextIdSequenceForProject(project));
|
|
3022
|
+
preferredSymbol = project.symbols.at(-1)?.id;
|
|
3023
|
+
renderAll();
|
|
3024
|
+
},
|
|
3025
|
+
},
|
|
3026
|
+
});
|
|
3027
|
+
|
|
3028
|
+
function inspectorTrigger() {
|
|
3029
|
+
const trigger = elements.buttonTrigger.value;
|
|
3030
|
+
if (isKeyTrigger(trigger)) return { trigger, key: elements.buttonKey.value };
|
|
3031
|
+
if (trigger === 'swipe') return { trigger, direction: elements.buttonSwipe.value };
|
|
3032
|
+
return { trigger };
|
|
3033
|
+
}
|
|
3034
|
+
|
|
3035
|
+
function updateElementButtonFromInspector() {
|
|
3036
|
+
const element = selectedElement();
|
|
3037
|
+
const scene = activeScene();
|
|
3038
|
+
if (!element || !scene) return;
|
|
3039
|
+
if (!elements.elementIsButton.checked) {
|
|
3040
|
+
element.buttonAction = null;
|
|
3041
|
+
renderAll();
|
|
3042
|
+
return;
|
|
3043
|
+
}
|
|
3044
|
+
const type = elements.buttonActionType.value;
|
|
3045
|
+
let target = null;
|
|
3046
|
+
if (type === 'gotoScene') {
|
|
3047
|
+
target = elements.buttonTargetScene.value || '';
|
|
3048
|
+
} else if (type === 'toggleVisibility' || type === 'editInput') {
|
|
3049
|
+
target = elements.buttonTargetElement.value || '';
|
|
3050
|
+
} else if (type === 'gotoFrame') {
|
|
3051
|
+
const raw = Number(elements.buttonTargetFrame.value);
|
|
3052
|
+
target = Number.isInteger(raw) ? raw : null;
|
|
3053
|
+
}
|
|
3054
|
+
const action = type === 'script' ? { ...inspectorTrigger(), type, script: element.buttonAction.script }
|
|
3055
|
+
: { ...inspectorTrigger(), type, target };
|
|
3056
|
+
if (['gotoScene', 'gotoFrame'].includes(type) && elements.jumpPlay.checked) action.play = true;
|
|
3057
|
+
if (type === 'editInput') {
|
|
3058
|
+
action.operation = elements.inputOperation.value;
|
|
3059
|
+
if (action.operation === 'insert') action.value = elements.insertValue.value;
|
|
3060
|
+
}
|
|
3061
|
+
element.buttonAction = action;
|
|
3062
|
+
renderAll();
|
|
3063
|
+
}
|
|
3064
|
+
|
|
3065
|
+
document.querySelector('#add-scene').addEventListener('click', addScene);
|
|
3066
|
+
elements.addLayer.addEventListener('click', () => {
|
|
3067
|
+
const scene = activeScene();
|
|
3068
|
+
if (!scene || isInteractivePreview()) return;
|
|
3069
|
+
const layer = addLayerToScene(scene, makeId('layer'));
|
|
3070
|
+
selectedLayerId = layer.id;
|
|
3071
|
+
selectedElementIds = [];
|
|
3072
|
+
pendingLayerDeleteId = null;
|
|
3073
|
+
renderAll();
|
|
3074
|
+
showStatus(`${layer.name} added`);
|
|
3075
|
+
});
|
|
3076
|
+
elements.layerDeleteMove.addEventListener('click', () => {
|
|
3077
|
+
const scene = activeScene();
|
|
3078
|
+
if (!scene || !pendingLayerDeleteId) return;
|
|
3079
|
+
try {
|
|
3080
|
+
const targetId = elements.layerDeleteTarget.value;
|
|
3081
|
+
removeSceneLayer(scene, pendingLayerDeleteId, { moveToLayerId: targetId });
|
|
3082
|
+
if (selectedLayerId === pendingLayerDeleteId) selectedLayerId = targetId;
|
|
3083
|
+
pendingLayerDeleteId = null;
|
|
3084
|
+
renderAll();
|
|
3085
|
+
elements.layerList.querySelector('.is-active .layer-select-btn')?.focus();
|
|
3086
|
+
showStatus('Elements moved and layer deleted');
|
|
3087
|
+
} catch (error) {
|
|
3088
|
+
showStatus(error.message, true);
|
|
3089
|
+
}
|
|
3090
|
+
});
|
|
3091
|
+
elements.layerDeleteAll.addEventListener('click', () => {
|
|
3092
|
+
const scene = activeScene();
|
|
3093
|
+
if (!scene || !pendingLayerDeleteId) return;
|
|
3094
|
+
try {
|
|
3095
|
+
const deletedId = pendingLayerDeleteId;
|
|
3096
|
+
const removed = scene.elements.filter(item => item.layerId === deletedId);
|
|
3097
|
+
removeSceneLayer(scene, deletedId, 'delete');
|
|
3098
|
+
selectedElementIds = selectedMembers(scene).map(item => item.id);
|
|
3099
|
+
if (selectedLayerId === deletedId) {
|
|
3100
|
+
selectedLayerId = orderedSceneLayers(scene).at(-1)?.id ?? null;
|
|
3101
|
+
}
|
|
3102
|
+
pendingLayerDeleteId = null;
|
|
3103
|
+
renderAll();
|
|
3104
|
+
elements.layerList.querySelector('.is-active .layer-select-btn')?.focus();
|
|
3105
|
+
reportObjectEdit('Layer and its elements deleted', removed);
|
|
3106
|
+
} catch (error) {
|
|
3107
|
+
showStatus(error.message, true);
|
|
3108
|
+
}
|
|
3109
|
+
});
|
|
3110
|
+
elements.layerDeleteCancel.addEventListener('click', () => {
|
|
3111
|
+
const row = [...elements.layerList.children].find(entry => entry.dataset.id === pendingLayerDeleteId);
|
|
3112
|
+
pendingLayerDeleteId = null;
|
|
3113
|
+
renderLayerDeletePrompt(activeScene());
|
|
3114
|
+
row?.querySelector('.layer-select-btn')?.focus();
|
|
3115
|
+
});
|
|
3116
|
+
document.querySelector('#bitmap-fit').addEventListener('change', event => {
|
|
3117
|
+
const item = selectedElement();
|
|
3118
|
+
if (item?.type !== 'bitmap' || event.target.disabled) return;
|
|
3119
|
+
item.fit = event.target.value;
|
|
3120
|
+
// A chosen fit replaces an imported source rectangle (the object then shows the whole image).
|
|
3121
|
+
delete item.crop;
|
|
3122
|
+
renderAll();
|
|
3123
|
+
});
|
|
3124
|
+
document.querySelector('#bitmap-crop').addEventListener('change', event => {
|
|
3125
|
+
const item = selectedElement(), field = event.target;
|
|
3126
|
+
if (item?.type !== 'bitmap' || item.fit !== 'cover' || field.disabled) return;
|
|
3127
|
+
if (Number.isFinite(field.valueAsNumber) && field.validity.valid) item[field.id === 'bitmap-crop-x' ? 'cropX' : 'cropY'] = field.valueAsNumber;
|
|
3128
|
+
else showStatus('Choose a crop position between 0 and 100 percent', true);
|
|
3129
|
+
renderAll();
|
|
3130
|
+
});
|
|
3131
|
+
elements.maskSource.addEventListener('change', () => {
|
|
3132
|
+
const element = selectedElement();
|
|
3133
|
+
const scene = activeScene();
|
|
3134
|
+
if (!element || isInteractivePreview() || isElementLocked(scene, element) || elements.maskSource.disabled) return;
|
|
3135
|
+
const source = elements.maskSource.value;
|
|
3136
|
+
if (!source) delete element.maskId;
|
|
3137
|
+
else if (maskCandidates(scene, element).some(item => item.id === source)) element.maskId = source;
|
|
3138
|
+
renderAll();
|
|
3139
|
+
});
|
|
3140
|
+
elements.elementLayer.addEventListener('change', () => {
|
|
3141
|
+
const scene = activeScene();
|
|
3142
|
+
const element = selectedElement();
|
|
3143
|
+
if (!scene || !element || isInteractivePreview() || isElementLocked(scene, element)) return;
|
|
3144
|
+
try {
|
|
3145
|
+
moveElementToLayer(scene, element.id, elements.elementLayer.value);
|
|
3146
|
+
selectedLayerId = element.layerId;
|
|
3147
|
+
renderAll();
|
|
3148
|
+
showStatus(`Moved to ${findElementLayer(scene, element)?.name ?? 'layer'}`);
|
|
3149
|
+
} catch (error) {
|
|
3150
|
+
showStatus(error.message, true);
|
|
3151
|
+
renderAll();
|
|
3152
|
+
}
|
|
3153
|
+
});
|
|
3154
|
+
elements.importProject.addEventListener('click', () => openProjectIoDialog('import'));
|
|
3155
|
+
document.querySelector('#browse-examples').addEventListener('click', () => openProjectIoDialog('examples'));
|
|
3156
|
+
elements.exportProject.addEventListener('click', () => openProjectIoDialog('export'));
|
|
3157
|
+
elements.projectIoClose.addEventListener('click', closeProjectIoDialog);
|
|
3158
|
+
elements.projectIoCancel.addEventListener('click', closeProjectIoDialog);
|
|
3159
|
+
elements.projectIoCopy.addEventListener('click', copyExportedProject);
|
|
3160
|
+
elements.projectIoForm.addEventListener('input', () => sampleRequest?.abort());
|
|
3161
|
+
elements.projectIoDialog.addEventListener('click', event => {
|
|
3162
|
+
if (event.target === elements.projectIoDialog) closeProjectIoDialog();
|
|
3163
|
+
});
|
|
3164
|
+
elements.projectIoExamples.addEventListener('click', async event => {
|
|
3165
|
+
const button = event.target.closest('[data-example]');
|
|
3166
|
+
if (!button) return;
|
|
3167
|
+
sampleRequest?.abort();
|
|
3168
|
+
const request = new AbortController();
|
|
3169
|
+
sampleRequest = request;
|
|
3170
|
+
try {
|
|
3171
|
+
const response = await fetch(`./examples/${button.dataset.example}`, { signal: request.signal });
|
|
3172
|
+
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
|
3173
|
+
const json = await response.text();
|
|
3174
|
+
if (request.signal.aborted || !elements.projectIoDialog.open) return;
|
|
3175
|
+
elements.projectIoTextarea.value = json;
|
|
3176
|
+
elements.projectIoError.hidden = true;
|
|
3177
|
+
elements.projectIoError.textContent = '';
|
|
3178
|
+
if (elements.projectIoDialog.dataset.mode === 'examples') importProjectFromDialog(button.textContent.trim());
|
|
3179
|
+
} catch (error) {
|
|
3180
|
+
if (request.signal.aborted || !elements.projectIoDialog.open) return;
|
|
3181
|
+
elements.projectIoError.textContent = `Could not load sample: ${error.message}`;
|
|
3182
|
+
elements.projectIoError.hidden = false;
|
|
3183
|
+
}
|
|
3184
|
+
});
|
|
3185
|
+
// An image or sound chosen or dropped in Import joins the open project's library, as Upload files does.
|
|
3186
|
+
elements.projectIoDialog.addEventListener('import-media-file', ({ detail: file }) => {
|
|
3187
|
+
closeProjectIoDialog();
|
|
3188
|
+
mediaLibrary.importFiles([file]);
|
|
3189
|
+
});
|
|
3190
|
+
|
|
3191
|
+
// A SWF chosen or dropped in Import: converted on the server into a new project, as Open SWF does.
|
|
3192
|
+
elements.projectIoDialog.addEventListener('import-swf-file', async ({ detail: file }) => {
|
|
3193
|
+
const version = ++mediaImportVersion;
|
|
3194
|
+
const notice = document.querySelector('#project-io-notice');
|
|
3195
|
+
elements.projectIoError.hidden = true;
|
|
3196
|
+
if (!confirmDiscard()) return;
|
|
3197
|
+
notice.textContent = `Converting ${file.name}…`;
|
|
3198
|
+
elements.projectIoSubmit.disabled = true;
|
|
3199
|
+
try {
|
|
3200
|
+
await projectsUi.openSwfFile(file);
|
|
3201
|
+
if (elements.projectIoDialog.open) closeProjectIoDialog();
|
|
3202
|
+
} catch (error) {
|
|
3203
|
+
if (version !== mediaImportVersion || !elements.projectIoDialog.open) return;
|
|
3204
|
+
notice.textContent = '';
|
|
3205
|
+
elements.projectIoError.textContent = `Could not open ${file.name}: ${error.message}`;
|
|
3206
|
+
elements.projectIoError.hidden = false;
|
|
3207
|
+
} finally {
|
|
3208
|
+
elements.projectIoSubmit.disabled = false;
|
|
3209
|
+
}
|
|
3210
|
+
});
|
|
3211
|
+
|
|
3212
|
+
elements.projectIoForm.addEventListener('submit', event => {
|
|
3213
|
+
event.preventDefault();
|
|
3214
|
+
if (elements.projectIoDialog.dataset.mode === 'examples') return;
|
|
3215
|
+
if (elements.projectIoTextarea.readOnly) {
|
|
3216
|
+
closeProjectIoDialog();
|
|
3217
|
+
return;
|
|
3218
|
+
}
|
|
3219
|
+
importProjectFromDialog();
|
|
3220
|
+
});
|
|
3221
|
+
elements.deleteScene.addEventListener('click', deleteScene);
|
|
3222
|
+
elements.deleteElement.addEventListener('click', removeSelectedElement);
|
|
3223
|
+
elements.groupObjects.addEventListener('click', () => arrangeObjects('group'));
|
|
3224
|
+
elements.ungroupObjects.addEventListener('click', () => arrangeObjects('ungroup'));
|
|
3225
|
+
elements.raiseObjects.addEventListener('click', () => arrangeObjects('forward'));
|
|
3226
|
+
elements.lowerObjects.addEventListener('click', () => arrangeObjects('backward'));
|
|
3227
|
+
elements.undo.addEventListener('click', () => moveHistory(-1));
|
|
3228
|
+
elements.redo.addEventListener('click', () => moveHistory(1));
|
|
3229
|
+
elements.addKeyframe.addEventListener('click', () => editFrames('key'));
|
|
3230
|
+
elements.frameEdit.addEventListener('change', () => {
|
|
3231
|
+
const operation = elements.frameEdit.value;
|
|
3232
|
+
elements.frameEdit.value = '';
|
|
3233
|
+
if (operation) editFrames(operation);
|
|
3234
|
+
});
|
|
3235
|
+
elements.previewButton.addEventListener('click', togglePreviewMode);
|
|
3236
|
+
elements.playButton.addEventListener('click', startPlayback);
|
|
3237
|
+
elements.stopButton.addEventListener('click', () => stopPlayback(true));
|
|
3238
|
+
elements.previousFrame.addEventListener('click', () => scrubFrame(playhead - 1));
|
|
3239
|
+
elements.nextFrame.addEventListener('click', () => scrubFrame(playhead + 1));
|
|
3240
|
+
elements.playhead.addEventListener('input', event => scrubFrame(Number(event.currentTarget.value)));
|
|
3241
|
+
elements.tweenEasing.addEventListener('change', updateTweenEasing);
|
|
3242
|
+
elements.toolButtons.forEach(button => {
|
|
3243
|
+
button.addEventListener('click', () => {
|
|
3244
|
+
const nextTool = button.dataset.tool;
|
|
3245
|
+
if (editingTextElementId) closeTextEditor(true);
|
|
3246
|
+
if (pendingPath && nextTool !== activeTool) {
|
|
3247
|
+
const minimum = pendingPath.kind === 'polygon' ? 3 : 2;
|
|
3248
|
+
if (pendingPath.points.length < minimum) {
|
|
3249
|
+
showStatus(`Add ${minimum - pendingPath.points.length} more point${minimum - pendingPath.points.length === 1 ? '' : 's'} or press Escape to cancel`, true);
|
|
3250
|
+
return;
|
|
3251
|
+
}
|
|
3252
|
+
finishPendingPath(pendingPath.kind === 'polygon');
|
|
3253
|
+
}
|
|
3254
|
+
activeTool = nextTool;
|
|
3255
|
+
const menu = button.closest('.more-tools');
|
|
3256
|
+
if (menu) { menu.querySelector('summary').focus(); menu.open = false; }
|
|
3257
|
+
showToolHint(activeTool);
|
|
3258
|
+
renderAll();
|
|
3259
|
+
});
|
|
3260
|
+
});
|
|
3261
|
+
|
|
3262
|
+
document.querySelector('#control-actions').addEventListener('click', () => {
|
|
3263
|
+
const source = selectedElement();
|
|
3264
|
+
if (source?.type === 'control') openEventEditor(activeScene(), playhead, null, source);
|
|
3265
|
+
});
|
|
3266
|
+
document.querySelector('#control-variable').addEventListener('change', event => {
|
|
3267
|
+
const source = selectedElement();
|
|
3268
|
+
if (source?.type !== 'control' || isInteractivePreview() || isElementLocked(activeScene(), source)) return;
|
|
3269
|
+
const variable = event.target.value.trim();
|
|
3270
|
+
if (variable) source.variable = variable;
|
|
3271
|
+
else delete source.variable;
|
|
3272
|
+
renderAll();
|
|
3273
|
+
});
|
|
3274
|
+
document.querySelector('#preview-surface').addEventListener('swoof:control', event => {
|
|
3275
|
+
if (!isInteractivePreview() || sceneTransition.active) return;
|
|
3276
|
+
const { entry, type } = event.detail;
|
|
3277
|
+
const handler = entry.timeline.events?.find(item => item.source === entry.element.id && item.trigger === type);
|
|
3278
|
+
if (!handler) return;
|
|
3279
|
+
for (const action of handler.actions) executeFrameAction(action, entry);
|
|
3280
|
+
renderAll();
|
|
3281
|
+
dispatchFrameEvents();
|
|
3282
|
+
});
|
|
3283
|
+
|
|
3284
|
+
elements.instanceSettings.addEventListener('change', event => {
|
|
3285
|
+
const element = selectedElement();
|
|
3286
|
+
if (element?.type !== 'symbol' || isInteractivePreview() || isElementLocked(activeScene(), element)) return;
|
|
3287
|
+
const field = event.target;
|
|
3288
|
+
if (field === elements.instanceMode) {
|
|
3289
|
+
if (field.value) element.symbolMode = field.value;
|
|
3290
|
+
else delete element.symbolMode;
|
|
3291
|
+
} else if (field === elements.instanceFirst) {
|
|
3292
|
+
if (!field.validity.valid) showStatus(`Choose a first frame between 1 and ${field.max}`, true);
|
|
3293
|
+
else if (field.value) element.firstFrame = field.valueAsNumber;
|
|
3294
|
+
else delete element.firstFrame;
|
|
3295
|
+
}
|
|
3296
|
+
renderAll();
|
|
3297
|
+
});
|
|
3298
|
+
elements.elementForm.addEventListener('change', event => {
|
|
3299
|
+
if (event.target.dataset.shapeProperty) {
|
|
3300
|
+
const input = event.target, element = selectedElement();
|
|
3301
|
+
if (element && !input.disabled && input.validity.valid && Number.isFinite(input.valueAsNumber)) {
|
|
3302
|
+
updatePoseProperty(element, input.dataset.shapeProperty, input.valueAsNumber);
|
|
3303
|
+
}
|
|
3304
|
+
renderAll();
|
|
3305
|
+
return;
|
|
3306
|
+
}
|
|
3307
|
+
|
|
3308
|
+
if (
|
|
3309
|
+
(event.target instanceof HTMLInputElement ||
|
|
3310
|
+
event.target instanceof HTMLSelectElement ||
|
|
3311
|
+
event.target instanceof HTMLTextAreaElement) &&
|
|
3312
|
+
event.target.dataset.property
|
|
3313
|
+
) setPoseFromInput(event.target);
|
|
3314
|
+
else if (event.target.dataset?.elementStyle) setElementStyleFromInput(event.target);
|
|
3315
|
+
});
|
|
3316
|
+
|
|
3317
|
+
// Line ends, corners, dashes, the fill rule and italic belong to the object, not to a keyframe.
|
|
3318
|
+
function setElementStyleFromInput(input) {
|
|
3319
|
+
const scene = activeScene();
|
|
3320
|
+
const element = selectedElement();
|
|
3321
|
+
const property = input.dataset.elementStyle;
|
|
3322
|
+
if (!scene || !element) return;
|
|
3323
|
+
if (isElementLocked(scene, element)) {
|
|
3324
|
+
showStatus('Unlock the layer before editing this element', true);
|
|
3325
|
+
renderAll();
|
|
3326
|
+
return;
|
|
3327
|
+
}
|
|
3328
|
+
let value = input.type === 'checkbox' ? input.checked : input.value;
|
|
3329
|
+
if (property === 'strokeDash') {
|
|
3330
|
+
const lengths = value.trim() ? value.trim().split(/[\s,]+/).map(Number) : [];
|
|
3331
|
+
if (lengths.some(length => !Number.isFinite(length) || length < 0 || length > 10000) || lengths.length > 64) {
|
|
3332
|
+
showStatus('Dashes are lengths from 0 to 10000, such as 6 3', true);
|
|
3333
|
+
renderAll();
|
|
3334
|
+
return;
|
|
3335
|
+
}
|
|
3336
|
+
value = lengths.some(length => length > 0) ? lengths : undefined;
|
|
3337
|
+
}
|
|
3338
|
+
const defaults = { lineCap: 'round', lineJoin: 'round', fillRule: '', italic: false };
|
|
3339
|
+
if (value === undefined || value === defaults[property]) delete element[property];
|
|
3340
|
+
else element[property] = value;
|
|
3341
|
+
if (property === 'strokeDash' && !element.strokeDash) delete element.strokeDashOffset;
|
|
3342
|
+
reportObjectEdit(`Changed ${input.closest('label')?.firstChild?.textContent.trim().toLowerCase() || property}`, [element]);
|
|
3343
|
+
renderAll();
|
|
3344
|
+
}
|
|
3345
|
+
elements.inputText.addEventListener('change', () => {
|
|
3346
|
+
const element = selectedElement();
|
|
3347
|
+
if (element?.type !== 'text' || element.buttonAction) return;
|
|
3348
|
+
element.inputText = elements.inputText.checked;
|
|
3349
|
+
if (element.field?.editable !== undefined) element.field.editable = element.inputText;
|
|
3350
|
+
renderAll();
|
|
3351
|
+
});
|
|
3352
|
+
document.querySelector('#text-field-settings').addEventListener('change', event => {
|
|
3353
|
+
const input = event.target;
|
|
3354
|
+
const element = selectedElement();
|
|
3355
|
+
if (element?.type !== 'text' || !input.dataset.textField || input.disabled) return;
|
|
3356
|
+
if (!input.validity.valid || input.type === 'number' && input.value === '') { renderAll(); return; }
|
|
3357
|
+
const name = input.dataset.textField;
|
|
3358
|
+
const field = element.field ??= {};
|
|
3359
|
+
if (name === 'variable' && !input.value.trim()) delete field.variable;
|
|
3360
|
+
else if (input.type === 'checkbox') field[name] = input.checked;
|
|
3361
|
+
else field[name] = input.type === 'number' ? input.valueAsNumber : input.value.trim();
|
|
3362
|
+
renderAll();
|
|
3363
|
+
});
|
|
3364
|
+
elements.elementIsButton.addEventListener('change', () => {
|
|
3365
|
+
const element = selectedElement();
|
|
3366
|
+
const scene = activeScene();
|
|
3367
|
+
if (!element || !scene) return;
|
|
3368
|
+
if (elements.elementIsButton.checked) {
|
|
3369
|
+
const otherScene = project.scenes.find(item => item.id !== scene.id) ?? scene;
|
|
3370
|
+
element.buttonAction = { trigger: 'click', type: 'gotoScene', target: otherScene.id };
|
|
3371
|
+
} else {
|
|
3372
|
+
element.buttonAction = null;
|
|
3373
|
+
}
|
|
3374
|
+
renderAll();
|
|
3375
|
+
});
|
|
3376
|
+
async function editButtonScript(element) {
|
|
3377
|
+
const id = element.buttonAction?.type === 'script' ? element.buttonAction.script : null;
|
|
3378
|
+
const trigger = inspectorTrigger();
|
|
3379
|
+
const drafts = new Map();
|
|
3380
|
+
const changed = await editAttachedScript(scriptEditorContext, drafts, id, `${element.name} ${trigger.trigger}`);
|
|
3381
|
+
if (changed) {
|
|
3382
|
+
applyScriptDrafts(project, drafts, new Set([changed]));
|
|
3383
|
+
element.buttonAction = { ...trigger, type: 'script', script: changed };
|
|
3384
|
+
}
|
|
3385
|
+
renderAll();
|
|
3386
|
+
}
|
|
3387
|
+
document.querySelector('#button-edit-script').onclick = () => editButtonScript(selectedElement());
|
|
3388
|
+
document.querySelector('#instance-scripts').onclick = () => openHandlers(selectedElement(), 'clip');
|
|
3389
|
+
elements.buttonActionType.addEventListener('change', () => {
|
|
3390
|
+
const element = selectedElement();
|
|
3391
|
+
const scene = activeScene();
|
|
3392
|
+
if (!element || !scene) return;
|
|
3393
|
+
const type = elements.buttonActionType.value;
|
|
3394
|
+
if (type === 'script') { editButtonScript(element); return; }
|
|
3395
|
+
let target = null;
|
|
3396
|
+
if (type === 'gotoScene') target = (project.scenes.find(item => item.id !== scene.id) ?? scene).id;
|
|
3397
|
+
else if (type === 'gotoFrame') target = 1;
|
|
3398
|
+
else if (type === 'toggleVisibility') target = scene.elements.find(item => item.id !== element.id)?.id ?? '';
|
|
3399
|
+
else if (type === 'editInput') target = scene.elements.find(item => item.inputText)?.id ?? '';
|
|
3400
|
+
element.buttonAction = { ...inspectorTrigger(), type, target };
|
|
3401
|
+
if (type === 'editInput') Object.assign(element.buttonAction, { operation: 'insert', value: '' });
|
|
3402
|
+
renderAll();
|
|
3403
|
+
});
|
|
3404
|
+
elements.jumpPlay.addEventListener('change', updateElementButtonFromInspector);
|
|
3405
|
+
elements.inputOperation.addEventListener('change', updateElementButtonFromInspector);
|
|
3406
|
+
for (const input of [elements.buttonTrigger, elements.buttonKey, elements.buttonSwipe]) {
|
|
3407
|
+
input.addEventListener('change', updateElementButtonFromInspector);
|
|
3408
|
+
}
|
|
3409
|
+
elements.insertValue.addEventListener('change', updateElementButtonFromInspector);
|
|
3410
|
+
elements.buttonTargetScene.addEventListener('change', updateElementButtonFromInspector);
|
|
3411
|
+
elements.buttonTargetFrame.addEventListener('change', updateElementButtonFromInspector);
|
|
3412
|
+
elements.buttonTargetElement.addEventListener('change', updateElementButtonFromInspector);
|
|
3413
|
+
elements.elementForm.addEventListener('input', event => {
|
|
3414
|
+
if (event.target instanceof HTMLTextAreaElement && event.target.dataset.property === 'text') {
|
|
3415
|
+
setPoseFromInput(event.target);
|
|
3416
|
+
}
|
|
3417
|
+
});
|
|
3418
|
+
elements.elementForm.addEventListener('submit', event => event.preventDefault());
|
|
3419
|
+
elements.sceneName.addEventListener('change', event => updateSceneProperty(event.currentTarget));
|
|
3420
|
+
elements.sceneLoop.addEventListener('change', event => updateSceneProperty(event.currentTarget));
|
|
3421
|
+
elements.sceneDuration.addEventListener('change', event => updateSceneProperty(event.currentTarget));
|
|
3422
|
+
elements.sceneStartFrame.addEventListener('change', event => updateSceneProperty(event.currentTarget));
|
|
3423
|
+
for (const input of [elements.stageWidth, elements.stageHeight, elements.stageFps, elements.stageBackground]) {
|
|
3424
|
+
input.dataset.stageProperty = {
|
|
3425
|
+
'stage-width': 'width',
|
|
3426
|
+
'stage-height': 'height',
|
|
3427
|
+
'stage-fps': 'frameRate',
|
|
3428
|
+
'stage-background': 'background',
|
|
3429
|
+
}[input.id];
|
|
3430
|
+
input.addEventListener(input.type === 'color' ? 'input' : 'change', event => updateStageProperty(event.currentTarget));
|
|
3431
|
+
}
|
|
3432
|
+
function nudgeSelection(x, y) {
|
|
3433
|
+
const scene = activeScene();
|
|
3434
|
+
const members = selectedMembers(scene);
|
|
3435
|
+
if (!members.length || members.some(item => isElementLocked(scene, item))) return;
|
|
3436
|
+
const stage = workingStage();
|
|
3437
|
+
if (members.length === 1) {
|
|
3438
|
+
const element = members[0];
|
|
3439
|
+
if (!visibleAt(element, playhead) || findElementLayer(scene, element)?.visible === false) return;
|
|
3440
|
+
const pose = poseAt(element, playhead);
|
|
3441
|
+
if (Math.abs(pose.x + x) > 4 * stage.width || Math.abs(pose.y + y) > 4 * stage.height) return;
|
|
3442
|
+
if (x) updatePoseProperty(element, 'x', pose.x + x);
|
|
3443
|
+
if (y) updatePoseProperty(element, 'y', pose.y + y);
|
|
3444
|
+
} else {
|
|
3445
|
+
transformMembers(groupTransformSources(members), { x: 0, y: 0 }, { x, y }, 1, 0, stage);
|
|
3446
|
+
}
|
|
3447
|
+
renderAll();
|
|
3448
|
+
}
|
|
3449
|
+
|
|
3450
|
+
document.addEventListener('keydown', event => {
|
|
3451
|
+
if (event.defaultPrevented || event.isComposing || document.querySelector('dialog[open]')) return;
|
|
3452
|
+
const target = event.target;
|
|
3453
|
+
const typing = (target.matches('input, textarea, select') && target !== elements.playhead) || target.isContentEditable;
|
|
3454
|
+
if (event.key === 'Escape' && isInteractivePreview()) {
|
|
3455
|
+
event.preventDefault();
|
|
3456
|
+
leavePreview();
|
|
3457
|
+
return;
|
|
3458
|
+
}
|
|
3459
|
+
if (target.closest('[role="tablist"], [role="separator"]')) return;
|
|
3460
|
+
if (event.code === 'Space' && !typing && !target.closest('button, a, summary') &&
|
|
3461
|
+
!event.metaKey && !event.ctrlKey && !event.altKey && !dragState && !pendingPath) {
|
|
3462
|
+
event.preventDefault();
|
|
3463
|
+
if (!event.repeat) startPlayback();
|
|
3464
|
+
return;
|
|
3465
|
+
}
|
|
3466
|
+
if (isInteractivePreview() || dragState || event.altKey) return;
|
|
3467
|
+
if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 's' && !event.altKey) {
|
|
3468
|
+
event.preventDefault();
|
|
3469
|
+
if (!event.repeat) projectsUi.save();
|
|
3470
|
+
return;
|
|
3471
|
+
}
|
|
3472
|
+
if (event.metaKey || event.ctrlKey) {
|
|
3473
|
+
const editingValue = target instanceof HTMLTextAreaElement || target?.isContentEditable ||
|
|
3474
|
+
(target instanceof HTMLInputElement && ['text', 'number', 'search'].includes(target.type));
|
|
3475
|
+
const key = event.key.toLowerCase();
|
|
3476
|
+
if (!editingValue && key === 'g') {
|
|
3477
|
+
event.preventDefault();
|
|
3478
|
+
arrangeObjects(event.shiftKey ? 'ungroup' : 'group');
|
|
3479
|
+
}
|
|
3480
|
+
if (!editingValue && (key === 'z' || key === 'y')) {
|
|
3481
|
+
event.preventDefault();
|
|
3482
|
+
moveHistory(key === 'y' || event.shiftKey ? 1 : -1);
|
|
3483
|
+
}
|
|
3484
|
+
return;
|
|
3485
|
+
}
|
|
3486
|
+
if (typing) return;
|
|
3487
|
+
if (!pendingPath) {
|
|
3488
|
+
if (event.key === ',' || event.key === '.') {
|
|
3489
|
+
event.preventDefault();
|
|
3490
|
+
scrubFrame(playhead + (event.key === ',' ? -1 : 1));
|
|
3491
|
+
return;
|
|
3492
|
+
}
|
|
3493
|
+
if (event.key === 'F6' || event.key === 'F7') {
|
|
3494
|
+
event.preventDefault();
|
|
3495
|
+
if (!event.repeat) editFrames(event.key === 'F6' ? 'key' : 'blank');
|
|
3496
|
+
return;
|
|
3497
|
+
}
|
|
3498
|
+
const delta = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] }[event.key];
|
|
3499
|
+
if (delta && selectedElementIds.length && (target === document.body || target === elements.canvas)) {
|
|
3500
|
+
event.preventDefault();
|
|
3501
|
+
const step = event.shiftKey ? 10 : 1;
|
|
3502
|
+
nudgeSelection(delta[0] * step, delta[1] * step);
|
|
3503
|
+
return;
|
|
3504
|
+
}
|
|
3505
|
+
}
|
|
3506
|
+
if (event.key === 'Escape' && pendingPath) {
|
|
3507
|
+
event.preventDefault();
|
|
3508
|
+
cancelPendingPath();
|
|
3509
|
+
return;
|
|
3510
|
+
}
|
|
3511
|
+
if (event.key === 'Escape' && (activeTool !== 'select' || selectedElementIds.length)) {
|
|
3512
|
+
event.preventDefault();
|
|
3513
|
+
if (activeTool === 'select') selectedElementIds = [];
|
|
3514
|
+
activeTool = 'select';
|
|
3515
|
+
renderAll();
|
|
3516
|
+
return;
|
|
3517
|
+
}
|
|
3518
|
+
if (event.key === 'Enter' && activeTool === 'pen' && pendingPath) {
|
|
3519
|
+
event.preventDefault();
|
|
3520
|
+
finishPendingPath(false);
|
|
3521
|
+
return;
|
|
3522
|
+
}
|
|
3523
|
+
if (event.key === 'Delete' || event.key === 'Backspace') {
|
|
3524
|
+
if (selectedElementIds.length) {
|
|
3525
|
+
event.preventDefault();
|
|
3526
|
+
removeSelectedElement();
|
|
3527
|
+
}
|
|
3528
|
+
return;
|
|
3529
|
+
}
|
|
3530
|
+
if (pendingPath && event.key === 'Enter') {
|
|
3531
|
+
event.preventDefault();
|
|
3532
|
+
finishPendingPath(pendingPath.kind === 'polygon');
|
|
3533
|
+
return;
|
|
3534
|
+
}
|
|
3535
|
+
const tool = {
|
|
3536
|
+
v: 'select',
|
|
3537
|
+
s: 'scale',
|
|
3538
|
+
r: 'rotate',
|
|
3539
|
+
m: 'rectangle',
|
|
3540
|
+
o: 'ellipse',
|
|
3541
|
+
g: 'polygon',
|
|
3542
|
+
l: 'line',
|
|
3543
|
+
p: 'pen',
|
|
3544
|
+
t: 'text',
|
|
3545
|
+
}[event.key.toLowerCase()];
|
|
3546
|
+
if (tool && !event.repeat) {
|
|
3547
|
+
if (editingTextElementId) closeTextEditor(true);
|
|
3548
|
+
if (pendingPath && tool !== activeTool) {
|
|
3549
|
+
const minimum = pendingPath.kind === 'polygon' ? 3 : 2;
|
|
3550
|
+
if (pendingPath.points.length < minimum) {
|
|
3551
|
+
showStatus(`Add ${minimum - pendingPath.points.length} more point${minimum - pendingPath.points.length === 1 ? '' : 's'} or press Escape to cancel`, true);
|
|
3552
|
+
return;
|
|
3553
|
+
}
|
|
3554
|
+
finishPendingPath(pendingPath.kind === 'polygon');
|
|
3555
|
+
}
|
|
3556
|
+
activeTool = tool;
|
|
3557
|
+
showToolHint(activeTool);
|
|
3558
|
+
renderAll();
|
|
3559
|
+
}
|
|
3560
|
+
});
|
|
3561
|
+
|
|
3562
|
+
project.scenes.push(makeScene('Scene 1'));
|
|
3563
|
+
selectedSceneId = project.scenes[0].id;
|
|
3564
|
+
selectedLayerId = project.scenes[0].layers[0].id;
|
|
3565
|
+
projectSession.detach(JSON.parse(serializeProject(project, 0)));
|
|
3566
|
+
renderAll();
|
|
3567
|
+
|
|
3568
|
+
window.addEventListener('beforeunload', event => {
|
|
3569
|
+
projectSession.check();
|
|
3570
|
+
if (!projectSession.dirty) return;
|
|
3571
|
+
projectSession.flush({ keepalive: true });
|
|
3572
|
+
event.preventDefault();
|
|
3573
|
+
event.returnValue = '';
|
|
3574
|
+
});
|
|
3575
|
+
window.addEventListener('pagehide', () => projectSession.flush({ keepalive: true }));
|
|
3576
|
+
|
|
3577
|
+
document.addEventListener('visibilitychange', renderCanvas);
|
|
3578
|
+
|
|
3579
|
+
new ResizeObserver(() => {
|
|
3580
|
+
renderCanvas();
|
|
3581
|
+
updateTextEditorPosition();
|
|
3582
|
+
}).observe(elements.canvas);
|