@antheo/morph 0.0.0-stage → 0.3.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/LICENSE +21 -0
- package/README.md +266 -2
- package/SKILL.md +61 -0
- package/dist/ai/cli-provider.d.ts +80 -0
- package/dist/ai/cli-provider.js +250 -0
- package/dist/ai/gate.d.ts +39 -0
- package/dist/ai/gate.js +124 -0
- package/dist/ai/provider.d.ts +36 -0
- package/dist/ai/provider.js +168 -0
- package/dist/ai/repair.d.ts +90 -0
- package/dist/ai/repair.js +172 -0
- package/dist/analyzer/deps.d.ts +30 -0
- package/dist/analyzer/deps.js +265 -0
- package/dist/analyzer/manifest.d.ts +5 -0
- package/dist/analyzer/manifest.js +119 -0
- package/dist/analyzer/parse.d.ts +21 -0
- package/dist/analyzer/parse.js +29 -0
- package/dist/batch-worker.d.ts +16 -0
- package/dist/batch-worker.js +10 -0
- package/dist/batch.d.ts +26 -0
- package/dist/batch.js +227 -0
- package/dist/bridge/index.d.ts +26 -0
- package/dist/bridge/index.js +138 -0
- package/dist/bridge/props.d.ts +56 -0
- package/dist/bridge/props.js +191 -0
- package/dist/bridge/wrappers.d.ts +24 -0
- package/dist/bridge/wrappers.js +276 -0
- package/dist/cli/format.d.ts +7 -0
- package/dist/cli/format.js +30 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +492 -0
- package/dist/fonts/carry.d.ts +34 -0
- package/dist/fonts/carry.js +113 -0
- package/dist/fonts/fallback.d.ts +11 -0
- package/dist/fonts/fallback.js +21 -0
- package/dist/fonts/google.d.ts +65 -0
- package/dist/fonts/google.js +343 -0
- package/dist/fonts/index.d.ts +27 -0
- package/dist/fonts/index.js +48 -0
- package/dist/fonts/local.d.ts +46 -0
- package/dist/fonts/local.js +150 -0
- package/dist/fonts/sfnt.d.ts +19 -0
- package/dist/fonts/sfnt.js +174 -0
- package/dist/fonts/shim.d.ts +14 -0
- package/dist/fonts/shim.js +96 -0
- package/dist/gate.d.ts +105 -0
- package/dist/gate.js +157 -0
- package/dist/index.d.ts +55 -0
- package/dist/index.js +74 -0
- package/dist/ir/annotate.d.ts +16 -0
- package/dist/ir/annotate.js +145 -0
- package/dist/ir/as-child.d.ts +18 -0
- package/dist/ir/as-child.js +239 -0
- package/dist/ir/compounds.d.ts +27 -0
- package/dist/ir/compounds.js +183 -0
- package/dist/ir/contexts.d.ts +26 -0
- package/dist/ir/contexts.js +185 -0
- package/dist/ir/dom.d.ts +11 -0
- package/dist/ir/dom.js +60 -0
- package/dist/ir/effect-returns.d.ts +10 -0
- package/dist/ir/effect-returns.js +25 -0
- package/dist/ir/extract-ui-types.d.ts +33 -0
- package/dist/ir/extract-ui-types.js +224 -0
- package/dist/ir/extract-ui.d.ts +34 -0
- package/dist/ir/extract-ui.js +567 -0
- package/dist/ir/falsy.d.ts +13 -0
- package/dist/ir/falsy.js +66 -0
- package/dist/ir/forward-refs.d.ts +11 -0
- package/dist/ir/forward-refs.js +155 -0
- package/dist/ir/fragment-source.d.ts +4 -0
- package/dist/ir/fragment-source.js +13 -0
- package/dist/ir/fragments.d.ts +32 -0
- package/dist/ir/fragments.js +192 -0
- package/dist/ir/helper-snippets.d.ts +30 -0
- package/dist/ir/helper-snippets.js +550 -0
- package/dist/ir/latest-refs.d.ts +11 -0
- package/dist/ir/latest-refs.js +187 -0
- package/dist/ir/live-args.d.ts +26 -0
- package/dist/ir/live-args.js +335 -0
- package/dist/ir/lower.d.ts +83 -0
- package/dist/ir/lower.js +6016 -0
- package/dist/ir/markup-values.d.ts +16 -0
- package/dist/ir/markup-values.js +188 -0
- package/dist/ir/model.d.ts +605 -0
- package/dist/ir/model.js +1 -0
- package/dist/ir/oracle.d.ts +91 -0
- package/dist/ir/oracle.js +610 -0
- package/dist/ir/radix.d.ts +122 -0
- package/dist/ir/radix.js +344 -0
- package/dist/ir/rename.d.ts +15 -0
- package/dist/ir/rename.js +151 -0
- package/dist/ir/render-props.d.ts +31 -0
- package/dist/ir/render-props.js +67 -0
- package/dist/ir/rewrite.d.ts +44 -0
- package/dist/ir/rewrite.js +381 -0
- package/dist/ir/running-index.d.ts +11 -0
- package/dist/ir/running-index.js +217 -0
- package/dist/ir/snapshots.d.ts +12 -0
- package/dist/ir/snapshots.js +140 -0
- package/dist/ir/style.d.ts +19 -0
- package/dist/ir/style.js +76 -0
- package/dist/ir/types.d.ts +42 -0
- package/dist/ir/types.js +271 -0
- package/dist/ir/walk.d.ts +11 -0
- package/dist/ir/walk.js +18 -0
- package/dist/mcp/server.d.ts +81 -0
- package/dist/mcp/server.js +518 -0
- package/dist/pipeline.d.ts +26 -0
- package/dist/pipeline.js +750 -0
- package/dist/registry/add.d.ts +91 -0
- package/dist/registry/add.js +273 -0
- package/dist/registry/fetch.d.ts +40 -0
- package/dist/registry/fetch.js +186 -0
- package/dist/registry/ip.d.ts +18 -0
- package/dist/registry/ip.js +153 -0
- package/dist/registry/item.d.ts +39 -0
- package/dist/registry/item.js +131 -0
- package/dist/registry/load.d.ts +35 -0
- package/dist/registry/load.js +106 -0
- package/dist/registry/paths.d.ts +8 -0
- package/dist/registry/paths.js +43 -0
- package/dist/registry/publish.d.ts +119 -0
- package/dist/registry/publish.js +439 -0
- package/dist/targets/angular/bank/bank.d.ts +39 -0
- package/dist/targets/angular/bank/bank.js +61 -0
- package/dist/targets/angular/bank/helpers.d.ts +64 -0
- package/dist/targets/angular/bank/helpers.js +246 -0
- package/dist/targets/angular/bank/kept.d.ts +98 -0
- package/dist/targets/angular/bank/kept.js +791 -0
- package/dist/targets/angular/bank/plan-helpers.d.ts +17 -0
- package/dist/targets/angular/bank/plan-helpers.js +286 -0
- package/dist/targets/angular/bank/plan.d.ts +22 -0
- package/dist/targets/angular/bank/plan.js +152 -0
- package/dist/targets/angular/bank/receivers.d.ts +66 -0
- package/dist/targets/angular/bank/receivers.js +293 -0
- package/dist/targets/angular/bank/runtime.d.ts +14 -0
- package/dist/targets/angular/bank/runtime.js +152 -0
- package/dist/targets/angular/controlled.d.ts +7 -0
- package/dist/targets/angular/controlled.js +37 -0
- package/dist/targets/angular/dynamic-tags.d.ts +34 -0
- package/dist/targets/angular/dynamic-tags.js +192 -0
- package/dist/targets/angular/emit.d.ts +41 -0
- package/dist/targets/angular/emit.js +5970 -0
- package/dist/targets/angular/exports.d.ts +48 -0
- package/dist/targets/angular/exports.js +243 -0
- package/dist/targets/angular/helpers.d.ts +15 -0
- package/dist/targets/angular/helpers.js +33 -0
- package/dist/targets/angular/host-boundary.d.ts +5 -0
- package/dist/targets/angular/host-boundary.js +166 -0
- package/dist/targets/angular/host-form.d.ts +150 -0
- package/dist/targets/angular/host-form.js +727 -0
- package/dist/targets/angular/markup-values.d.ts +58 -0
- package/dist/targets/angular/markup-values.js +661 -0
- package/dist/targets/angular/motion-directive.d.ts +12 -0
- package/dist/targets/angular/motion-directive.js +257 -0
- package/dist/targets/angular/motion-hooks.d.ts +73 -0
- package/dist/targets/angular/motion-hooks.js +293 -0
- package/dist/targets/angular/motion-layout.d.ts +14 -0
- package/dist/targets/angular/motion-layout.js +74 -0
- package/dist/targets/angular/motion-templates.d.ts +10 -0
- package/dist/targets/angular/motion-templates.js +65 -0
- package/dist/targets/angular/motion.d.ts +57 -0
- package/dist/targets/angular/motion.js +202 -0
- package/dist/targets/angular/narrowing.d.ts +24 -0
- package/dist/targets/angular/narrowing.js +205 -0
- package/dist/targets/angular/ngc.d.ts +23 -0
- package/dist/targets/angular/ngc.js +134 -0
- package/dist/targets/angular/passed-handle.d.ts +39 -0
- package/dist/targets/angular/passed-handle.js +154 -0
- package/dist/targets/angular/projected.d.ts +9 -0
- package/dist/targets/angular/projected.js +63 -0
- package/dist/targets/angular/radix/cores/alert-dialog.d.ts +13 -0
- package/dist/targets/angular/radix/cores/alert-dialog.js +388 -0
- package/dist/targets/angular/radix/cores/index.d.ts +17 -0
- package/dist/targets/angular/radix/cores/index.js +50 -0
- package/dist/targets/angular/radix/cores/slider.d.ts +8 -0
- package/dist/targets/angular/radix/cores/slider.js +202 -0
- package/dist/targets/angular/radix/index.d.ts +21 -0
- package/dist/targets/angular/radix/index.js +35 -0
- package/dist/targets/angular/radix/packages.d.ts +3 -0
- package/dist/targets/angular/radix/packages.js +558 -0
- package/dist/targets/angular/radix/part.d.ts +236 -0
- package/dist/targets/angular/radix/part.js +71 -0
- package/dist/targets/angular/radix/prepare.d.ts +66 -0
- package/dist/targets/angular/radix/prepare.js +548 -0
- package/dist/targets/angular/radix/template.d.ts +43 -0
- package/dist/targets/angular/radix/template.js +172 -0
- package/dist/targets/angular/refs.d.ts +68 -0
- package/dist/targets/angular/refs.js +443 -0
- package/dist/targets/angular/slots.d.ts +22 -0
- package/dist/targets/angular/slots.js +60 -0
- package/dist/targets/angular/source-types.d.ts +10 -0
- package/dist/targets/angular/source-types.js +45 -0
- package/dist/targets/angular/spread-forward.d.ts +24 -0
- package/dist/targets/angular/spread-forward.js +72 -0
- package/dist/targets/angular/spread.d.ts +32 -0
- package/dist/targets/angular/spread.js +182 -0
- package/dist/targets/angular/svg-hosts.d.ts +25 -0
- package/dist/targets/angular/svg-hosts.js +107 -0
- package/dist/targets/angular/template-expr.d.ts +36 -0
- package/dist/targets/angular/template-expr.js +287 -0
- package/dist/targets/angular/types.d.ts +9 -0
- package/dist/targets/angular/types.js +63 -0
- package/dist/targets/angular/walk.d.ts +11 -0
- package/dist/targets/angular/walk.js +26 -0
- package/dist/targets/react-native/emit.d.ts +14 -0
- package/dist/targets/react-native/emit.js +585 -0
- package/dist/targets/react-native/fidelity.d.ts +5 -0
- package/dist/targets/react-native/fidelity.js +43 -0
- package/dist/targets/react-native/motion.d.ts +10 -0
- package/dist/targets/react-native/motion.js +290 -0
- package/dist/targets/react-native/skia.d.ts +30 -0
- package/dist/targets/react-native/skia.js +358 -0
- package/dist/targets/shared/context.d.ts +47 -0
- package/dist/targets/shared/context.js +195 -0
- package/dist/targets/shared/foreign.d.ts +10 -0
- package/dist/targets/shared/foreign.js +72 -0
- package/dist/targets/shared/fragments.d.ts +21 -0
- package/dist/targets/shared/fragments.js +309 -0
- package/dist/targets/shared/handles.d.ts +65 -0
- package/dist/targets/shared/handles.js +299 -0
- package/dist/targets/shared/inline.d.ts +53 -0
- package/dist/targets/shared/inline.js +524 -0
- package/dist/targets/shared/layout.d.ts +70 -0
- package/dist/targets/shared/layout.js +224 -0
- package/dist/targets/shared/markup.d.ts +26 -0
- package/dist/targets/shared/markup.js +65 -0
- package/dist/targets/shared/module.d.ts +84 -0
- package/dist/targets/shared/module.js +468 -0
- package/dist/targets/shared/motion-hooks.d.ts +37 -0
- package/dist/targets/shared/motion-hooks.js +87 -0
- package/dist/targets/shared/motion-layout.d.ts +70 -0
- package/dist/targets/shared/motion-layout.js +392 -0
- package/dist/targets/shared/portal.d.ts +10 -0
- package/dist/targets/shared/portal.js +23 -0
- package/dist/targets/shared/prop-writes.d.ts +11 -0
- package/dist/targets/shared/prop-writes.js +32 -0
- package/dist/targets/shared/prune.d.ts +54 -0
- package/dist/targets/shared/prune.js +405 -0
- package/dist/targets/shared/react-libs.d.ts +25 -0
- package/dist/targets/shared/react-libs.js +142 -0
- package/dist/targets/shared/react-types.d.ts +16 -0
- package/dist/targets/shared/react-types.js +374 -0
- package/dist/targets/shared/react-values.d.ts +20 -0
- package/dist/targets/shared/react-values.js +145 -0
- package/dist/targets/shared/ref-callback.d.ts +16 -0
- package/dist/targets/shared/ref-callback.js +114 -0
- package/dist/targets/shared/script.d.ts +65 -0
- package/dist/targets/shared/script.js +406 -0
- package/dist/targets/shared/unused.d.ts +12 -0
- package/dist/targets/shared/unused.js +146 -0
- package/dist/targets/svelte/dom-spread.d.ts +27 -0
- package/dist/targets/svelte/dom-spread.js +146 -0
- package/dist/targets/svelte/emit.d.ts +15 -0
- package/dist/targets/svelte/emit.js +3784 -0
- package/dist/targets/svelte/handle-branches.d.ts +22 -0
- package/dist/targets/svelte/handle-branches.js +146 -0
- package/dist/targets/svelte/html-keys.d.ts +9 -0
- package/dist/targets/svelte/html-keys.js +40 -0
- package/dist/targets/svelte/markup-data/data.d.ts +51 -0
- package/dist/targets/svelte/markup-data/data.js +305 -0
- package/dist/targets/svelte/markup-data/helper.d.ts +12 -0
- package/dist/targets/svelte/markup-data/helper.js +81 -0
- package/dist/targets/svelte/markup-data/module-data.d.ts +21 -0
- package/dist/targets/svelte/markup-data/module-data.js +473 -0
- package/dist/targets/svelte/markup-data/sites.d.ts +52 -0
- package/dist/targets/svelte/markup-data/sites.js +303 -0
- package/dist/targets/svelte/motion-layout.d.ts +13 -0
- package/dist/targets/svelte/motion-layout.js +70 -0
- package/dist/targets/svelte/motion-table.d.ts +14 -0
- package/dist/targets/svelte/motion-table.js +308 -0
- package/dist/targets/svelte/motion.d.ts +46 -0
- package/dist/targets/svelte/motion.js +405 -0
- package/dist/targets/svelte/presence.d.ts +71 -0
- package/dist/targets/svelte/presence.js +318 -0
- package/dist/targets/svelte/radix/accordion.d.ts +9 -0
- package/dist/targets/svelte/radix/accordion.js +24 -0
- package/dist/targets/svelte/radix/aspect-ratio.d.ts +6 -0
- package/dist/targets/svelte/radix/aspect-ratio.js +8 -0
- package/dist/targets/svelte/radix/avatar.d.ts +6 -0
- package/dist/targets/svelte/radix/avatar.js +10 -0
- package/dist/targets/svelte/radix/checkbox.d.ts +10 -0
- package/dist/targets/svelte/radix/checkbox.js +24 -0
- package/dist/targets/svelte/radix/collapsible.d.ts +7 -0
- package/dist/targets/svelte/radix/collapsible.js +16 -0
- package/dist/targets/svelte/radix/context-menu.d.ts +8 -0
- package/dist/targets/svelte/radix/context-menu.js +49 -0
- package/dist/targets/svelte/radix/cores/alert-dialog.d.ts +17 -0
- package/dist/targets/svelte/radix/cores/alert-dialog.js +449 -0
- package/dist/targets/svelte/radix/cores/collapsible.d.ts +12 -0
- package/dist/targets/svelte/radix/cores/collapsible.js +214 -0
- package/dist/targets/svelte/radix/cores/core.d.ts +32 -0
- package/dist/targets/svelte/radix/cores/core.js +80 -0
- package/dist/targets/svelte/radix/cores/direction.d.ts +10 -0
- package/dist/targets/svelte/radix/cores/direction.js +64 -0
- package/dist/targets/svelte/radix/cores/index.d.ts +19 -0
- package/dist/targets/svelte/radix/cores/index.js +85 -0
- package/dist/targets/svelte/radix/cores/modal-layer.d.ts +11 -0
- package/dist/targets/svelte/radix/cores/modal-layer.js +244 -0
- package/dist/targets/svelte/radix/cores/presence.d.ts +12 -0
- package/dist/targets/svelte/radix/cores/presence.js +129 -0
- package/dist/targets/svelte/radix/cores/slider-logic.d.ts +10 -0
- package/dist/targets/svelte/radix/cores/slider-logic.js +287 -0
- package/dist/targets/svelte/radix/cores/slider.d.ts +13 -0
- package/dist/targets/svelte/radix/cores/slider.js +267 -0
- package/dist/targets/svelte/radix/dialog.d.ts +8 -0
- package/dist/targets/svelte/radix/dialog.js +20 -0
- package/dist/targets/svelte/radix/dropdown-menu.d.ts +9 -0
- package/dist/targets/svelte/radix/dropdown-menu.js +38 -0
- package/dist/targets/svelte/radix/emit.d.ts +12 -0
- package/dist/targets/svelte/radix/emit.js +1339 -0
- package/dist/targets/svelte/radix/hover-card.d.ts +7 -0
- package/dist/targets/svelte/radix/hover-card.js +22 -0
- package/dist/targets/svelte/radix/index.d.ts +12 -0
- package/dist/targets/svelte/radix/index.js +28 -0
- package/dist/targets/svelte/radix/label.d.ts +3 -0
- package/dist/targets/svelte/radix/label.js +5 -0
- package/dist/targets/svelte/radix/menubar.d.ts +7 -0
- package/dist/targets/svelte/radix/menubar.js +34 -0
- package/dist/targets/svelte/radix/navigation-menu.d.ts +8 -0
- package/dist/targets/svelte/radix/navigation-menu.js +25 -0
- package/dist/targets/svelte/radix/packages.d.ts +34 -0
- package/dist/targets/svelte/radix/packages.js +100 -0
- package/dist/targets/svelte/radix/part.d.ts +161 -0
- package/dist/targets/svelte/radix/part.js +85 -0
- package/dist/targets/svelte/radix/popover.d.ts +7 -0
- package/dist/targets/svelte/radix/popover.js +15 -0
- package/dist/targets/svelte/radix/progress.d.ts +11 -0
- package/dist/targets/svelte/radix/progress.js +27 -0
- package/dist/targets/svelte/radix/radio-group.d.ts +9 -0
- package/dist/targets/svelte/radix/radio-group.js +26 -0
- package/dist/targets/svelte/radix/scroll-area.d.ts +7 -0
- package/dist/targets/svelte/radix/scroll-area.js +19 -0
- package/dist/targets/svelte/radix/select.d.ts +13 -0
- package/dist/targets/svelte/radix/select.js +81 -0
- package/dist/targets/svelte/radix/separator.d.ts +3 -0
- package/dist/targets/svelte/radix/separator.js +5 -0
- package/dist/targets/svelte/radix/slider.d.ts +6 -0
- package/dist/targets/svelte/radix/slider.js +8 -0
- package/dist/targets/svelte/radix/switch.d.ts +6 -0
- package/dist/targets/svelte/radix/switch.js +10 -0
- package/dist/targets/svelte/radix/tabs.d.ts +8 -0
- package/dist/targets/svelte/radix/tabs.js +15 -0
- package/dist/targets/svelte/radix/toggle-group.d.ts +9 -0
- package/dist/targets/svelte/radix/toggle-group.js +17 -0
- package/dist/targets/svelte/radix/toggle.d.ts +6 -0
- package/dist/targets/svelte/radix/toggle.js +9 -0
- package/dist/targets/svelte/radix/tooltip.d.ts +6 -0
- package/dist/targets/svelte/radix/tooltip.js +24 -0
- package/dist/targets/svelte/strip.d.ts +2 -0
- package/dist/targets/svelte/strip.js +5 -0
- package/dist/targets/vue/emit.d.ts +15 -0
- package/dist/targets/vue/emit.js +4092 -0
- package/dist/targets/vue/events.d.ts +11 -0
- package/dist/targets/vue/events.js +13 -0
- package/dist/targets/vue/module-builders.d.ts +28 -0
- package/dist/targets/vue/module-builders.js +258 -0
- package/dist/targets/vue/motion-layout.d.ts +19 -0
- package/dist/targets/vue/motion-layout.js +79 -0
- package/dist/targets/vue/motion.d.ts +12 -0
- package/dist/targets/vue/motion.js +46 -0
- package/dist/targets/vue/radix/accordion.d.ts +3 -0
- package/dist/targets/vue/radix/accordion.js +12 -0
- package/dist/targets/vue/radix/alert-dialog.d.ts +6 -0
- package/dist/targets/vue/radix/alert-dialog.js +18 -0
- package/dist/targets/vue/radix/aspect-ratio.d.ts +6 -0
- package/dist/targets/vue/radix/aspect-ratio.js +8 -0
- package/dist/targets/vue/radix/avatar.d.ts +3 -0
- package/dist/targets/vue/radix/avatar.js +7 -0
- package/dist/targets/vue/radix/checkbox.d.ts +3 -0
- package/dist/targets/vue/radix/checkbox.js +9 -0
- package/dist/targets/vue/radix/collapsible.d.ts +7 -0
- package/dist/targets/vue/radix/collapsible.js +11 -0
- package/dist/targets/vue/radix/context-menu.d.ts +3 -0
- package/dist/targets/vue/radix/context-menu.js +30 -0
- package/dist/targets/vue/radix/dialog.d.ts +3 -0
- package/dist/targets/vue/radix/dialog.js +12 -0
- package/dist/targets/vue/radix/direction.d.ts +7 -0
- package/dist/targets/vue/radix/direction.js +9 -0
- package/dist/targets/vue/radix/dropdown-menu.d.ts +3 -0
- package/dist/targets/vue/radix/dropdown-menu.js +29 -0
- package/dist/targets/vue/radix/hover-card.d.ts +3 -0
- package/dist/targets/vue/radix/hover-card.js +11 -0
- package/dist/targets/vue/radix/index.d.ts +65 -0
- package/dist/targets/vue/radix/index.js +225 -0
- package/dist/targets/vue/radix/label.d.ts +3 -0
- package/dist/targets/vue/radix/label.js +5 -0
- package/dist/targets/vue/radix/menubar.d.ts +6 -0
- package/dist/targets/vue/radix/menubar.js +29 -0
- package/dist/targets/vue/radix/navigation-menu.d.ts +6 -0
- package/dist/targets/vue/radix/navigation-menu.js +21 -0
- package/dist/targets/vue/radix/part.d.ts +41 -0
- package/dist/targets/vue/radix/part.js +46 -0
- package/dist/targets/vue/radix/popover.d.ts +3 -0
- package/dist/targets/vue/radix/popover.js +11 -0
- package/dist/targets/vue/radix/progress.d.ts +3 -0
- package/dist/targets/vue/radix/progress.js +6 -0
- package/dist/targets/vue/radix/radio-group.d.ts +3 -0
- package/dist/targets/vue/radix/radio-group.js +10 -0
- package/dist/targets/vue/radix/scroll-area.d.ts +3 -0
- package/dist/targets/vue/radix/scroll-area.js +11 -0
- package/dist/targets/vue/radix/select.d.ts +3 -0
- package/dist/targets/vue/radix/select.js +29 -0
- package/dist/targets/vue/radix/separator.d.ts +3 -0
- package/dist/targets/vue/radix/separator.js +5 -0
- package/dist/targets/vue/radix/slider.d.ts +3 -0
- package/dist/targets/vue/radix/slider.js +13 -0
- package/dist/targets/vue/radix/switch.d.ts +3 -0
- package/dist/targets/vue/radix/switch.js +9 -0
- package/dist/targets/vue/radix/tabs.d.ts +3 -0
- package/dist/targets/vue/radix/tabs.js +12 -0
- package/dist/targets/vue/radix/toggle-group.d.ts +3 -0
- package/dist/targets/vue/radix/toggle-group.js +10 -0
- package/dist/targets/vue/radix/toggle.d.ts +3 -0
- package/dist/targets/vue/radix/toggle.js +8 -0
- package/dist/targets/vue/radix/tooltip.d.ts +3 -0
- package/dist/targets/vue/radix/tooltip.js +14 -0
- package/dist/targets/vue/render-fn/h.d.ts +52 -0
- package/dist/targets/vue/render-fn/h.js +442 -0
- package/dist/targets/vue/render-fn.d.ts +21 -0
- package/dist/targets/vue/render-fn.js +357 -0
- package/dist/targets/vue/slot.d.ts +9 -0
- package/dist/targets/vue/slot.js +57 -0
- package/dist/typecheck/host.d.ts +45 -0
- package/dist/typecheck/host.js +309 -0
- package/dist/typecheck/index.d.ts +16 -0
- package/dist/typecheck/index.js +17 -0
- package/dist/typecheck/lucide.d.ts +8 -0
- package/dist/typecheck/lucide.js +45 -0
- package/dist/typecheck/sourcemap.d.ts +9 -0
- package/dist/typecheck/sourcemap.js +54 -0
- package/dist/typecheck/svelte.d.ts +9 -0
- package/dist/typecheck/svelte.js +116 -0
- package/dist/typecheck/vue.d.ts +8 -0
- package/dist/typecheck/vue.js +78 -0
- package/dist/types.d.ts +446 -0
- package/dist/types.js +11 -0
- package/dist/utils/cleanup.d.ts +32 -0
- package/dist/utils/cleanup.js +119 -0
- package/dist/utils/errors.d.ts +7 -0
- package/dist/utils/errors.js +15 -0
- package/dist/utils/fs-safe.d.ts +14 -0
- package/dist/utils/fs-safe.js +64 -0
- package/dist/validate.d.ts +16 -0
- package/dist/validate.js +204 -0
- package/dist/verify/auto-steps.d.ts +107 -0
- package/dist/verify/auto-steps.js +471 -0
- package/dist/verify/bundle.d.ts +68 -0
- package/dist/verify/bundle.js +548 -0
- package/dist/verify/diff.d.ts +31 -0
- package/dist/verify/diff.js +133 -0
- package/dist/verify/leaks.d.ts +25 -0
- package/dist/verify/leaks.js +261 -0
- package/dist/verify/link-worker.d.ts +1 -0
- package/dist/verify/link-worker.js +27 -0
- package/dist/verify/runner.d.ts +57 -0
- package/dist/verify/runner.js +867 -0
- package/dist/verify/sandbox.d.ts +40 -0
- package/dist/verify/sandbox.js +496 -0
- package/dist/verify/steps.d.ts +42 -0
- package/dist/verify/steps.js +475 -0
- package/dist/verify/verdict.d.ts +15 -0
- package/dist/verify/verdict.js +19 -0
- package/package.json +118 -4
|
@@ -0,0 +1,3784 @@
|
|
|
1
|
+
import * as t from '@babel/types';
|
|
2
|
+
import { parseSource } from '../../analyzer/parse.js';
|
|
3
|
+
import { MOTION_PACKAGES, resolveLocal } from '../../analyzer/deps.js';
|
|
4
|
+
import { assertPaths, nonNullFacts, patternNames, ROW_HELPERS, unwrap } from '../../ir/lower.js';
|
|
5
|
+
import { asChildElements } from '../../ir/as-child.js';
|
|
6
|
+
import { snippetHelperHolder } from '../../ir/helper-snippets.js';
|
|
7
|
+
import { domAttributeName, domEventName, isDomEventProp } from '../../ir/dom.js';
|
|
8
|
+
import { TYPED_SETTERS, bindingsUsed, cloneWithRefs, renameFree, rewrite, stripTypes, transform } from '../../ir/rewrite.js';
|
|
9
|
+
import { renameBinding } from '../../ir/rename.js';
|
|
10
|
+
import { isStringy, isUnitless, kebabCase, numericLiteral, reactStyleValue, styleKey, unitlessSource } from '../../ir/style.js';
|
|
11
|
+
import { markupNames, pruneUnused, wordsIn } from '../shared/prune.js';
|
|
12
|
+
import { reactValues, replaceElementTests, reportReactRuntime } from '../shared/react-values.js';
|
|
13
|
+
import { ImportSet, importPath, keepProvidersFiled } from '../shared/layout.js';
|
|
14
|
+
import { expandUse, passesMarkup, snippetArgument, takesRef, templateExpressions } from '../shared/inline.js';
|
|
15
|
+
import { droppedSlotMessage, rendersSlot, renderSignature } from '../../ir/render-props.js';
|
|
16
|
+
import { addOriginalImport, moduleFacts, namesIn, rewriteImportTypes, rewriteReexport, SVELTE_MOTION_HOOKS, transformModuleBody } from '../shared/module.js';
|
|
17
|
+
import { bareExpression, holdsMotionValue, isMotionTemplate, motionHookPlan, SCROLL_VALUES } from '../shared/motion-hooks.js';
|
|
18
|
+
import { inheritedAttrType, mapReactTypes } from '../shared/react-types.js';
|
|
19
|
+
import { NameAllocator, buildCore, cutLeftoverJsx, moduleLets, moduleSetters, orNull, reactiveDeps, refHolds, routeModuleWrites, typedCall } from '../shared/script.js';
|
|
20
|
+
import { SVG_TAGS, VOID_TAGS, componentStyle, escapeText, genericsAttr, innerHtmlWarning, printExpr, printInline, printProgram } from '../shared/markup.js';
|
|
21
|
+
import { contextModuleBody, guardedContext, linkContexts, svelteContextHelper } from '../shared/context.js';
|
|
22
|
+
import { childComponent, domElementType as tagElementType, forwardedElement, forwardsElement, handleMemberNames, handleMembers, handleType, handleValue, passesHandle, readsReactive } from '../shared/handles.js';
|
|
23
|
+
import { propWrites } from '../shared/prop-writes.js';
|
|
24
|
+
import { ACTION_PROPS, MOTION_ACTION, MOTION_ENTER, MOTION_EXIT, MOTION_HELPER_FILE, UNCONVERTED, actionParams, motionFeatures, useMotionHelper } from './motion.js';
|
|
25
|
+
// M2: layout / layoutId / drag (motion-layout.ts)
|
|
26
|
+
import { LAYOUT_HELPER_FILE, MOTION_DRAG, MOTION_LAYOUT, layoutActions } from './motion-layout.js';
|
|
27
|
+
import { layoutDragParams, playsLayoutOrDrag, useLayoutHelper } from '../shared/motion-layout.js';
|
|
28
|
+
import { MarkupData } from './markup-data/data.js';
|
|
29
|
+
import { MARKUP_ELEMENT_TYPE, MARKUP_MODULE_FILE, MARKUP_TYPE, MARKUP_VIEW, MARKUP_VIEW_FILE, useMarkupHelper } from './markup-data/helper.js';
|
|
30
|
+
import { drawsModuleData, planModuleData } from './markup-data/module-data.js';
|
|
31
|
+
import { holdsMotionTag, resolveMotionSpreads, resolveMotionTables } from './motion-table.js';
|
|
32
|
+
import { constantKey, enterPlacements, exitPlacements, moduleAnimatesIn, unfollowedEnters } from './presence.js';
|
|
33
|
+
import { SVELTE_PORTAL_SOURCE } from '../shared/portal.js';
|
|
34
|
+
import { alreadyDomNamed, changeEvent, domPropsSource, inheritedAttributeName, staticDomProps } from './dom-spread.js';
|
|
35
|
+
import { passesBitsChild, prepareSvelteRadix } from './radix/index.js';
|
|
36
|
+
import { branchTargets, membersInEvery, reachedMembers } from './handle-branches.js';
|
|
37
|
+
import { settlesLikeReact } from '../shared/ref-callback.js';
|
|
38
|
+
import { svelteHtmlKeys } from './html-keys.js';
|
|
39
|
+
/** Rune calls that only build a value: a binding nobody reads can go. */
|
|
40
|
+
const PURE_RUNES = new Set(['$state', '$state.raw', '$derived', '$derived.by', '$props.id']);
|
|
41
|
+
const SVELTE_APIS = ['onMount', 'untrack'];
|
|
42
|
+
/** `$state` for a plain value, `$state.raw` for anything that could be an object (see the state case in `item`). */
|
|
43
|
+
function stateRune(init) {
|
|
44
|
+
if (!init)
|
|
45
|
+
return '$state';
|
|
46
|
+
const plain = t.isStringLiteral(init) || t.isNumericLiteral(init) || t.isBooleanLiteral(init) || t.isNullLiteral(init) || t.isTemplateLiteral(init) || t.isIdentifier(init, { name: 'undefined' }) || (t.isUnaryExpression(init) && t.isNumericLiteral(init.argument));
|
|
47
|
+
return plain ? '$state' : '$state.raw';
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Names Svelte reads as a rune when `$` comes before them. In a component, a binding named like one turns that rune
|
|
51
|
+
* into a store subscription to the binding (`const state = ...` makes `$state(0)` read the store `state`), which fails
|
|
52
|
+
* at runtime and only warns at compile time (store_rune_conflict). `$props` is the one Svelte tells apart.
|
|
53
|
+
*/
|
|
54
|
+
const RUNE_NAMES = new Set(['state', 'derived', 'effect', 'bindable', 'inspect', 'host']);
|
|
55
|
+
/** Whether a component passes its forwarded ref on to child components (held in `$state.raw`, read through `$derived`). */
|
|
56
|
+
function passesRefOn(ir) {
|
|
57
|
+
const isComponent = (x) => 'template' in x;
|
|
58
|
+
return isComponent(ir) && !!ir.forwardRef && (!!passesHandle(ir) || !!branchTargets(ir));
|
|
59
|
+
}
|
|
60
|
+
/** Whether the function's script may call the rune (`$state` for its state, refs and element refs, and so on). */
|
|
61
|
+
function mayUseRune(ir, rune) {
|
|
62
|
+
switch (rune) {
|
|
63
|
+
case 'state':
|
|
64
|
+
return ir.items.some((i) => i.kind === 'state' || i.kind === 'reducer' || i.kind === 'ref' || i.kind === 'hook') || passesRefOn(ir);
|
|
65
|
+
case 'derived':
|
|
66
|
+
return ir.items.some((i) => i.kind === 'derived' || i.kind === 'block' || i.kind === 'hook' || i.kind === 'context' || i.kind === 'handle') || [...ir.bindings.values()].some((b) => b.kind === 'rest') || passesRefOn(ir);
|
|
67
|
+
case 'effect':
|
|
68
|
+
return ir.items.some((i) => i.kind === 'effect');
|
|
69
|
+
case 'bindable':
|
|
70
|
+
return !!Reflect.get(ir, 'forwardRef');
|
|
71
|
+
default:
|
|
72
|
+
return false;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Renames the bindings of a component or hook named like a rune its script calls (`state` becomes `stateValue`). A
|
|
77
|
+
* conflict this misses is still reported after emission (svelte-rune-name).
|
|
78
|
+
*/
|
|
79
|
+
function avoidRuneNames(ir, taken) {
|
|
80
|
+
for (const name of [...ir.bindings.keys()]) {
|
|
81
|
+
if (!RUNE_NAMES.has(name) || !mayUseRune(ir, name))
|
|
82
|
+
continue;
|
|
83
|
+
const kind = ir.bindings.get(name)?.kind;
|
|
84
|
+
const alloc = new NameAllocator([...taken, ...ir.bindings.keys()]);
|
|
85
|
+
const to = alloc.alloc(kind === 'function' ? `${name}Fn` : `${name}Value`);
|
|
86
|
+
if (!renameBinding(ir, name, to))
|
|
87
|
+
continue;
|
|
88
|
+
taken.add(to);
|
|
89
|
+
// a list row's helper (ir/lower's ROW_HELPERS) reads the component's names through identifiers lowering did not
|
|
90
|
+
// resolve: its free uses of the old name are the binding's too, unless the helper declares that name itself
|
|
91
|
+
for (const item of ir.items) {
|
|
92
|
+
if (item.kind !== 'function' || !ROW_HELPERS.has(item.node) || declaresName(item.node, name))
|
|
93
|
+
continue;
|
|
94
|
+
item.node = renameFree(item.node, new Map([[name, t.identifier(to)]]));
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
/** Whether a function declares a name anywhere inside it (a parameter, a variable, a nested function or class). */
|
|
99
|
+
function declaresName(fn, name) {
|
|
100
|
+
let found = false;
|
|
101
|
+
t.traverseFast(fn, (n) => {
|
|
102
|
+
if (found)
|
|
103
|
+
return;
|
|
104
|
+
if (t.isFunction(n))
|
|
105
|
+
for (const p of n.params)
|
|
106
|
+
if (name in t.getBindingIdentifiers(p, false))
|
|
107
|
+
found = true;
|
|
108
|
+
if ((t.isVariableDeclarator(n) || t.isCatchClause(n)) && name in t.getBindingIdentifiers(t.isCatchClause(n) ? (n.param ?? t.identifier('_')) : n.id, false))
|
|
109
|
+
found = true;
|
|
110
|
+
if ((t.isFunctionDeclaration(n) || t.isClassDeclaration(n)) && n.id?.name === name)
|
|
111
|
+
found = true;
|
|
112
|
+
});
|
|
113
|
+
return found;
|
|
114
|
+
}
|
|
115
|
+
/** Form fields: a change or input event is dispatched on the field itself, never on something inside it. */
|
|
116
|
+
const FIELD_TAGS = new Set(['input', 'textarea', 'select']);
|
|
117
|
+
/**
|
|
118
|
+
* React's ChangeEvent on a field types `e.target` as the field; the DOM's (and Svelte's handler types) say only
|
|
119
|
+
* `EventTarget | null` for `target`, and type the field as `currentTarget`. On a field the two are the same element, so
|
|
120
|
+
* an inline handler's `e.target` reads `e.currentTarget`: the same value, typed as React typed it, with no cast.
|
|
121
|
+
*/
|
|
122
|
+
function changeTargetIsField(handler) {
|
|
123
|
+
const fn = unwrap(handler);
|
|
124
|
+
if (!(t.isArrowFunctionExpression(fn) || t.isFunctionExpression(fn)))
|
|
125
|
+
return handler;
|
|
126
|
+
const param = fn.params[0];
|
|
127
|
+
if (!t.isIdentifier(param))
|
|
128
|
+
return handler;
|
|
129
|
+
const name = param.name;
|
|
130
|
+
const copy = t.cloneNode(fn, true);
|
|
131
|
+
t.traverse(copy, (n, ancestors) => {
|
|
132
|
+
if (!t.isMemberExpression(n) || n.computed || !t.isIdentifier(n.object, { name }) || !t.isIdentifier(n.property, { name: 'target' }))
|
|
133
|
+
return;
|
|
134
|
+
// a nested function that declares the same name sees its own
|
|
135
|
+
const shadowed = ancestors.some(({ node }) => node !== copy && t.isFunction(node) && node.params.some((p) => name in t.getBindingIdentifiers(p)));
|
|
136
|
+
if (!shadowed)
|
|
137
|
+
n.property = t.identifier('currentTarget');
|
|
138
|
+
});
|
|
139
|
+
return copy;
|
|
140
|
+
}
|
|
141
|
+
/** Whether a handler reads `.nativeEvent` anywhere. */
|
|
142
|
+
function readsNativeEvent(handler) {
|
|
143
|
+
let found = false;
|
|
144
|
+
t.traverseFast(handler, (n) => {
|
|
145
|
+
if ((t.isMemberExpression(n) || t.isOptionalMemberExpression(n)) && !n.computed && t.isIdentifier(n.property, { name: 'nativeEvent' }))
|
|
146
|
+
found = true;
|
|
147
|
+
});
|
|
148
|
+
return found;
|
|
149
|
+
}
|
|
150
|
+
/** The DOM event type React's types give `nativeEvent` for a handler prop (React's NativeMouseEvent and the rest). */
|
|
151
|
+
function nativeEventType(reactName) {
|
|
152
|
+
const e = reactName.replace(/^on/, '').replace(/Capture$/, '');
|
|
153
|
+
if (/^(Click|DoubleClick|Mouse|ContextMenu|AuxClick)/.test(e))
|
|
154
|
+
return 'MouseEvent';
|
|
155
|
+
if (/^(Pointer|GotPointer|LostPointer)/.test(e))
|
|
156
|
+
return 'PointerEvent';
|
|
157
|
+
if (/^Key/.test(e))
|
|
158
|
+
return 'KeyboardEvent';
|
|
159
|
+
if (/^(Focus|Blur)/.test(e))
|
|
160
|
+
return 'FocusEvent';
|
|
161
|
+
if (/^Wheel/.test(e))
|
|
162
|
+
return 'WheelEvent';
|
|
163
|
+
if (/^Touch/.test(e))
|
|
164
|
+
return 'TouchEvent';
|
|
165
|
+
if (/^(Drag|Drop)/.test(e))
|
|
166
|
+
return 'DragEvent';
|
|
167
|
+
if (/^Animation/.test(e))
|
|
168
|
+
return 'AnimationEvent';
|
|
169
|
+
if (/^Transition/.test(e))
|
|
170
|
+
return 'TransitionEvent';
|
|
171
|
+
return 'Event';
|
|
172
|
+
}
|
|
173
|
+
/** `e.nativeEvent` → `e` in an inline element handler whose own first parameter is `e` (not where a nested function rebinds it). */
|
|
174
|
+
function nativeEventIsEvent(handler, reactName) {
|
|
175
|
+
const fn = unwrap(handler);
|
|
176
|
+
if (!(t.isArrowFunctionExpression(fn) || t.isFunctionExpression(fn)))
|
|
177
|
+
return handler;
|
|
178
|
+
const param = fn.params[0];
|
|
179
|
+
if (!t.isIdentifier(param))
|
|
180
|
+
return handler;
|
|
181
|
+
const name = param.name;
|
|
182
|
+
const reads = new Set();
|
|
183
|
+
t.traverse(fn.body, (n, ancestors) => {
|
|
184
|
+
if (!(t.isMemberExpression(n) || t.isOptionalMemberExpression(n)) || n.computed || !t.isIdentifier(n.object, { name }) || !t.isIdentifier(n.property, { name: 'nativeEvent' }))
|
|
185
|
+
return;
|
|
186
|
+
const shadowed = ancestors.some(({ node }) => t.isFunction(node) && node.params.some((p) => name in t.getBindingIdentifiers(p)));
|
|
187
|
+
if (!shadowed)
|
|
188
|
+
reads.add(n);
|
|
189
|
+
});
|
|
190
|
+
if (!reads.size)
|
|
191
|
+
return handler;
|
|
192
|
+
// (the expression is the conversion's own copy, rewritten for the markup: changed in place)
|
|
193
|
+
// `(e.nativeEvent as PointerEvent)`: the author's cast is from the DOM event React typed nativeEvent as (MouseEvent
|
|
194
|
+
// for onClick); Svelte types the handler's event as that event and its currentTarget, which TypeScript will not cast
|
|
195
|
+
// to a sibling event type, so the read is typed as React typed it first: `(e as MouseEvent as PointerEvent)`
|
|
196
|
+
const body = transform(fn.body, (n, parent) => {
|
|
197
|
+
if (!reads.has(n))
|
|
198
|
+
return null;
|
|
199
|
+
return t.isTSAsExpression(parent) && parent.expression === n ? t.tsAsExpression(t.identifier(name), t.tsTypeReference(t.identifier(nativeEventType(reactName)))) : t.identifier(name);
|
|
200
|
+
});
|
|
201
|
+
if (t.isBlockStatement(body))
|
|
202
|
+
fn.body = body;
|
|
203
|
+
else if (t.isExpression(body) && t.isArrowFunctionExpression(fn))
|
|
204
|
+
fn.body = body;
|
|
205
|
+
return handler;
|
|
206
|
+
}
|
|
207
|
+
function parseStatements(src) {
|
|
208
|
+
return parseSource(src, 'helper.ts').program.body;
|
|
209
|
+
}
|
|
210
|
+
/** Script-side emission shared by components and rune modules. */
|
|
211
|
+
class SvelteScript {
|
|
212
|
+
ir;
|
|
213
|
+
alloc;
|
|
214
|
+
ctx;
|
|
215
|
+
facts;
|
|
216
|
+
svelte = new Map();
|
|
217
|
+
helpers = new Set();
|
|
218
|
+
/** what the file's motion elements ask of the motion action (see motionFeatures) */
|
|
219
|
+
motion = new Set();
|
|
220
|
+
/** the local name of the portal attachment (see SVELTE_PORTAL_SOURCE), once a portal uses it */
|
|
221
|
+
portalName = null;
|
|
222
|
+
typeImports = [];
|
|
223
|
+
imports = new ImportSet();
|
|
224
|
+
cores = [];
|
|
225
|
+
/** hook results read through `$derived(result.member)` */
|
|
226
|
+
propRenames = new Map();
|
|
227
|
+
firstId = null;
|
|
228
|
+
idCount = 1;
|
|
229
|
+
constructor(ir, alloc, ctx, facts) {
|
|
230
|
+
this.ir = ir;
|
|
231
|
+
this.alloc = alloc;
|
|
232
|
+
this.ctx = ctx;
|
|
233
|
+
this.facts = facts;
|
|
234
|
+
}
|
|
235
|
+
api(name) {
|
|
236
|
+
let local = this.svelte.get(name);
|
|
237
|
+
if (!local) {
|
|
238
|
+
local = this.alloc.has(name) ? this.alloc.alloc(`svelte${name.charAt(0).toUpperCase()}${name.slice(1)}`) : name;
|
|
239
|
+
this.alloc.reserve(local);
|
|
240
|
+
this.svelte.set(name, local);
|
|
241
|
+
}
|
|
242
|
+
return local;
|
|
243
|
+
}
|
|
244
|
+
r(node, skip) {
|
|
245
|
+
return rewrite(node, { ir: this.ir, mode: 'svelte', propRenames: this.propRenames, ...(skip ? { skip } : {}) });
|
|
246
|
+
}
|
|
247
|
+
type(type) {
|
|
248
|
+
return type ? mapReactTypes(t.cloneNode(type, true), 'svelte', this.facts.reactNames, this.typeImports) : null;
|
|
249
|
+
}
|
|
250
|
+
warn(code, message, severity = 'warning', line) {
|
|
251
|
+
// an error about a component with no line of its own points at the component (see sparesUnusedComponents)
|
|
252
|
+
const at = line ?? (severity === 'error' ? this.ir.line : undefined);
|
|
253
|
+
this.ctx.diagnostics.push({ code, severity, message, file: this.ctx.sourceRel, target: 'svelte', ...(at ? { line: at } : {}) });
|
|
254
|
+
}
|
|
255
|
+
decl(name, init, kind = 'const') {
|
|
256
|
+
return t.variableDeclaration(kind, [t.variableDeclarator(typeof name === 'string' ? t.identifier(name) : name, init)]);
|
|
257
|
+
}
|
|
258
|
+
rune(name, args, type = null) {
|
|
259
|
+
return typedCall(name, type, args);
|
|
260
|
+
}
|
|
261
|
+
items() {
|
|
262
|
+
const out = [];
|
|
263
|
+
// a block of several values is destructured where it is declared (`const { a, b } = $derived.by(…)`): the values
|
|
264
|
+
// read from it are declared there
|
|
265
|
+
const destructured = new Set();
|
|
266
|
+
for (const block of this.ir.items) {
|
|
267
|
+
if (block.kind !== 'block' || !block.members || !this.ir.bindings.get(block.name)?.reactive)
|
|
268
|
+
continue;
|
|
269
|
+
const members = block.members;
|
|
270
|
+
for (const other of this.ir.items) {
|
|
271
|
+
if (other.kind === 'derived' && other.names.length === 1 && members.includes(other.names[0] ?? '') && t.isMemberExpression(other.init) && t.isIdentifier(other.init.object, { name: block.name }))
|
|
272
|
+
destructured.add(other);
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
// values lowering kept because they build elements (FunctionIR.keptMarkup), written as data where they can be, each
|
|
276
|
+
// in its place in the source
|
|
277
|
+
const kept = this.markup?.values() ?? [];
|
|
278
|
+
const print = (item) => {
|
|
279
|
+
out.push(...this.item(item).map((s) => mapReactTypes(s, 'svelte', this.facts.reactNames, this.typeImports)));
|
|
280
|
+
};
|
|
281
|
+
const printKept = (k) => {
|
|
282
|
+
out.push(...this.keptValue(k).map((s) => mapReactTypes(s, 'svelte', this.facts.reactNames, this.typeImports)));
|
|
283
|
+
};
|
|
284
|
+
const placed = new Set([null, ...this.ir.items]);
|
|
285
|
+
for (const k of kept)
|
|
286
|
+
if (k.after === null)
|
|
287
|
+
printKept(k);
|
|
288
|
+
// React runs every layout effect of a commit before any passive one, each kind in source order; Svelte runs a
|
|
289
|
+
// component's `$effect`s and onMounts in the order they are registered (deferred to mount in that order:
|
|
290
|
+
// svelte/src/internal/client/context.js `pop`). A useEffect written before the last useLayoutEffect is registered
|
|
291
|
+
// right after that layout effect, so the layout effects come first and each kind keeps its order.
|
|
292
|
+
const plan = this.effectReorder();
|
|
293
|
+
for (const item of this.ir.items) {
|
|
294
|
+
// the layout effects written after the first useEffect (or custom hook) are registered in front of it
|
|
295
|
+
if (plan && item === plan.before)
|
|
296
|
+
for (const h of plan.hoisted)
|
|
297
|
+
print(h);
|
|
298
|
+
if (plan?.hoisted.includes(item)) {
|
|
299
|
+
// values kept after it stay where they were: only the effect's registration moves
|
|
300
|
+
for (const k of kept)
|
|
301
|
+
if (k.after === item)
|
|
302
|
+
printKept(k);
|
|
303
|
+
continue;
|
|
304
|
+
}
|
|
305
|
+
if (!destructured.has(item))
|
|
306
|
+
print(item);
|
|
307
|
+
for (const k of kept)
|
|
308
|
+
if (k.after === item)
|
|
309
|
+
printKept(k);
|
|
310
|
+
}
|
|
311
|
+
// one whose neighbour another pass removed goes last: a `$derived` is read only once the script has run
|
|
312
|
+
for (const k of kept)
|
|
313
|
+
if (!placed.has(k.after))
|
|
314
|
+
printKept(k);
|
|
315
|
+
return out;
|
|
316
|
+
}
|
|
317
|
+
/**
|
|
318
|
+
* A kept value written as data: a block that reads reactive values re-runs as React re-renders (`$derived.by`), whatever
|
|
319
|
+
* its binding says (the binding is left as lowering made it for the other targets).
|
|
320
|
+
*/
|
|
321
|
+
keptValue(k) {
|
|
322
|
+
const item = k.item;
|
|
323
|
+
if (item.kind !== 'block' || !k.reactive)
|
|
324
|
+
return this.item(item);
|
|
325
|
+
const statements = item.statements.map((s) => this.r(s, new Set([item.name])));
|
|
326
|
+
const fn = t.arrowFunctionExpression([], t.blockStatement(item.returns ? statements : [...statements, t.returnStatement(t.identifier(item.name))]));
|
|
327
|
+
return [this.decl(item.name, typedCall('$derived.by', this.type(item.type), [fn]))];
|
|
328
|
+
}
|
|
329
|
+
/** the component's elements held as data (markup-data/data.ts), set by the component's emitter */
|
|
330
|
+
markup = null;
|
|
331
|
+
item(item) {
|
|
332
|
+
const b = (name) => this.ir.bindings.get(name);
|
|
333
|
+
switch (item.kind) {
|
|
334
|
+
// React state is only ever replaced by its setter, never changed in place, which is $state.raw: a deep $state
|
|
335
|
+
// would hand back a proxy, so `prev !== props.items` stays true forever and an effect loops
|
|
336
|
+
case 'state':
|
|
337
|
+
return [this.decl(item.name, this.rune(stateRune(item.init), item.init ? [this.r(item.init)] : [], this.type(item.type)), 'let')];
|
|
338
|
+
case 'reducer':
|
|
339
|
+
return [
|
|
340
|
+
this.decl(item.name, this.rune(stateRune(item.init), [this.r(item.init)]), 'let'),
|
|
341
|
+
t.functionDeclaration(t.identifier(item.dispatch), [t.identifier('action')], t.blockStatement([t.expressionStatement(t.assignmentExpression('=', t.identifier(item.name), t.callExpression(this.r(item.reducer), [t.identifier(item.name), t.identifier('action')])))])),
|
|
342
|
+
];
|
|
343
|
+
case 'ref': {
|
|
344
|
+
const binding = b(item.name);
|
|
345
|
+
const type = this.type(item.type);
|
|
346
|
+
// the element a parent's ref reaches: the `ref = $bindable()` prop holds it (see propsDeclaration)
|
|
347
|
+
if (this.forward?.local === item.name)
|
|
348
|
+
return [];
|
|
349
|
+
if (binding?.refKind === 'dom' && !binding.escapes) {
|
|
350
|
+
const elType = type ?? t.tsTypeReference(t.identifier('HTMLElement'));
|
|
351
|
+
return [this.decl(item.name, this.rune('$state', [t.nullLiteral()], orNull(elType)), 'let')];
|
|
352
|
+
}
|
|
353
|
+
const init = item.init ? this.r(item.init) : null;
|
|
354
|
+
if (binding?.escapes || binding?.refKind === 'dom') {
|
|
355
|
+
const id = t.identifier(item.name);
|
|
356
|
+
// `useRef<T>(null)`: React types `current` as `T | null`
|
|
357
|
+
const dom = binding.refKind === 'dom';
|
|
358
|
+
const inner = dom ? orNull(type ?? t.tsTypeReference(t.identifier('HTMLElement'))) : type && refHolds(type, init);
|
|
359
|
+
if (inner)
|
|
360
|
+
id.typeAnnotation = t.tsTypeAnnotation(t.tsTypeLiteral([t.tsPropertySignature(t.identifier('current'), t.tsTypeAnnotation(inner))]));
|
|
361
|
+
// an element's box starts empty (null); any other `useRef()` holds undefined, as in React
|
|
362
|
+
return [this.decl(id, t.objectExpression([t.objectProperty(t.identifier('current'), init ?? (dom ? t.nullLiteral() : t.identifier('undefined')))]))];
|
|
363
|
+
}
|
|
364
|
+
const id = t.identifier(item.name);
|
|
365
|
+
if (type)
|
|
366
|
+
id.typeAnnotation = t.tsTypeAnnotation(refHolds(type, init));
|
|
367
|
+
return [this.decl(id, init, 'let')];
|
|
368
|
+
}
|
|
369
|
+
case 'derived': {
|
|
370
|
+
// `const bg = useMotionTemplate\`…\``: motion's form (see motionTemplate)
|
|
371
|
+
if (isMotionTemplate(item.init) && t.isIdentifier(item.id))
|
|
372
|
+
return this.motionTemplate(item.id.name, item.init);
|
|
373
|
+
const reactive = item.names.some((n) => b(n)?.reactive);
|
|
374
|
+
if (!reactive) {
|
|
375
|
+
const id = t.cloneNode(item.id, true);
|
|
376
|
+
return [t.variableDeclaration(item.declKind, [t.variableDeclarator(id, this.r(item.init))])];
|
|
377
|
+
}
|
|
378
|
+
const id = t.cloneNode(item.id, true);
|
|
379
|
+
if (t.isIdentifier(id))
|
|
380
|
+
id.typeAnnotation = null;
|
|
381
|
+
return [this.decl(id, this.rune('$derived', [this.r(item.init)], t.isIdentifier(item.id) ? this.type(item.type) : null))];
|
|
382
|
+
}
|
|
383
|
+
case 'block': {
|
|
384
|
+
const reactive = b(item.name)?.reactive;
|
|
385
|
+
const skip = new Set([item.name]);
|
|
386
|
+
const statements = item.statements.map((s) => this.r(s, skip));
|
|
387
|
+
const fn = t.arrowFunctionExpression([], t.blockStatement(item.returns ? statements : [...statements, t.returnStatement(t.identifier(item.name))]));
|
|
388
|
+
if (reactive && item.members) {
|
|
389
|
+
const pattern = t.objectPattern(item.members.map((m) => t.objectProperty(t.identifier(m), t.identifier(m), false, true)));
|
|
390
|
+
return [this.decl(pattern, typedCall('$derived.by', null, [fn]))];
|
|
391
|
+
}
|
|
392
|
+
if (reactive)
|
|
393
|
+
return [this.decl(item.name, typedCall('$derived.by', this.type(item.type), [fn]))];
|
|
394
|
+
if (!item.returns)
|
|
395
|
+
return statements;
|
|
396
|
+
return [this.decl(item.name, t.callExpression(t.parenthesizedExpression(fn), []))];
|
|
397
|
+
}
|
|
398
|
+
case 'function': {
|
|
399
|
+
const node = this.r(item.node);
|
|
400
|
+
return t.isFunctionDeclaration(node) ? [node] : [this.decl(item.name, node)];
|
|
401
|
+
}
|
|
402
|
+
case 'effect':
|
|
403
|
+
return this.effect(item);
|
|
404
|
+
case 'id': {
|
|
405
|
+
// Svelte allows one $props.id() per component: further ids derive from it
|
|
406
|
+
if (this.firstId) {
|
|
407
|
+
this.idCount++;
|
|
408
|
+
return [this.decl(item.name, t.templateLiteral([t.templateElement({ raw: '', cooked: '' }), t.templateElement({ raw: `-${this.idCount}`, cooked: `-${this.idCount}` }, true)], [t.identifier(this.firstId)]))];
|
|
409
|
+
}
|
|
410
|
+
this.firstId = item.name;
|
|
411
|
+
return [this.decl(item.name, t.callExpression(t.memberExpression(t.identifier('$props'), t.identifier('id')), []))];
|
|
412
|
+
}
|
|
413
|
+
case 'hook':
|
|
414
|
+
return item.source === 'motion' ? this.motionHook(item) : this.localHook(item);
|
|
415
|
+
case 'statement':
|
|
416
|
+
return [this.r(item.node)];
|
|
417
|
+
case 'expose':
|
|
418
|
+
return this.expose(item.object);
|
|
419
|
+
case 'forward':
|
|
420
|
+
// the element is bound to the `ref` prop (see propsDeclaration)
|
|
421
|
+
return [];
|
|
422
|
+
case 'handle':
|
|
423
|
+
return this.handle(item);
|
|
424
|
+
case 'context':
|
|
425
|
+
// the provider's getter, called in a reactive scope: the value follows the provider (see shared/context)
|
|
426
|
+
return [this.decl(item.name, t.callExpression(t.memberExpression(t.identifier('$derived'), t.identifier('by')), [t.callExpression(t.memberExpression(t.identifier(item.context), t.identifier('get')), [])]))];
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
/** `Ctx.set(() => value)` for each provider the markup had, after every read (a component reads its parent's value). */
|
|
430
|
+
provides(comp) {
|
|
431
|
+
return comp.provides.flatMap((p) => {
|
|
432
|
+
const set = (value) => t.expressionStatement(t.callExpression(t.memberExpression(t.identifier(p.context.local), t.identifier('set')), [t.arrowFunctionExpression([], value)]));
|
|
433
|
+
if (!p.when)
|
|
434
|
+
return [set(this.r(p.value))];
|
|
435
|
+
// a provider under a condition: its value while the condition holds, the one from above (a getter) otherwise
|
|
436
|
+
const above = this.alloc.alloc(`${p.context.local.charAt(0).toLowerCase()}${p.context.local.slice(1)}Above`);
|
|
437
|
+
this.alloc.reserve(above);
|
|
438
|
+
const read = t.callExpression(t.memberExpression(t.identifier(p.context.local), t.identifier('get')), []);
|
|
439
|
+
return [t.variableDeclaration('const', [t.variableDeclarator(t.identifier(above), read)]), set(t.conditionalExpression(this.r(p.when), this.r(p.value), t.callExpression(t.identifier(above), [])))];
|
|
440
|
+
});
|
|
441
|
+
}
|
|
442
|
+
/** A component the markup renders, by tag (set by the emitter, which knows the graph). */
|
|
443
|
+
childOf = () => null;
|
|
444
|
+
/** The element a parent's `bind:ref` reaches, and the name the component's own code reads it by. */
|
|
445
|
+
forward = null;
|
|
446
|
+
/** A component another component of the graph renders (set by the emitter, which knows the graph). */
|
|
447
|
+
childOfAny = () => null;
|
|
448
|
+
/**
|
|
449
|
+
* The forwarded ref put on a child component whose handle members are all functions (see handleMemberNames), always
|
|
450
|
+
* rendered while this one is: the child bound to a local, and each member an exported function that calls the
|
|
451
|
+
* child's, so a parent's bind:this reaches the functions React's ref.current had.
|
|
452
|
+
*/
|
|
453
|
+
passed = null;
|
|
454
|
+
passedHandle(comp, tag) {
|
|
455
|
+
const child = this.childOf(tag);
|
|
456
|
+
if (!child || !comp.forwardRef || passesHandle(comp)?.node.tag !== tag || this.ir.items.some((i) => i.kind === 'expose' || i.kind === 'handle'))
|
|
457
|
+
return null;
|
|
458
|
+
const members = handleMemberNames(child, (parent, inner) => this.childOfAny(parent, inner));
|
|
459
|
+
if (!members?.length || !members.every((m) => m.fn && /^[A-Za-z_$][\w$]*$/.test(m.name) && !this.alloc.has(m.name)))
|
|
460
|
+
return null;
|
|
461
|
+
if (!this.passed) {
|
|
462
|
+
const name = this.alloc.alloc('inner');
|
|
463
|
+
this.alloc.reserve(name);
|
|
464
|
+
for (const m of members)
|
|
465
|
+
this.alloc.reserve(m.name);
|
|
466
|
+
this.passed = { name, tag, members: members.map((m) => m.name) };
|
|
467
|
+
}
|
|
468
|
+
return this.passed.name;
|
|
469
|
+
}
|
|
470
|
+
/** The forwarded ref put on one of several branch children (see handle-branches.ts): the local each branch binds. */
|
|
471
|
+
branchPassed = null;
|
|
472
|
+
passedBranch(comp, tag) {
|
|
473
|
+
if (!comp.forwardRef || this.ir.items.some((i) => i.kind === 'expose' || i.kind === 'handle') || this.passed)
|
|
474
|
+
return null;
|
|
475
|
+
const targets = branchTargets(comp);
|
|
476
|
+
if (!targets?.some((n) => n.tag === tag))
|
|
477
|
+
return null;
|
|
478
|
+
const childOf = (parent, inner) => (parent === comp ? this.childOf(inner) : this.childOfAny(parent, inner));
|
|
479
|
+
if (!this.branchPassed) {
|
|
480
|
+
const members = reachedMembers(comp, childOf);
|
|
481
|
+
const every = membersInEvery(comp, childOf);
|
|
482
|
+
if (!members?.length || !every || !members.every((m) => m.fn && /^[A-Za-z_$][\w$]*$/.test(m.name) && !this.alloc.has(m.name)))
|
|
483
|
+
return null;
|
|
484
|
+
const name = this.alloc.alloc('inner');
|
|
485
|
+
this.alloc.reserve(name);
|
|
486
|
+
for (const m of members)
|
|
487
|
+
this.alloc.reserve(m.name);
|
|
488
|
+
this.branchPassed = { name, tags: [...new Set(targets.map((n) => n.tag))], members: every };
|
|
489
|
+
}
|
|
490
|
+
return this.branchPassed.name;
|
|
491
|
+
}
|
|
492
|
+
/** Why a forwarded ref put on a child component is not passed on. */
|
|
493
|
+
forwardProblem(tag) {
|
|
494
|
+
const child = this.childOf(tag);
|
|
495
|
+
if (!child)
|
|
496
|
+
return `<${tag}> is not a component of this conversion, so what its ref holds is unknown; a Svelte parent's bind:ref holds this component's element only.`;
|
|
497
|
+
if (forwardsElement(child))
|
|
498
|
+
return `<${tag}> binds its element to its own \`ref\` prop; a Svelte parent's bind:ref holds this component's element only.`;
|
|
499
|
+
return `a Svelte parent's bind:this reaches this component's exports only (the ref is passed on to one component that is always rendered and whose handle members are all functions).`;
|
|
500
|
+
}
|
|
501
|
+
/** `let inner = $state.raw<…>()` and one exported function per member of the child's handle (see passedHandle). */
|
|
502
|
+
passStatements() {
|
|
503
|
+
if (this.branchPassed)
|
|
504
|
+
return this.branchStatements(this.branchPassed);
|
|
505
|
+
if (!this.passed)
|
|
506
|
+
return [];
|
|
507
|
+
const { name, tag, members } = this.passed;
|
|
508
|
+
const exportsType = t.tsTypeReference(t.identifier('ReturnType'), t.tsTypeParameterInstantiation([t.tsTypeQuery(t.identifier(tag))]));
|
|
509
|
+
const out = [this.decl(name, typedCall('$state.raw', exportsType, []), 'let')];
|
|
510
|
+
for (const m of members) {
|
|
511
|
+
const args = t.restElement(t.identifier('args'));
|
|
512
|
+
args.typeAnnotation = t.tsTypeAnnotation(t.tsTypeReference(t.identifier('Parameters'), t.tsTypeParameterInstantiation([t.tsIndexedAccessType(t.cloneNode(exportsType), t.tsLiteralType(t.stringLiteral(m)))])));
|
|
513
|
+
// the child is bound while this component is mounted, which is when a parent can call it
|
|
514
|
+
const missing = t.ifStatement(t.unaryExpression('!', t.identifier(name)), t.throwStatement(t.newExpression(t.identifier('Error'), [t.stringLiteral(`${m}: <${tag}> is not mounted`)])));
|
|
515
|
+
const call = t.callExpression(t.memberExpression(t.identifier(name), t.identifier(m)), [t.spreadElement(t.identifier('args'))]);
|
|
516
|
+
out.push(t.exportNamedDeclaration(t.functionDeclaration(t.identifier(m), [args], t.blockStatement([missing, t.returnStatement(call)]))));
|
|
517
|
+
}
|
|
518
|
+
return out;
|
|
519
|
+
}
|
|
520
|
+
/**
|
|
521
|
+
* `let inner = $state.raw<ReturnType<typeof A> | ReturnType<typeof B>>()`, bound by every branch, and each member a
|
|
522
|
+
* getter on this component's exports: `const m = $derived(inner?.m)`, or `inner && 'm' in inner ? inner.m : undefined`
|
|
523
|
+
* for a member only some of the children have (see handle-branches.ts).
|
|
524
|
+
*/
|
|
525
|
+
branchStatements({ name, tags, members }) {
|
|
526
|
+
const exportsOf = (tag) => t.tsTypeReference(t.identifier('ReturnType'), t.tsTypeParameterInstantiation([t.tsTypeQuery(t.identifier(tag))]));
|
|
527
|
+
const type = tags.length > 1 ? t.tsUnionType(tags.map(exportsOf)) : exportsOf(tags[0] ?? '');
|
|
528
|
+
const out = [this.decl(name, typedCall('$state.raw', type, []), 'let')];
|
|
529
|
+
for (const [m, every] of members) {
|
|
530
|
+
const read = t.memberExpression(t.identifier(name), t.identifier(m));
|
|
531
|
+
const value = every
|
|
532
|
+
? t.optionalMemberExpression(t.identifier(name), t.identifier(m), false, true)
|
|
533
|
+
: t.conditionalExpression(t.logicalExpression('&&', t.identifier(name), t.binaryExpression('in', t.stringLiteral(m), t.identifier(name))), read, t.identifier('undefined'));
|
|
534
|
+
out.push(this.decl(m, t.callExpression(t.identifier('$derived'), [value])));
|
|
535
|
+
}
|
|
536
|
+
out.push(t.exportNamedDeclaration(null, [...members.keys()].map((m) => t.exportSpecifier(t.identifier(m), t.identifier(m)))));
|
|
537
|
+
return out;
|
|
538
|
+
}
|
|
539
|
+
/**
|
|
540
|
+
* A handle that is not an object literal: held once (`$derived` when it reads reactive values), and each member a
|
|
541
|
+
* parent reaches is an exported function that calls the current handle's (an exported value would be a snapshot).
|
|
542
|
+
*/
|
|
543
|
+
handle(item) {
|
|
544
|
+
const members = handleMembers(item, this.ir, this.ctx);
|
|
545
|
+
if (!members) {
|
|
546
|
+
this.warn('imperative-handle', 'useImperativeHandle builds its handle from something whose members are not visible (a hook result, a parameter): give the handle a type (`useImperativeHandle<Handle>`, `forwardRef<Handle, Props>`) or an object literal.', 'error');
|
|
547
|
+
return [];
|
|
548
|
+
}
|
|
549
|
+
const reactive = readsReactive(item.value, this.ir);
|
|
550
|
+
const written = handleType(item, this.ir);
|
|
551
|
+
let type = this.type(written);
|
|
552
|
+
// members the type marks optional that the handle always has (`isReady?: () => boolean`, written in the literal):
|
|
553
|
+
// typed as present, `Handle & Required<Pick<Handle, 'isReady'>>`, so the exported function reads them as React's
|
|
554
|
+
// handle holds them
|
|
555
|
+
const declared = written ? this.ctx.types.members(written, this.ctx.sourceFile) : null;
|
|
556
|
+
const present = type && declared ? members.filter((m) => m.always && declared.get(m.name)?.optional) : [];
|
|
557
|
+
if (type && present.length) {
|
|
558
|
+
const keys = t.tsUnionType(present.map((m) => t.tsLiteralType(t.stringLiteral(m.name))));
|
|
559
|
+
const pick = t.tsTypeReference(t.identifier('Pick'), t.tsTypeParameterInstantiation([t.cloneNode(type, true), present.length > 1 ? keys : (keys.types[0] ?? keys)]));
|
|
560
|
+
type = t.tsIntersectionType([type, t.tsTypeReference(t.identifier('Required'), t.tsTypeParameterInstantiation([pick]))]);
|
|
561
|
+
}
|
|
562
|
+
if (!type && members.some((m) => !m.always)) {
|
|
563
|
+
this.warn('imperative-handle', `The handle has ${members.filter((m) => !m.always).map((m) => m.name).join(', ')} in some of its forms only: give it a type (\`useImperativeHandle<Handle>\`, \`forwardRef<Handle, Props>\`) so the exported functions can be typed.`, 'error');
|
|
564
|
+
return [];
|
|
565
|
+
}
|
|
566
|
+
const raw = this.r(item.value);
|
|
567
|
+
const handle = this.alloc.alloc('handle');
|
|
568
|
+
this.alloc.reserve(handle);
|
|
569
|
+
const init = !reactive ? handleValue(raw) : t.isBlockStatement(raw) ? typedCall('$derived.by', type, [t.arrowFunctionExpression([], raw)]) : this.rune('$derived', [raw], type);
|
|
570
|
+
const id = t.identifier(handle);
|
|
571
|
+
if (!reactive && type)
|
|
572
|
+
id.typeAnnotation = t.tsTypeAnnotation(type);
|
|
573
|
+
const out = [this.decl(id, init)];
|
|
574
|
+
const exportAs = (local, name) => t.exportNamedDeclaration(null, [t.exportSpecifier(t.identifier(local), t.identifier(name))]);
|
|
575
|
+
for (const m of members) {
|
|
576
|
+
if (!/^[A-Za-z_$][\w$]*$/.test(m.name)) {
|
|
577
|
+
this.warn('imperative-handle', `The handle member "${m.name}" is not a name a Svelte component can export.`, 'error');
|
|
578
|
+
continue;
|
|
579
|
+
}
|
|
580
|
+
const local = this.alloc.has(m.name) ? this.alloc.alloc(`${m.name}Handle`) : m.name;
|
|
581
|
+
this.alloc.reserve(local);
|
|
582
|
+
const read = t.memberExpression(t.identifier(handle), t.identifier(m.name));
|
|
583
|
+
let decl;
|
|
584
|
+
if (m.fn) {
|
|
585
|
+
// typed by the handle's own member, through `NonNullable` where one of its forms lacks it
|
|
586
|
+
const member = t.tsTypeQuery(t.tsQualifiedName(t.identifier(handle), t.identifier(m.name)));
|
|
587
|
+
const fnType = m.always ? member : t.tsTypeReference(t.identifier('NonNullable'), t.tsTypeParameterInstantiation([member]));
|
|
588
|
+
const args = t.restElement(t.identifier('args'));
|
|
589
|
+
args.typeAnnotation = t.tsTypeAnnotation(t.tsTypeReference(t.identifier('Parameters'), t.tsTypeParameterInstantiation([fnType])));
|
|
590
|
+
const call = m.always ? t.callExpression(read, [t.spreadElement(t.identifier('args'))]) : t.optionalCallExpression(read, [t.spreadElement(t.identifier('args'))], true);
|
|
591
|
+
decl = t.functionDeclaration(t.identifier(local), [args], t.blockStatement([t.returnStatement(call)]));
|
|
592
|
+
}
|
|
593
|
+
else if (!reactive)
|
|
594
|
+
decl = t.variableDeclaration('const', [t.variableDeclarator(t.identifier(local), read)]);
|
|
595
|
+
else {
|
|
596
|
+
this.warn('imperative-handle', `The handle member "${m.name}" is a value that follows reactive state: a Svelte component exports functions and constants, so it has no live form (make it a function).`, 'error');
|
|
597
|
+
continue;
|
|
598
|
+
}
|
|
599
|
+
out.push(local === m.name ? t.exportNamedDeclaration(decl) : decl);
|
|
600
|
+
if (local !== m.name)
|
|
601
|
+
out.push(exportAs(local, m.name));
|
|
602
|
+
}
|
|
603
|
+
return out;
|
|
604
|
+
}
|
|
605
|
+
/** The handle's members as component exports (a parent reaches them through bind:this). */
|
|
606
|
+
expose(obj) {
|
|
607
|
+
const out = [];
|
|
608
|
+
const exportAs = (local, name) => t.exportNamedDeclaration(null, [t.exportSpecifier(t.identifier(local), t.identifier(name))]);
|
|
609
|
+
for (const p of this.r(obj).properties) {
|
|
610
|
+
const name = (t.isObjectMethod(p) || t.isObjectProperty(p)) && t.isIdentifier(p.key) ? p.key.name : null;
|
|
611
|
+
// { focus }: the component's own function, exported as it is
|
|
612
|
+
if (name && t.isObjectProperty(p) && t.isIdentifier(p.value, { name })) {
|
|
613
|
+
out.push(exportAs(name, name));
|
|
614
|
+
continue;
|
|
615
|
+
}
|
|
616
|
+
// a member named like a prop or a local (open, and an `open` prop) is declared under a free name and exported as itself
|
|
617
|
+
const local = name && this.alloc.has(name) ? this.alloc.alloc(`${name}Handle`) : name;
|
|
618
|
+
if (name && local === name)
|
|
619
|
+
this.alloc.reserve(name);
|
|
620
|
+
let decl = null;
|
|
621
|
+
if (local && t.isObjectMethod(p) && p.kind === 'method')
|
|
622
|
+
decl = t.functionDeclaration(t.identifier(local), p.params, p.body, p.generator, p.async);
|
|
623
|
+
else if (local && t.isObjectProperty(p) && t.isExpression(p.value))
|
|
624
|
+
decl = t.variableDeclaration('const', [t.variableDeclarator(t.identifier(local), p.value)]);
|
|
625
|
+
if (!decl || !name || !local) {
|
|
626
|
+
this.warn('imperative-handle', 'A computed or spread member of useImperativeHandle is not exported.', 'error');
|
|
627
|
+
continue;
|
|
628
|
+
}
|
|
629
|
+
if (local === name && (t.isFunctionDeclaration(decl) || t.isVariableDeclaration(decl)))
|
|
630
|
+
out.push(t.exportNamedDeclaration(decl));
|
|
631
|
+
else
|
|
632
|
+
out.push(decl, exportAs(local, name));
|
|
633
|
+
}
|
|
634
|
+
return out;
|
|
635
|
+
}
|
|
636
|
+
motionHook(item) {
|
|
637
|
+
const call = this.r(item.call);
|
|
638
|
+
const mapped = item.hook === 'useTransform' && call.arguments.length >= 3 ? 'mapValue' : SVELTE_MOTION_HOOKS[item.hook];
|
|
639
|
+
if (item.hook === 'useReducedMotion') {
|
|
640
|
+
this.warn('motion-hook', 'useReducedMotion reads the media query once, at setup.', 'info');
|
|
641
|
+
const media = t.memberExpression(t.callExpression(t.memberExpression(t.identifier('window'), t.identifier('matchMedia')), [t.stringLiteral('(prefers-reduced-motion: reduce)')]), t.identifier('matches'));
|
|
642
|
+
return item.id ? [this.decl(item.id, media)] : [];
|
|
643
|
+
}
|
|
644
|
+
const plan = motionHookPlan(item.hook, item.call, item.id);
|
|
645
|
+
if (typeof plan === 'string') {
|
|
646
|
+
this.warn('motion-hook', `${plan}: not converted.`, 'error', item.call.loc?.start.line);
|
|
647
|
+
return [];
|
|
648
|
+
}
|
|
649
|
+
if (plan)
|
|
650
|
+
return this.motionPlan(plan);
|
|
651
|
+
if (item.hook === 'useAnimationFrame')
|
|
652
|
+
return this.animationFrame(item);
|
|
653
|
+
if (!mapped || item.hook === 'useAnimate') {
|
|
654
|
+
this.warn('motion-hook', `${item.hook} has no drop-in counterpart in motion for Svelte; it is not converted.`, 'error');
|
|
655
|
+
return [];
|
|
656
|
+
}
|
|
657
|
+
// Framer's useTransform and useSpring read their arguments again on every render (new ranges, a new source, a new
|
|
658
|
+
// spring config, what a transform function reads, take effect at once); motion's functions read them when the value
|
|
659
|
+
// is made (a transform function, when its source next changes). useMotionValue reads its initial value once in both.
|
|
660
|
+
if (item.hook === 'useTransform' || item.hook === 'useSpring') {
|
|
661
|
+
const names = reactiveReads(item.call, this.ir);
|
|
662
|
+
const one = names.length === 1;
|
|
663
|
+
if (names.length)
|
|
664
|
+
this.warn('hook-args-once', `${item.hook}() is given ${names.map((n) => `"${n}"`).join(', ')}, which change${one ? 's' : ''} over the component's life; React's hook reads ${one ? 'it' : 'them'} again on every render, motion's ${mapped}() reads ${one ? 'it' : 'them'} when the value is made${mapped === 'transformValue' ? ' and when its source changes' : ''}, so a later change does not reach the value as it does in React.`, 'warning', item.call.loc?.start.line);
|
|
665
|
+
}
|
|
666
|
+
// (`const motionValue = useMotionValue(0)`: the function is imported under a free name)
|
|
667
|
+
call.callee = t.identifier(this.motionFn(mapped));
|
|
668
|
+
// useSpring(0) is MotionValue<number> by React's overloads; springValue's type parameter would keep the literal (0)
|
|
669
|
+
const source = call.arguments[0];
|
|
670
|
+
const literal = t.isUnaryExpression(source, { operator: '-' }) ? source.argument : source;
|
|
671
|
+
if (mapped === 'springValue' && !call.typeParameters && (t.isNumericLiteral(literal) || t.isStringLiteral(literal) || t.isTemplateLiteral(literal))) {
|
|
672
|
+
call.typeParameters = t.tsTypeParameterInstantiation([t.isNumericLiteral(literal) ? t.tsNumberKeyword() : t.tsStringKeyword()]);
|
|
673
|
+
}
|
|
674
|
+
return item.id ? [this.decl(item.id, call)] : [t.expressionStatement(call)];
|
|
675
|
+
}
|
|
676
|
+
/**
|
|
677
|
+
* useMotionTemplate`…${x}…` over motion's transformValue: `transformValue(() => \`…${x.get()}…\`)`, which follows the
|
|
678
|
+
* motion values it reads, as Framer's template follows its values. A part that is not a motion value is written as
|
|
679
|
+
* it is when it reads nothing reactive; one that reads props or state would be fixed at setup in transformValue
|
|
680
|
+
* (Framer rebuilds the text on render), so it is refused, named.
|
|
681
|
+
*/
|
|
682
|
+
motionTemplate(name, tagged) {
|
|
683
|
+
const quasi = tagged.quasi;
|
|
684
|
+
const line = tagged.loc?.start.line;
|
|
685
|
+
const parts = [];
|
|
686
|
+
for (const e of quasi.expressions) {
|
|
687
|
+
if (!t.isExpression(e)) {
|
|
688
|
+
this.warn('motion-hook', 'useMotionTemplate holds a type in its template: not converted.', 'error', line);
|
|
689
|
+
return [];
|
|
690
|
+
}
|
|
691
|
+
const bound = t.isIdentifier(e) ? this.ir.refs.get(e) : undefined;
|
|
692
|
+
if (bound && holdsMotionValue(this.ir, bound)) {
|
|
693
|
+
parts.push(t.callExpression(t.memberExpression(t.identifier(bound), t.identifier('get')), []));
|
|
694
|
+
continue;
|
|
695
|
+
}
|
|
696
|
+
if (readsReactive(e, this.ir)) {
|
|
697
|
+
this.warn('motion-hook', `useMotionTemplate reads ${printExpr(e)}, a reactive value that is not a motion value: motion's transformValue would read it once, while Framer rebuilds the text when it changes. Not converted.`, 'error', line);
|
|
698
|
+
return [];
|
|
699
|
+
}
|
|
700
|
+
parts.push(this.r(e));
|
|
701
|
+
}
|
|
702
|
+
const text = t.templateLiteral(quasi.quasis.map((q) => t.cloneNode(q)), parts);
|
|
703
|
+
return [this.decl(name, t.callExpression(t.identifier(this.motionFn('transformValue')), [t.arrowFunctionExpression([], text)]))];
|
|
704
|
+
}
|
|
705
|
+
/** The local name of a `motion` function, imported under a free name when the component has one of its own. */
|
|
706
|
+
motionFn(name) {
|
|
707
|
+
const known = this.motionFns.get(name);
|
|
708
|
+
if (known)
|
|
709
|
+
return known;
|
|
710
|
+
const local = this.alloc.has(name) ? this.alloc.alloc(`motion${name.charAt(0).toUpperCase()}${name.slice(1)}`) : name;
|
|
711
|
+
this.alloc.reserve(local);
|
|
712
|
+
this.motionFns.set(name, local);
|
|
713
|
+
this.imports.named('motion', name, local);
|
|
714
|
+
return local;
|
|
715
|
+
}
|
|
716
|
+
/** `motion` functions by name → the local name the file imports each under */
|
|
717
|
+
motionFns = new Map();
|
|
718
|
+
/**
|
|
719
|
+
* useInView and useScroll over `motion`'s inView and scroll, as Framer writes them: started in an effect after render
|
|
720
|
+
* (`ref.current` is the element then), stopped by the effect's cleanup; the effect re-runs when a reactive option it
|
|
721
|
+
* reads changes, as Framer's effect does on its dependencies. useInView's value is `$state` (the markup and effects
|
|
722
|
+
* read it, as React state); useScroll's values are `motionValue`s with no state around them.
|
|
723
|
+
*/
|
|
724
|
+
/**
|
|
725
|
+
* Framer's useAnimationFrame(callback): the callback on each frame's update step, given the time since the first frame
|
|
726
|
+
* and the frame's delta. Framer adds it in an effect (`frame.update(tick, true)`, `cancelFrame` on cleanup) and keeps
|
|
727
|
+
* the first frame's time in a ref, so a new callback goes on counting from it: here the time is a plain `let` of the
|
|
728
|
+
* component and the effect re-adds the callback when a value it reads to make it changes. The callback reads state as
|
|
729
|
+
* it is when it runs, as React's newest callback does.
|
|
730
|
+
*/
|
|
731
|
+
animationFrame(item) {
|
|
732
|
+
const callback = item.call.arguments[0];
|
|
733
|
+
if (item.id || item.call.arguments.length !== 1 || !callback || !t.isExpression(callback)) {
|
|
734
|
+
this.warn('motion-hook', 'useAnimationFrame is given other than one callback, or its value is kept: not converted.', 'error', item.call.loc?.start.line);
|
|
735
|
+
return [];
|
|
736
|
+
}
|
|
737
|
+
const frame = this.motionFn('frame');
|
|
738
|
+
const cancel = this.motionFn('cancelFrame');
|
|
739
|
+
const fn = this.r(callback);
|
|
740
|
+
const named = this.alloc.alloc('frameCallback');
|
|
741
|
+
const start = this.alloc.alloc('firstFrame');
|
|
742
|
+
const tick = this.alloc.alloc('tick');
|
|
743
|
+
const data = t.objectPattern([t.objectProperty(t.identifier('timestamp'), t.identifier('timestamp'), false, true), t.objectProperty(t.identifier('delta'), t.identifier('delta'), false, true)]);
|
|
744
|
+
data.typeAnnotation = t.tsTypeAnnotation(t.tsTypeLiteral(['timestamp', 'delta'].map((k) => t.tsPropertySignature(t.identifier(k), t.tsTypeAnnotation(t.tsNumberKeyword())))));
|
|
745
|
+
const tickBody = t.blockStatement([
|
|
746
|
+
t.ifStatement(t.unaryExpression('!', t.identifier(start)), t.expressionStatement(t.assignmentExpression('=', t.identifier(start), t.identifier('timestamp')))),
|
|
747
|
+
t.expressionStatement(t.callExpression(t.identifier(named), [t.binaryExpression('-', t.identifier('timestamp'), t.identifier(start)), t.identifier('delta')])),
|
|
748
|
+
]);
|
|
749
|
+
// typed as Framer types the callback (time, delta), which also types the parameters the source leaves to inference
|
|
750
|
+
const callbackId = t.identifier(named);
|
|
751
|
+
const number = (name) => Object.assign(t.identifier(name), { typeAnnotation: t.tsTypeAnnotation(t.tsNumberKeyword()) });
|
|
752
|
+
callbackId.typeAnnotation = t.tsTypeAnnotation(t.tsFunctionType(null, [number('time'), number('delta')], t.tsTypeAnnotation(t.tsVoidKeyword())));
|
|
753
|
+
const body = t.blockStatement([
|
|
754
|
+
t.variableDeclaration('const', [t.variableDeclarator(callbackId, fn)]),
|
|
755
|
+
this.decl(tick, t.arrowFunctionExpression([data], tickBody)),
|
|
756
|
+
t.expressionStatement(t.callExpression(t.memberExpression(t.identifier(frame), t.identifier('update')), [t.identifier(tick), t.booleanLiteral(true)])),
|
|
757
|
+
t.returnStatement(t.arrowFunctionExpression([], t.callExpression(t.identifier(cancel), [t.identifier(tick)]))),
|
|
758
|
+
]);
|
|
759
|
+
return [this.decl(start, t.numericLiteral(0), 'let'), t.expressionStatement(t.callExpression(t.identifier('$effect'), [t.arrowFunctionExpression([], body)]))];
|
|
760
|
+
}
|
|
761
|
+
motionPlan(plan) {
|
|
762
|
+
const element = (ref) => t.logicalExpression('??', this.r(t.memberExpression(bareExpression(ref), t.identifier('current'))), t.identifier('undefined'));
|
|
763
|
+
const effect = (body) => t.expressionStatement(t.callExpression(t.identifier('$effect'), [t.arrowFunctionExpression([], t.blockStatement(body))]));
|
|
764
|
+
if (plan.hook === 'useInView') {
|
|
765
|
+
const inView = this.motionFn('inView');
|
|
766
|
+
const initial = plan.options.get('initial');
|
|
767
|
+
const set = (value) => t.expressionStatement(t.assignmentExpression('=', t.identifier(plan.name), t.booleanLiteral(value)));
|
|
768
|
+
const body = [];
|
|
769
|
+
const target = this.alloc.alloc('element');
|
|
770
|
+
body.push(this.decl(target, this.r(t.memberExpression(plan.ref, t.identifier('current')))), t.ifStatement(t.unaryExpression('!', t.identifier(target)), t.returnStatement()));
|
|
771
|
+
// Framer: `setInView(true); return once ? undefined : () => setInView(false)`; a `once` that is not written out
|
|
772
|
+
// is read in the effect, so a change re-runs it as it re-runs Framer's
|
|
773
|
+
const once = plan.options.get('once');
|
|
774
|
+
const leave = t.arrowFunctionExpression([], t.blockStatement([set(false)]));
|
|
775
|
+
let after = [t.returnStatement(leave)];
|
|
776
|
+
const written = once ? bareExpression(once) : null;
|
|
777
|
+
if (t.isBooleanLiteral(written)) {
|
|
778
|
+
if (written.value)
|
|
779
|
+
after = [];
|
|
780
|
+
}
|
|
781
|
+
else if (once) {
|
|
782
|
+
const local = this.alloc.alloc('once');
|
|
783
|
+
body.push(this.decl(local, this.r(once)));
|
|
784
|
+
after = [t.returnStatement(t.conditionalExpression(t.identifier(local), t.identifier('undefined'), leave))];
|
|
785
|
+
}
|
|
786
|
+
const options = [];
|
|
787
|
+
const root = plan.options.get('root');
|
|
788
|
+
if (root)
|
|
789
|
+
options.push(t.objectProperty(t.identifier('root'), element(root)));
|
|
790
|
+
for (const key of ['margin', 'amount']) {
|
|
791
|
+
const value = plan.options.get(key);
|
|
792
|
+
if (value)
|
|
793
|
+
options.push(t.objectProperty(t.identifier(key), this.r(value)));
|
|
794
|
+
}
|
|
795
|
+
const enter = t.arrowFunctionExpression([], t.blockStatement([set(true), ...after]));
|
|
796
|
+
body.push(t.returnStatement(t.callExpression(t.identifier(inView), [t.identifier(target), enter, ...(options.length ? [t.objectExpression(options)] : [])])));
|
|
797
|
+
return [this.decl(plan.name, this.rune('$state', [initial ? this.r(initial) : t.booleanLiteral(false)]), 'let'), effect(body)];
|
|
798
|
+
}
|
|
799
|
+
const motionValue = this.motionFn('motionValue');
|
|
800
|
+
const scroll = this.motionFn('scroll');
|
|
801
|
+
const out = [...plan.values.values()].map((name) => this.decl(name, t.callExpression(t.identifier(motionValue), [t.numericLiteral(0)])));
|
|
802
|
+
// Framer: `scroll((_progress, { x, y }) => { scrollX.set(x.current); … })`, for the values the component takes out
|
|
803
|
+
const axes = [...new Set([...plan.values.keys()].map((k) => SCROLL_VALUES.get(k)?.axis ?? 'y'))].sort();
|
|
804
|
+
const info = t.objectPattern(axes.map((a) => t.objectProperty(t.identifier(a), t.identifier(a), false, true)));
|
|
805
|
+
const sets = [...plan.values].map(([key, name]) => {
|
|
806
|
+
const how = SCROLL_VALUES.get(key);
|
|
807
|
+
return t.expressionStatement(t.callExpression(t.memberExpression(t.identifier(name), t.identifier('set')), [t.memberExpression(t.identifier(how?.axis ?? 'y'), t.identifier(how?.field ?? 'progress'))]));
|
|
808
|
+
});
|
|
809
|
+
const options = [];
|
|
810
|
+
for (const key of ['target', 'container']) {
|
|
811
|
+
const ref = plan.options.get(key);
|
|
812
|
+
if (ref)
|
|
813
|
+
options.push(t.objectProperty(t.identifier(key), element(ref)));
|
|
814
|
+
}
|
|
815
|
+
for (const key of ['offset', 'axis']) {
|
|
816
|
+
const value = plan.options.get(key);
|
|
817
|
+
if (value)
|
|
818
|
+
options.push(t.objectProperty(t.identifier(key), this.r(value)));
|
|
819
|
+
}
|
|
820
|
+
const onScroll = t.arrowFunctionExpression([t.identifier('_progress'), info], t.blockStatement(sets));
|
|
821
|
+
out.push(effect([t.returnStatement(t.callExpression(t.identifier(scroll), [onScroll, ...(options.length ? [t.objectExpression(options)] : [])]))]));
|
|
822
|
+
return out;
|
|
823
|
+
}
|
|
824
|
+
/** `const { a, run } = useThing()`: the call once, reactive members through `$derived`, functions as they are. */
|
|
825
|
+
localHook(item) {
|
|
826
|
+
const call = this.r(item.call);
|
|
827
|
+
if (!item.live)
|
|
828
|
+
this.checkHookArgs(item.call, item.hook);
|
|
829
|
+
if (!item.id)
|
|
830
|
+
return [t.expressionStatement(call)];
|
|
831
|
+
const names = patternNames(item.id);
|
|
832
|
+
const reactive = names.filter((n) => this.ir.bindings.get(n)?.reactive);
|
|
833
|
+
if (!reactive.length)
|
|
834
|
+
return [this.decl(item.id, call)];
|
|
835
|
+
const holder = this.alloc.alloc(item.hook.replace(/^use/, '').replace(/^./, (c) => c.toLowerCase()) || 'hook');
|
|
836
|
+
const out = [this.decl(holder, call)];
|
|
837
|
+
if (t.isIdentifier(item.id)) {
|
|
838
|
+
out.push(this.decl(item.id.name, this.rune('$derived', [t.memberExpression(t.identifier(holder), t.identifier('value'))])));
|
|
839
|
+
return out;
|
|
840
|
+
}
|
|
841
|
+
const plain = [];
|
|
842
|
+
const entries = [];
|
|
843
|
+
if (t.isObjectPattern(item.id)) {
|
|
844
|
+
for (const p of item.id.properties) {
|
|
845
|
+
if (t.isObjectProperty(p) && t.isIdentifier(p.key)) {
|
|
846
|
+
const local = t.isIdentifier(p.value) ? p.value.name : t.isAssignmentPattern(p.value) && t.isIdentifier(p.value.left) ? p.value.left.name : null;
|
|
847
|
+
if (local)
|
|
848
|
+
entries.push([p.key.name, local]);
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
else if (t.isArrayPattern(item.id)) {
|
|
853
|
+
item.id.elements.forEach((el, i) => {
|
|
854
|
+
if (t.isIdentifier(el))
|
|
855
|
+
entries.push([String(i), el.name]);
|
|
856
|
+
});
|
|
857
|
+
}
|
|
858
|
+
for (const [key, local] of entries) {
|
|
859
|
+
const access = /^\d+$/.test(key) ? t.memberExpression(t.identifier(holder), t.numericLiteral(Number(key)), true) : t.memberExpression(t.identifier(holder), t.identifier(key));
|
|
860
|
+
if (reactive.includes(local))
|
|
861
|
+
out.push(this.decl(local, this.rune('$derived', [access])));
|
|
862
|
+
else
|
|
863
|
+
plain.push(t.objectProperty(t.identifier(key), t.identifier(local), false, key === local));
|
|
864
|
+
}
|
|
865
|
+
if (plain.length) {
|
|
866
|
+
if (t.isArrayPattern(item.id))
|
|
867
|
+
for (const p of plain)
|
|
868
|
+
out.push(this.decl(p.value.name, t.memberExpression(t.identifier(holder), t.numericLiteral(Number(p.key.name)), true)));
|
|
869
|
+
else
|
|
870
|
+
out.push(this.decl(t.objectPattern(plain), t.identifier(holder)));
|
|
871
|
+
}
|
|
872
|
+
return out;
|
|
873
|
+
}
|
|
874
|
+
checkHookArgs(call, hook) {
|
|
875
|
+
const reactiveIn = (e) => {
|
|
876
|
+
if (t.isFunction(e))
|
|
877
|
+
return false;
|
|
878
|
+
if (t.isObjectExpression(e))
|
|
879
|
+
return e.properties.some((p) => (t.isObjectProperty(p) ? reactiveIn(p.value) : t.isSpreadElement(p) ? reactiveIn(p.argument) : false));
|
|
880
|
+
for (const name of bindingsUsed(e, this.ir)) {
|
|
881
|
+
const binding = this.ir.bindings.get(name);
|
|
882
|
+
if (binding && (binding.kind === 'prop' || binding.kind === 'state' || binding.kind === 'reducer' || binding.kind === 'propsObject' || (binding.kind === 'derived' && binding.reactive)))
|
|
883
|
+
return true;
|
|
884
|
+
}
|
|
885
|
+
return false;
|
|
886
|
+
};
|
|
887
|
+
if (call.arguments.some((a) => reactiveIn(a))) {
|
|
888
|
+
this.warn('hook-args-once', `${hook}() is called with reactive values; it reads its arguments once at setup, so later prop or state changes do not reach it.`);
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
/**
|
|
892
|
+
* The layout effect after which the passive effects written before it are registered (see items()), or null when no
|
|
893
|
+
* useEffect comes before a useLayoutEffect. A custom hook called between them keeps its place, so its own effects
|
|
894
|
+
* would change order against the moved ones: that shape is said (effect-order), located at the hook's call.
|
|
895
|
+
*/
|
|
896
|
+
effectReorder() {
|
|
897
|
+
const items = this.ir.items;
|
|
898
|
+
// the first place passive effects may start: a useEffect, or a custom hook (whose effects run where it is called)
|
|
899
|
+
const first = items.findIndex((i) => (i.kind === 'effect' && i.phase === 'effect') || (i.kind === 'hook' && i.source === 'local'));
|
|
900
|
+
if (first < 0)
|
|
901
|
+
return null;
|
|
902
|
+
const hoisted = items.slice(first + 1).filter((i) => i.kind === 'effect' && i.phase === 'layout');
|
|
903
|
+
const before = items[first];
|
|
904
|
+
if (!hoisted.length || !before)
|
|
905
|
+
return null;
|
|
906
|
+
if (!EFFECT_ORDER_CHECKED.has(this.ir)) {
|
|
907
|
+
EFFECT_ORDER_CHECKED.add(this.ir);
|
|
908
|
+
// a custom hook passed over keeps its own layout effects in place: React runs them in source order among this
|
|
909
|
+
// component's, which the hoisted ones now precede; said when the hook has one (or cannot be looked into)
|
|
910
|
+
const last = items.indexOf(hoisted[hoisted.length - 1]);
|
|
911
|
+
for (const hook of items.slice(first, last)) {
|
|
912
|
+
if (hook.kind !== 'hook' || hook.source !== 'local')
|
|
913
|
+
continue;
|
|
914
|
+
const ir = this.hookIr(hook.hook);
|
|
915
|
+
if (ir && !ir.items.some((i) => i.kind === 'effect' && i.phase === 'layout'))
|
|
916
|
+
continue;
|
|
917
|
+
this.warn('effect-order', `${hook.hook} is called before a useLayoutEffect of this component and ${ir ? 'has a layout effect of its own' : 'cannot be looked into'}. React runs the layout effects in source order before any useEffect; the Svelte output registers this component's layout effects ahead of its useEffects and custom hooks to match, so a layout effect inside ${hook.hook} now runs after this component's later ones.`, 'warning', hook.call.loc?.start.line);
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
return { before, hoisted };
|
|
921
|
+
}
|
|
922
|
+
/** A custom hook of the conversion by its local name: declared in this file or imported from one of the conversion. */
|
|
923
|
+
hookIr(local) {
|
|
924
|
+
const mod = this.ctx.moduleOf?.(this.ctx.sourceFile) ?? null;
|
|
925
|
+
const own = mod?.hooks.find((h) => h.name === local);
|
|
926
|
+
if (own)
|
|
927
|
+
return own;
|
|
928
|
+
for (const d of mod?.imports ?? []) {
|
|
929
|
+
const spec = d.specifiers.find((x) => x.local.name === local);
|
|
930
|
+
if (!spec)
|
|
931
|
+
continue;
|
|
932
|
+
const file = resolveLocal(this.ctx.sourceFile, d.source.value, this.ctx.project);
|
|
933
|
+
const name = t.isImportSpecifier(spec) ? (t.isIdentifier(spec.imported) ? spec.imported.name : spec.imported.value) : null;
|
|
934
|
+
return file && name ? (this.ctx.moduleOf?.(file)?.hooks.find((h) => h.name === name) ?? null) : null;
|
|
935
|
+
}
|
|
936
|
+
return null;
|
|
937
|
+
}
|
|
938
|
+
effect(item) {
|
|
939
|
+
let body;
|
|
940
|
+
if (item.core && 'template' in this.ir) {
|
|
941
|
+
const comp = this.ir;
|
|
942
|
+
const core = buildCore(comp, item, item.core, (name) => this.ctx.oracle?.typeOf(this.ctx.sourceFile, comp.name, name) ?? null);
|
|
943
|
+
this.cores.push({ module: core, name: item.core.name });
|
|
944
|
+
const elementRef = item.core.elementRef;
|
|
945
|
+
const elBinding = comp.bindings.get(elementRef);
|
|
946
|
+
const element = elBinding?.escapes ? t.memberExpression(t.identifier(elementRef), t.identifier('current')) : t.identifier(elementRef);
|
|
947
|
+
body = core.call('svelte', (name) => t.identifier(name), t.tsNonNullExpression(element), (name) => this.boxFor(name), (name) => this.setterFn(name));
|
|
948
|
+
}
|
|
949
|
+
else
|
|
950
|
+
body = this.r(item.body);
|
|
951
|
+
// useLayoutEffect runs after React has written the DOM, before paint: Svelte's `$effect` runs then too (after the
|
|
952
|
+
// DOM update, in the same flush), where `$effect.pre` runs before the update and would measure the DOM as it was
|
|
953
|
+
// (VS6, 4 Dec: a layout effect that re-measured rows after a re-sort read the old rows). Render-time adjustments
|
|
954
|
+
// (phase 'render') run before the DOM update, as React computes them while rendering.
|
|
955
|
+
const effectRune = item.phase === 'render' ? '$effect.pre' : '$effect';
|
|
956
|
+
// a body that only returns its cleanup (`useEffect(() => subscribe(fn), [])`) stays an expression: `() => subscribe(fn)`
|
|
957
|
+
const only = body.body.length === 1 && t.isReturnStatement(body.body[0]) ? body.body[0].argument : null;
|
|
958
|
+
const callback = () => t.arrowFunctionExpression([], only ?? body);
|
|
959
|
+
if (item.deps === null)
|
|
960
|
+
return [t.expressionStatement(t.callExpression(t.identifier(effectRune), [callback()]))];
|
|
961
|
+
const sources = reactiveDeps(item.deps, this.ir).map((d) => this.r(d));
|
|
962
|
+
if (!sources.length)
|
|
963
|
+
return [t.expressionStatement(t.callExpression(t.identifier(this.api('onMount')), [callback()]))];
|
|
964
|
+
// re-run only when the listed dependencies change, as useEffect does: read them, run the body untracked
|
|
965
|
+
const reads = sources.map((s) => t.expressionStatement(s));
|
|
966
|
+
const untracked = t.returnStatement(t.callExpression(t.identifier(this.api('untrack')), [callback()]));
|
|
967
|
+
return [t.expressionStatement(t.callExpression(t.identifier(effectRune), [t.arrowFunctionExpression([], t.blockStatement([...reads, untracked]))]))];
|
|
968
|
+
}
|
|
969
|
+
boxFor(name) {
|
|
970
|
+
const b = this.ir.bindings.get(name);
|
|
971
|
+
if (b?.refKind === 'dom' && !b.escapes) {
|
|
972
|
+
return t.objectExpression([t.objectMethod('get', t.identifier('current'), [], t.blockStatement([t.returnStatement(t.identifier(name))]))]);
|
|
973
|
+
}
|
|
974
|
+
return t.identifier(name);
|
|
975
|
+
}
|
|
976
|
+
setterFn(name) {
|
|
977
|
+
const state = this.ir.bindings.get(name)?.state ?? name;
|
|
978
|
+
return t.arrowFunctionExpression([t.identifier('value')], t.assignmentExpression('=', t.identifier(state), t.identifier('value')));
|
|
979
|
+
}
|
|
980
|
+
/** The helpers the script declares, and the imports of those written once per conversion (`outPath`: the file's path). */
|
|
981
|
+
helperStatements(outPath) {
|
|
982
|
+
const out = [];
|
|
983
|
+
if (this.helpers.has('toStyleString')) {
|
|
984
|
+
out.push(...parseStatements(unitlessSource()));
|
|
985
|
+
out.push(...parseStatements("/**\n * React style objects as a style attribute: kebab-case names, px on numbers except unitless properties and custom\n * properties. A style string (the `style` a parent passes) is kept as it is; later parts win, as later keys of a spread do.\n */\nfunction toStyleString(...parts: (Record<string, unknown> | string | null | undefined)[]): string {\n return parts\n .flatMap((style) => {\n if (!style || typeof style === 'string') return style ? [style] : [];\n return Object.entries(style)\n .filter(([, value]) => value !== undefined && value !== null && value !== false && value !== '')\n .map(([key, value]) => {\n const name = key.startsWith('--') ? key : key.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`).replace(/^(webkit|moz|ms)-/, '-$1-');\n const css = typeof value === 'number' && value !== 0 && !key.startsWith('--') && !UNITLESS.has(key) ? `${value}px` : String(value);\n return `${name}: ${css}`;\n });\n })\n .join('; ');\n}"));
|
|
986
|
+
}
|
|
987
|
+
// an object of React DOM props spread onto an element, renamed when it arrives (dom-spread.ts)
|
|
988
|
+
if (this.helpers.has('domProps'))
|
|
989
|
+
out.push(...parseStatements(domPropsSource(this.helpers.has('domPropsSvg'))));
|
|
990
|
+
if (this.helpers.has('toStyleObject')) {
|
|
991
|
+
out.push(...parseStatements("/** A style attribute (`max-width: 4px; --tint: red`) as the object React's `style` was: camelCase names, values kept as written. */\nfunction toStyleObject(style: string | null | undefined): Record<string, string | number | undefined> {\n const out: Record<string, string | number | undefined> = {};\n // a `;` inside parentheses (`url(data:image/png;base64,...)`) does not end a declaration\n for (const declaration of (style ?? '').split(/;(?![^(]*\\))/)) {\n const colon = declaration.indexOf(':');\n if (colon < 1) continue;\n const name = declaration.slice(0, colon).trim();\n out[name.startsWith('--') ? name : name.replace(/^-(webkit|moz|ms)-/, (_, p: string) => `${p.charAt(0).toUpperCase()}${p.slice(1)}-`).replace(/-([a-z])/g, (_, c: string) => c.toUpperCase())] = declaration.slice(colon + 1).trim();\n }\n return out;\n}"));
|
|
992
|
+
}
|
|
993
|
+
// typed like a React style value (CSSProperties takes strings and numbers), so a style directive accepts the result
|
|
994
|
+
if (this.helpers.has('toPx'))
|
|
995
|
+
out.push(...parseStatements("const toPx = (value: string | number | null | undefined) => (typeof value === 'number' && value !== 0 ? `${value}px` : value);"));
|
|
996
|
+
// the motion action (and the exit transition) live in one file of the conversion, which this file imports
|
|
997
|
+
if (this.helpers.has('motion') || this.helpers.has('motionExit')) {
|
|
998
|
+
const source = importPath(outPath, this.ctx.helperPath?.(MOTION_HELPER_FILE) ?? MOTION_HELPER_FILE);
|
|
999
|
+
this.imports.named(source, MOTION_ACTION);
|
|
1000
|
+
if (this.helpers.has('motionEnter'))
|
|
1001
|
+
this.imports.named(source, MOTION_ENTER);
|
|
1002
|
+
if (this.helpers.has('motionExit'))
|
|
1003
|
+
this.imports.named(source, MOTION_EXIT);
|
|
1004
|
+
useMotionHelper(this.ctx.diagnostics, this.motion);
|
|
1005
|
+
}
|
|
1006
|
+
// M2: the layout and drag actions, from the conversion's motion-layout.ts
|
|
1007
|
+
const layoutNames = layoutActions(this);
|
|
1008
|
+
if (layoutNames.size) {
|
|
1009
|
+
const source = importPath(outPath, this.ctx.helperPath?.(LAYOUT_HELPER_FILE) ?? LAYOUT_HELPER_FILE);
|
|
1010
|
+
for (const name of layoutNames)
|
|
1011
|
+
this.imports.named(source, name);
|
|
1012
|
+
}
|
|
1013
|
+
if (this.portalName)
|
|
1014
|
+
out.push(...parseStatements(SVELTE_PORTAL_SOURCE.replace('function portal(', `function ${this.portalName}(`)));
|
|
1015
|
+
// elements held as data: their types and their renderer live in two files of the conversion, which this file imports
|
|
1016
|
+
if (this.markup && (this.markup.sites.length || this.markup.view)) {
|
|
1017
|
+
const source = importPath(outPath, this.ctx.helperPath?.(MARKUP_MODULE_FILE) ?? MARKUP_MODULE_FILE);
|
|
1018
|
+
if (this.markup.sites.length)
|
|
1019
|
+
this.imports.type(source, MARKUP_ELEMENT_TYPE);
|
|
1020
|
+
if (this.markup.type)
|
|
1021
|
+
this.imports.type(source, MARKUP_TYPE);
|
|
1022
|
+
if (this.markup.view)
|
|
1023
|
+
this.imports.defaultImport(importPath(outPath, this.ctx.helperPath?.(MARKUP_VIEW_FILE) ?? MARKUP_VIEW_FILE), MARKUP_VIEW);
|
|
1024
|
+
}
|
|
1025
|
+
return out;
|
|
1026
|
+
}
|
|
1027
|
+
}
|
|
1028
|
+
/** `typeof x === 'number'` (or 'string'): the value tested, only text where the test holds. */
|
|
1029
|
+
function textTested(test) {
|
|
1030
|
+
if (!t.isBinaryExpression(test) || (test.operator !== '===' && test.operator !== '=='))
|
|
1031
|
+
return null;
|
|
1032
|
+
const of = (x, y) => t.isUnaryExpression(x, { operator: 'typeof' }) && (t.isStringLiteral(y, { value: 'number' }) || t.isStringLiteral(y, { value: 'string' })) ? x.argument : null;
|
|
1033
|
+
return of(test.left, test.right) ?? of(test.right, test.left);
|
|
1034
|
+
}
|
|
1035
|
+
/** The value is one an enclosing branch tested as text. */
|
|
1036
|
+
function testedAsText(e, scope) {
|
|
1037
|
+
return !!scope.text?.some((x) => t.isNodesEquivalent(x, e));
|
|
1038
|
+
}
|
|
1039
|
+
/**
|
|
1040
|
+
* Prints Svelte markup without ever putting whitespace between sibling nodes (Svelte would render it as a space):
|
|
1041
|
+
* line breaks go inside tags, before a deferred `>`, the way Prettier formats whitespace-sensitive HTML.
|
|
1042
|
+
*/
|
|
1043
|
+
class Markup {
|
|
1044
|
+
out = '';
|
|
1045
|
+
/** a tag's closing bracket, held back: inline form, the form at the start of a line, and a forced line break */
|
|
1046
|
+
pending = null;
|
|
1047
|
+
flush() {
|
|
1048
|
+
if (!this.pending)
|
|
1049
|
+
return;
|
|
1050
|
+
this.out += this.pending.indent === null ? this.pending.inline : `\n${this.pending.indent}${this.pending.broken}`;
|
|
1051
|
+
this.pending = null;
|
|
1052
|
+
}
|
|
1053
|
+
write(s) {
|
|
1054
|
+
this.flush();
|
|
1055
|
+
this.out += s;
|
|
1056
|
+
}
|
|
1057
|
+
/** Ends a tag; the bracket is held back so the next line can start with it. */
|
|
1058
|
+
bracket(inline, broken, indent = null) {
|
|
1059
|
+
this.flush();
|
|
1060
|
+
this.pending = { inline, broken, indent };
|
|
1061
|
+
}
|
|
1062
|
+
/** Moves to a new line, if a held bracket makes that safe. */
|
|
1063
|
+
breakLine(indent) {
|
|
1064
|
+
if (!this.pending)
|
|
1065
|
+
return;
|
|
1066
|
+
this.out += `\n${indent}${this.pending.broken}`;
|
|
1067
|
+
this.pending = null;
|
|
1068
|
+
}
|
|
1069
|
+
done() {
|
|
1070
|
+
this.flush();
|
|
1071
|
+
const s = this.out;
|
|
1072
|
+
this.out = '';
|
|
1073
|
+
return s;
|
|
1074
|
+
}
|
|
1075
|
+
}
|
|
1076
|
+
class SvelteTemplate {
|
|
1077
|
+
comp;
|
|
1078
|
+
script;
|
|
1079
|
+
facts;
|
|
1080
|
+
moduleWrites;
|
|
1081
|
+
inline;
|
|
1082
|
+
m = new Markup();
|
|
1083
|
+
/** snippets of markup a caller passes only while a test holds, printed at the top level of the markup */
|
|
1084
|
+
hoisted = [];
|
|
1085
|
+
/** printing a private component as a snippet: its props arrive as they are, a style as an object */
|
|
1086
|
+
asSnippet = false;
|
|
1087
|
+
/** components whose children arrive through the rest they spread (see restForwardedChildren) */
|
|
1088
|
+
forwarded = new Set();
|
|
1089
|
+
/** the component reads its style string back as an object (see styleObjectProp) */
|
|
1090
|
+
styleObject = false;
|
|
1091
|
+
/** the markup draws elements module code holds as data (through MarkupView, which the file imports) */
|
|
1092
|
+
drewData = false;
|
|
1093
|
+
constructor(comp, script, facts, moduleWrites, inline = { comps: new Map(), snippets: new Set(), used: new Set() }) {
|
|
1094
|
+
this.comp = comp;
|
|
1095
|
+
this.script = script;
|
|
1096
|
+
this.facts = facts;
|
|
1097
|
+
this.moduleWrites = moduleWrites;
|
|
1098
|
+
this.inline = inline;
|
|
1099
|
+
}
|
|
1100
|
+
/** A private component: a snippet call, or (when the caller passes markup, which a call cannot take) its markup in place. */
|
|
1101
|
+
inlined(n, comp, indent, scope) {
|
|
1102
|
+
for (const name of comp.moduleNames)
|
|
1103
|
+
this.inline.used.add(name);
|
|
1104
|
+
if (passesMarkup(n) || takesRef(comp)) {
|
|
1105
|
+
this.nodes(expandUse(n, comp, this.comp.refs), indent, scope);
|
|
1106
|
+
return;
|
|
1107
|
+
}
|
|
1108
|
+
this.inline.snippets.add(comp.name);
|
|
1109
|
+
this.m.breakLine(indent);
|
|
1110
|
+
// a snippet with no props takes no argument (see snippet())
|
|
1111
|
+
const takesProps = comp.props.some((p) => p.key !== 'key' && p.key !== 'ref');
|
|
1112
|
+
this.m.write(`{@render ${comp.name}(${takesProps ? this.expr(snippetArgument(n, comp), true) : ''})}`);
|
|
1113
|
+
}
|
|
1114
|
+
/** `{#snippet Name({ a, b = 1 }: { a: T; b?: U })}` with its derived values as `{@const}`, then its markup. */
|
|
1115
|
+
snippet(comp) {
|
|
1116
|
+
this.asSnippet = true;
|
|
1117
|
+
const members = [];
|
|
1118
|
+
const params = [];
|
|
1119
|
+
for (const p of comp.props) {
|
|
1120
|
+
if (p.key === 'key' || p.key === 'ref')
|
|
1121
|
+
continue;
|
|
1122
|
+
const declared = comp.declared.get(p.key);
|
|
1123
|
+
let type = p.kind === 'children' ? null : this.script.type(declared?.type ?? p.type);
|
|
1124
|
+
if (p.kind === 'children' || (p.kind === 'node' && !type)) {
|
|
1125
|
+
this.script.typeImports.push({ source: 'svelte', name: 'Snippet' });
|
|
1126
|
+
type = p.kind === 'children' ? t.tsTypeReference(t.identifier('Snippet')) : t.tsUnionType([t.tsTypeReference(t.identifier('Snippet')), t.tsStringKeyword(), t.tsNumberKeyword()]);
|
|
1127
|
+
}
|
|
1128
|
+
const key = /^[A-Za-z_$][\w$]*$/.test(p.key) ? t.identifier(p.key) : t.stringLiteral(p.key);
|
|
1129
|
+
const sig = t.tsPropertySignature(t.cloneNode(key), t.tsTypeAnnotation(type ?? t.tsUnknownKeyword()));
|
|
1130
|
+
sig.optional = !!p.defaultValue || p.optional || p.kind === 'children' || !declared || declared.optional;
|
|
1131
|
+
members.push(sig);
|
|
1132
|
+
const value = p.defaultValue && p.kind !== 'children' ? t.assignmentPattern(t.identifier(p.local), t.cloneNode(p.defaultValue, true)) : t.identifier(p.local);
|
|
1133
|
+
params.push(t.objectProperty(key, value, false, t.isIdentifier(key) && key.name === p.local && !(p.defaultValue && p.kind !== 'children')));
|
|
1134
|
+
}
|
|
1135
|
+
const pattern = t.objectPattern(params);
|
|
1136
|
+
const type = mapReactTypes(t.tsTypeLiteral(members), 'svelte', this.facts.reactNames, this.script.typeImports);
|
|
1137
|
+
for (const name of namesIn([pattern, type]))
|
|
1138
|
+
this.inline.used.add(name);
|
|
1139
|
+
// a pattern prints its type only as a function parameter: the two are joined here
|
|
1140
|
+
if (params.length)
|
|
1141
|
+
this.typedMarkup = true;
|
|
1142
|
+
this.m.write(`{#snippet ${comp.name}(${params.length ? `${printInline(pattern)}: ${printInline(type)}` : ''})}`);
|
|
1143
|
+
for (const item of comp.items) {
|
|
1144
|
+
if (item.kind === 'derived' && t.isIdentifier(item.id))
|
|
1145
|
+
this.m.write(`{@const ${item.id.name} = ${this.expr(item.init)}}`);
|
|
1146
|
+
else if (item.kind === 'function') {
|
|
1147
|
+
const fn = item.node;
|
|
1148
|
+
const value = t.isFunctionDeclaration(fn) ? t.arrowFunctionExpression(fn.params, fn.body, fn.async) : fn;
|
|
1149
|
+
this.m.write(`{@const ${item.name} = ${this.expr(value)}}`);
|
|
1150
|
+
}
|
|
1151
|
+
}
|
|
1152
|
+
this.node(comp.template, ' ', { loopNames: new Set() });
|
|
1153
|
+
// markup its props' data holds: snippets declared in this one, where its props are in scope
|
|
1154
|
+
for (const v of comp.markupValues ?? [])
|
|
1155
|
+
this.m.write(this.markupValue(v.name, v.template));
|
|
1156
|
+
this.m.write('{/snippet}');
|
|
1157
|
+
}
|
|
1158
|
+
/** the component's render helpers its markup calls (printed as snippets after it) */
|
|
1159
|
+
fragmentsUsed = new Set();
|
|
1160
|
+
/** the bindings rendered as `<svelte:element this={…}>`: tag names, never components (see narrowTagProps) */
|
|
1161
|
+
tagNames = new Set();
|
|
1162
|
+
/** row locals whose object of React DOM props domSpreadLocal wrote with the DOM's names (spread as they are) */
|
|
1163
|
+
domLocals = new Set();
|
|
1164
|
+
/** the markup holds TypeScript (typed snippet parameters, a cast): the file needs a `lang="ts"` script to parse */
|
|
1165
|
+
typedMarkup = false;
|
|
1166
|
+
/** A render helper as a snippet: `{#snippet row(step: Step, sub: boolean)}`, its values as `{@const}`, its markup. */
|
|
1167
|
+
/** printing a render helper (its parameters are names a top-level snippet cannot read) */
|
|
1168
|
+
inFragment = false;
|
|
1169
|
+
fragment(def) {
|
|
1170
|
+
this.inFragment = true;
|
|
1171
|
+
try {
|
|
1172
|
+
this.fragmentBody(def);
|
|
1173
|
+
}
|
|
1174
|
+
finally {
|
|
1175
|
+
this.inFragment = false;
|
|
1176
|
+
}
|
|
1177
|
+
}
|
|
1178
|
+
fragmentBody(def) {
|
|
1179
|
+
const params = def.params.map((p) => {
|
|
1180
|
+
const id = t.identifier(p.name);
|
|
1181
|
+
id.optional = !!p.optional;
|
|
1182
|
+
const declared = t.isTSTypeAnnotation(p.typeAnnotation) ? this.script.type(p.typeAnnotation.typeAnnotation) : null;
|
|
1183
|
+
if (declared) {
|
|
1184
|
+
const type = mapReactTypes(declared, 'svelte', this.facts.reactNames, this.script.typeImports);
|
|
1185
|
+
for (const name of namesIn([type]))
|
|
1186
|
+
this.inline.used.add(name);
|
|
1187
|
+
id.typeAnnotation = t.tsTypeAnnotation(type);
|
|
1188
|
+
this.typedMarkup = true;
|
|
1189
|
+
}
|
|
1190
|
+
return id;
|
|
1191
|
+
});
|
|
1192
|
+
// a parameter prints its `?` and its type only as part of a function
|
|
1193
|
+
const head = printInline(t.arrowFunctionExpression(params, t.blockStatement([])));
|
|
1194
|
+
this.m.write(`{#snippet ${def.name}(${head.slice(head.indexOf('(') + 1, head.lastIndexOf(') =>'))})}`);
|
|
1195
|
+
for (const l of def.locals) {
|
|
1196
|
+
const d = l.declarations[0];
|
|
1197
|
+
if (d && t.isIdentifier(d.id) && d.init)
|
|
1198
|
+
this.m.write(`{@const ${d.id.name} = ${this.expr(d.init)}}`);
|
|
1199
|
+
}
|
|
1200
|
+
this.node(def.template, ' ', { loopNames: new Set() });
|
|
1201
|
+
this.m.write('{/snippet}');
|
|
1202
|
+
}
|
|
1203
|
+
/**
|
|
1204
|
+
* A row's object of React DOM props spread onto elements (`const props = { className: 'row', onClick: … }` then
|
|
1205
|
+
* `<button {...props}>`): Svelte's spread takes the DOM's names (`class`, `onclick`; `onClick` would listen to an event
|
|
1206
|
+
* named "Click" and `className` would become an attribute of that name), so the object is written with them, as the
|
|
1207
|
+
* attributes written on an element are. Only when every read of it is such a spread and every key has a DOM name;
|
|
1208
|
+
* null otherwise (the object is printed as written).
|
|
1209
|
+
*/
|
|
1210
|
+
domSpreadLocal(d, children) {
|
|
1211
|
+
if (!t.isIdentifier(d.id) || !d.init)
|
|
1212
|
+
return null;
|
|
1213
|
+
const as = t.isTSAsExpression(d.init) ? d.init : null;
|
|
1214
|
+
const obj = as ? as.expression : d.init;
|
|
1215
|
+
if (!t.isObjectExpression(obj))
|
|
1216
|
+
return null;
|
|
1217
|
+
const tags = domSpreadTags(children, d.id.name);
|
|
1218
|
+
if (!tags?.size)
|
|
1219
|
+
return null;
|
|
1220
|
+
const copy = cloneWithRefs(obj, this.comp);
|
|
1221
|
+
for (const p of copy.properties) {
|
|
1222
|
+
if (!t.isObjectProperty(p) || p.computed)
|
|
1223
|
+
return null;
|
|
1224
|
+
const key = t.isIdentifier(p.key) ? p.key.name : t.isStringLiteral(p.key) ? p.key.value : null;
|
|
1225
|
+
if (key === null || key === 'style' || key === 'ref' || key === 'key' || key === 'children' || key === 'dangerouslySetInnerHTML')
|
|
1226
|
+
return null;
|
|
1227
|
+
let dom = domAttributeName(key);
|
|
1228
|
+
if (/^on[A-Z]/.test(key)) {
|
|
1229
|
+
// React's onChange on a field is the DOM's input event, which depends on the element: not written here
|
|
1230
|
+
if (!isDomEventProp(key) || (key === 'onChange' && [...tags].some((tag) => FIELD_TAGS.has(tag))))
|
|
1231
|
+
return null;
|
|
1232
|
+
// React's onFocus and onBlur bubble (focusin, focusout), as the attributes written on an element do
|
|
1233
|
+
dom = `on${key === 'onFocus' ? 'focusin' : key === 'onBlur' ? 'focusout' : domEventName(key, '', [])}`;
|
|
1234
|
+
}
|
|
1235
|
+
if (dom === key)
|
|
1236
|
+
continue;
|
|
1237
|
+
p.key = /^[A-Za-z_$][\w$]*$/.test(dom) ? t.identifier(dom) : t.stringLiteral(dom);
|
|
1238
|
+
p.shorthand = false;
|
|
1239
|
+
}
|
|
1240
|
+
this.domLocals.add(d.id.name);
|
|
1241
|
+
return as ? t.tsAsExpression(copy, as.typeAnnotation) : copy;
|
|
1242
|
+
}
|
|
1243
|
+
/** An expression as markup prints it; `post` sees it once rewritten (a copy rewritten first would lose its bindings). */
|
|
1244
|
+
expr(e, inline = false, post) {
|
|
1245
|
+
const rewritten = this.script.r(e);
|
|
1246
|
+
const holder = t.expressionStatement(post ? post(rewritten) : rewritten);
|
|
1247
|
+
if (this.moduleWrites)
|
|
1248
|
+
for (const n of routeModuleWrites([holder], this.moduleWrites.names, new Set(this.comp.bindings.keys())))
|
|
1249
|
+
this.moduleWrites.written.add(n);
|
|
1250
|
+
const typed = this.markupTypes(holder.expression);
|
|
1251
|
+
return inline ? printInline(typed) : printExpr(typed);
|
|
1252
|
+
}
|
|
1253
|
+
/**
|
|
1254
|
+
* Svelte markup is TypeScript (`lang="ts"`), so an expression keeps the assertions its author wrote (`as Element`,
|
|
1255
|
+
* `x!`, `closest<HTMLElement>()`), with React's types mapped: they say what React's types knew. A cast to a React type
|
|
1256
|
+
* with no Svelte counterpart is dropped, as are parameter and return annotations (the markup types a handler's
|
|
1257
|
+
* event itself).
|
|
1258
|
+
*/
|
|
1259
|
+
markupTypes(e) {
|
|
1260
|
+
const hasUnknown = (type) => {
|
|
1261
|
+
let found = false;
|
|
1262
|
+
t.traverseFast(type, (x) => {
|
|
1263
|
+
if (t.isTSUnknownKeyword(x))
|
|
1264
|
+
found = true;
|
|
1265
|
+
});
|
|
1266
|
+
return found;
|
|
1267
|
+
};
|
|
1268
|
+
const mapped = (type) => {
|
|
1269
|
+
const out = this.script.type(type);
|
|
1270
|
+
if (!out || (hasUnknown(out) && !hasUnknown(type)))
|
|
1271
|
+
return null;
|
|
1272
|
+
for (const name of namesIn([out]))
|
|
1273
|
+
this.inline.used.add(name);
|
|
1274
|
+
return out;
|
|
1275
|
+
};
|
|
1276
|
+
// a cast of the whole value (`{...rest as ButtonProps}`, `style={{ ... } as CSSProperties}`) only restates what the
|
|
1277
|
+
// attribute or the component's props already type: dropped, as before
|
|
1278
|
+
// `as const` is not one: it narrows the value (`['left', 'right'] as const` iterates literal types), so it stays
|
|
1279
|
+
const asConst = (n) => t.isTSAsExpression(n) && t.isTSTypeReference(n.typeAnnotation) && t.isIdentifier(n.typeAnnotation.typeName, { name: 'const' });
|
|
1280
|
+
let root = e;
|
|
1281
|
+
while ((t.isTSAsExpression(root) || t.isTSSatisfiesExpression(root) || t.isTSTypeAssertion(root)) && !asConst(root))
|
|
1282
|
+
root = root.expression;
|
|
1283
|
+
const kept = new WeakSet();
|
|
1284
|
+
// a function inside the value (`const go = (i: number) => …` in a handler) is typed by no attribute: its
|
|
1285
|
+
// parameters keep the types its author wrote (mapped), or they would be implicitly `any`
|
|
1286
|
+
const nestedParams = new WeakSet();
|
|
1287
|
+
t.traverseFast(root, (n) => {
|
|
1288
|
+
if (TYPED_SETTERS.has(n) && (t.isArrowFunctionExpression(n) || t.isFunctionExpression(n)))
|
|
1289
|
+
for (const p of n.params)
|
|
1290
|
+
t.traverseFast(p, (x) => {
|
|
1291
|
+
kept.add(x);
|
|
1292
|
+
});
|
|
1293
|
+
const handlerRoot = t.isArrowFunctionExpression(root) || t.isFunctionExpression(root);
|
|
1294
|
+
if (handlerRoot && n !== root && (t.isArrowFunctionExpression(n) || t.isFunctionExpression(n)))
|
|
1295
|
+
for (const p of n.params)
|
|
1296
|
+
nestedParams.add(p);
|
|
1297
|
+
});
|
|
1298
|
+
const out = transform(root, (n) => {
|
|
1299
|
+
if (asConst(n))
|
|
1300
|
+
return null;
|
|
1301
|
+
if (t.isTSAsExpression(n) || t.isTSSatisfiesExpression(n) || t.isTSTypeAssertion(n)) {
|
|
1302
|
+
const type = mapped(n.typeAnnotation);
|
|
1303
|
+
if (!type)
|
|
1304
|
+
return n.expression;
|
|
1305
|
+
return t.isTSSatisfiesExpression(n) ? t.tsSatisfiesExpression(n.expression, type) : t.tsAsExpression(n.expression, type);
|
|
1306
|
+
}
|
|
1307
|
+
if ((t.isCallExpression(n) || t.isNewExpression(n)) && t.isTSTypeParameterInstantiation(n.typeParameters)) {
|
|
1308
|
+
const params = n.typeParameters.params.map((p) => mapped(p));
|
|
1309
|
+
const kept = params.filter((p) => p !== null);
|
|
1310
|
+
n.typeParameters = kept.length === params.length ? t.tsTypeParameterInstantiation(kept) : null;
|
|
1311
|
+
return null;
|
|
1312
|
+
}
|
|
1313
|
+
// a setter's parameter keeps its type (the value, or a function of the previous one), or its function branch is `never`
|
|
1314
|
+
// (only a type written in the React source: one the type oracle inferred, parsed from its own text, stays out)
|
|
1315
|
+
const written = (x) => !!x.loc && x.loc.filename !== 'oracle.ts';
|
|
1316
|
+
if ((t.isIdentifier(n) || t.isObjectPattern(n) || t.isArrayPattern(n) || t.isRestElement(n)) && nestedParams.has(n) && t.isTSTypeAnnotation(n.typeAnnotation) && written(n.typeAnnotation.typeAnnotation)) {
|
|
1317
|
+
const type = mapped(n.typeAnnotation.typeAnnotation);
|
|
1318
|
+
n.typeAnnotation = type ? t.tsTypeAnnotation(type) : null;
|
|
1319
|
+
return null;
|
|
1320
|
+
}
|
|
1321
|
+
if ((t.isIdentifier(n) || t.isObjectPattern(n) || t.isArrayPattern(n) || t.isAssignmentPattern(n) || t.isRestElement(n)) && n.typeAnnotation && !kept.has(n))
|
|
1322
|
+
n.typeAnnotation = null;
|
|
1323
|
+
if (t.isArrowFunctionExpression(n) || t.isFunctionExpression(n)) {
|
|
1324
|
+
n.returnType = null;
|
|
1325
|
+
n.typeParameters = null;
|
|
1326
|
+
}
|
|
1327
|
+
return null;
|
|
1328
|
+
});
|
|
1329
|
+
t.traverseFast(out, (n) => {
|
|
1330
|
+
if (t.isTSAsExpression(n) || t.isTSSatisfiesExpression(n) || t.isTSNonNullExpression(n) || t.isTSTypeParameterInstantiation(n))
|
|
1331
|
+
this.typedMarkup = true;
|
|
1332
|
+
});
|
|
1333
|
+
return out;
|
|
1334
|
+
}
|
|
1335
|
+
/** Attribute text inside quotes: Svelte reads `{` as the start of an expression. */
|
|
1336
|
+
/**
|
|
1337
|
+
* The text a parent writes between the tags of a component whose children React types as text, as that component's
|
|
1338
|
+
* `children` prop: one text or one value, as React's type allows; markup there has no text form and is an error.
|
|
1339
|
+
*/
|
|
1340
|
+
textChildrenAttr(tag, children) {
|
|
1341
|
+
const only = children.length === 1 ? children[0] : undefined;
|
|
1342
|
+
if (only?.type === 'text')
|
|
1343
|
+
return `children="${this.quote(only.value)}"`;
|
|
1344
|
+
if (only?.type === 'expr' && !only.markup)
|
|
1345
|
+
return `children={${this.expr(only.expr)}}`;
|
|
1346
|
+
this.script.warn('children-value', `<${tag}> takes its children as text (React types them so), and this one is given markup: Svelte passes that text as the children prop, and markup has no text form. Not converted.`, 'error');
|
|
1347
|
+
return null;
|
|
1348
|
+
}
|
|
1349
|
+
quote(s) {
|
|
1350
|
+
return s.replace(/&(?=[a-zA-Z#])/g, '&').replace(/"/g, '"').replace(/\{/g, '{').replace(/\}/g, '}');
|
|
1351
|
+
}
|
|
1352
|
+
/**
|
|
1353
|
+
* A value of the component computed from others (`const picture = isPerState(art) ? art[key] : art`) that React's
|
|
1354
|
+
* types say may be an element: it holds the snippet a caller passed as often as text or nothing, so it renders as a
|
|
1355
|
+
* snippet where it is one, as data reads already do (ir/markup-values), never as the function's source text. Not under
|
|
1356
|
+
* a branch that tested it as text (`typeof picture === 'number'`), where it is only text.
|
|
1357
|
+
*/
|
|
1358
|
+
derivedMarkup(e, scope) {
|
|
1359
|
+
if (!t.isIdentifier(e) || !e.loc || this.comp.bindings.get(e.name)?.kind !== 'derived')
|
|
1360
|
+
return false;
|
|
1361
|
+
if (testedAsText(e, scope) || this.script.markup?.readsWritten(e))
|
|
1362
|
+
return false;
|
|
1363
|
+
const kind = this.script.ctx.oracle?.elementKind(this.script.ctx.sourceFile, e.loc);
|
|
1364
|
+
return !!kind && kind.element && !kind.unknown;
|
|
1365
|
+
}
|
|
1366
|
+
/**
|
|
1367
|
+
* A value printed as text whose React type, as the checker prints it, holds a boolean beside text (`flag`, `string |
|
|
1368
|
+
* boolean`) or is a list of text (`string[]`, `(string | number)[]`): read once more in the output, so only a name or
|
|
1369
|
+
* a chain of member reads (reading it again computes nothing). Null: text only, or a type not known that exactly.
|
|
1370
|
+
*/
|
|
1371
|
+
textForm(e) {
|
|
1372
|
+
let base = e;
|
|
1373
|
+
while (t.isMemberExpression(base) || t.isOptionalMemberExpression(base)) {
|
|
1374
|
+
if (base.computed && !t.isStringLiteral(base.property) && !t.isNumericLiteral(base.property) && !t.isIdentifier(base.property))
|
|
1375
|
+
return null;
|
|
1376
|
+
base = base.object;
|
|
1377
|
+
}
|
|
1378
|
+
if (!t.isIdentifier(base) || !e.loc)
|
|
1379
|
+
return null;
|
|
1380
|
+
const type = this.script.ctx.oracle?.typeOfExpression(this.script.ctx.sourceFile, e.loc);
|
|
1381
|
+
if (!type)
|
|
1382
|
+
return null;
|
|
1383
|
+
const bare = (x) => (t.isTSParenthesizedType(x) ? bare(x.typeAnnotation) : x);
|
|
1384
|
+
const members = (x) => {
|
|
1385
|
+
const b = bare(x);
|
|
1386
|
+
return t.isTSUnionType(b) ? b.types.flatMap(members) : [b];
|
|
1387
|
+
};
|
|
1388
|
+
const nothing = (m) => t.isTSNullKeyword(m) || t.isTSUndefinedKeyword(m);
|
|
1389
|
+
const text = (m) => t.isTSStringKeyword(m) || t.isTSNumberKeyword(m) || (t.isTSLiteralType(m) && (t.isStringLiteral(m.literal) || t.isNumericLiteral(m.literal) || t.isTemplateLiteral(m.literal)));
|
|
1390
|
+
const bool = (m) => t.isTSBooleanKeyword(m) || (t.isTSLiteralType(m) && t.isBooleanLiteral(m.literal));
|
|
1391
|
+
const list = (m) => t.isTSArrayType(m) && members(m.elementType).every((x) => text(x) || nothing(x));
|
|
1392
|
+
const all = members(type);
|
|
1393
|
+
if (all.some(bool) && all.every((m) => bool(m) || text(m) || nothing(m)))
|
|
1394
|
+
return 'boolean';
|
|
1395
|
+
if (all.some(list) && all.every((m) => list(m) || nothing(m)))
|
|
1396
|
+
return all.some(nothing) ? 'maybe-list' : 'list';
|
|
1397
|
+
return null;
|
|
1398
|
+
}
|
|
1399
|
+
/** A handler may call preventDefault: its code says so, or it is a value whose code is not the component's. */
|
|
1400
|
+
mayPreventDefault(handler) {
|
|
1401
|
+
const fn = unwrap(handler);
|
|
1402
|
+
const own = t.isIdentifier(fn) ? this.comp.items.find((i) => i.kind === 'function' && i.name === fn.name) : undefined;
|
|
1403
|
+
const callback = t.isIdentifier(fn) ? this.comp.items.find((i) => i.kind === 'derived' && i.names.length === 1 && i.names[0] === fn.name) : undefined;
|
|
1404
|
+
const body = t.isArrowFunctionExpression(fn) || t.isFunctionExpression(fn) ? fn : own?.kind === 'function' ? own.node : callback?.kind === 'derived' ? callback.init : null;
|
|
1405
|
+
if (!body)
|
|
1406
|
+
return true;
|
|
1407
|
+
// the event passed on to other code (`stop(e)`) may be stopped there
|
|
1408
|
+
const first = t.isFunction(body) ? body.params[0] : undefined;
|
|
1409
|
+
const event = t.isIdentifier(first) ? first.name : null;
|
|
1410
|
+
let found = !t.isFunction(body);
|
|
1411
|
+
t.traverseFast(body, (n) => {
|
|
1412
|
+
if (t.isIdentifier(n, { name: 'preventDefault' }))
|
|
1413
|
+
found = true;
|
|
1414
|
+
if (event && (t.isCallExpression(n) || t.isNewExpression(n)) && n.arguments.some((x) => t.isIdentifier(x, { name: event })))
|
|
1415
|
+
found = true;
|
|
1416
|
+
});
|
|
1417
|
+
return found;
|
|
1418
|
+
}
|
|
1419
|
+
nodes(list, indent, scope) {
|
|
1420
|
+
const flat = list.flatMap((x) => (x.type === 'fragment' ? x.children : [x]));
|
|
1421
|
+
flat.forEach((n, i) => {
|
|
1422
|
+
if (n.type === 'text' && (i === 0 || i === flat.length - 1))
|
|
1423
|
+
this.edgeText(n.value, i === 0, i === flat.length - 1);
|
|
1424
|
+
else
|
|
1425
|
+
this.node(n, indent, scope);
|
|
1426
|
+
});
|
|
1427
|
+
}
|
|
1428
|
+
/**
|
|
1429
|
+
* Text at the start or end of an element, block or snippet: Svelte removes the whitespace there (`<b>Note: </b>`
|
|
1430
|
+
* renders "Note:"), React keeps it, so that whitespace is written as an expression, which Svelte keeps.
|
|
1431
|
+
*/
|
|
1432
|
+
edgeText(value, first, last) {
|
|
1433
|
+
const lead = first ? (/^[ \t\r\n]+/.exec(value)?.[0] ?? '') : '';
|
|
1434
|
+
const rest = value.slice(lead.length);
|
|
1435
|
+
const trail = last ? (/[ \t\r\n]+$/.exec(rest)?.[0] ?? '') : '';
|
|
1436
|
+
const middle = rest.slice(0, rest.length - trail.length);
|
|
1437
|
+
const kept = (ws) => (ws ? `{'${ws.replace(/\t/g, '\\t').replace(/\r/g, '\\r').replace(/\n/g, '\\n')}'}` : '');
|
|
1438
|
+
this.m.write(`${kept(lead)}${middle ? escapeText(middle, true) : ''}${kept(trail)}`);
|
|
1439
|
+
}
|
|
1440
|
+
node(n, indent, scope) {
|
|
1441
|
+
switch (n.type) {
|
|
1442
|
+
case 'text':
|
|
1443
|
+
this.m.write(escapeText(n.value, true));
|
|
1444
|
+
return;
|
|
1445
|
+
case 'unconverted': {
|
|
1446
|
+
// a value script code builds out of elements, written as data: drawn as React draws a child
|
|
1447
|
+
const value = this.script.markup?.rendered(n);
|
|
1448
|
+
if (value) {
|
|
1449
|
+
this.m.breakLine(indent);
|
|
1450
|
+
this.m.write(`<${MARKUP_VIEW} value={${this.expr(value, true)}} />`);
|
|
1451
|
+
return;
|
|
1452
|
+
}
|
|
1453
|
+
this.m.write(`<!-- antheo-morph: not converted: ${n.reason.replace(/--/g, '- -')} -->`);
|
|
1454
|
+
return;
|
|
1455
|
+
}
|
|
1456
|
+
case 'render':
|
|
1457
|
+
this.fragmentsUsed.add(n.name);
|
|
1458
|
+
this.m.breakLine(indent);
|
|
1459
|
+
this.m.write(`{@render ${n.name}(${n.args.map((a) => this.expr(a, true)).join(', ')})}`);
|
|
1460
|
+
return;
|
|
1461
|
+
case 'expr':
|
|
1462
|
+
// a value that reads elements module code holds as data (`{marked(label, ranges)}`, a loop item over a table of
|
|
1463
|
+
// them): drawn as React draws a child (see markup-data/module-data)
|
|
1464
|
+
if (drawsModuleData(n)) {
|
|
1465
|
+
this.drewData = true;
|
|
1466
|
+
this.m.breakLine(indent);
|
|
1467
|
+
this.m.write(`<${MARKUP_VIEW} value={${this.expr(n.expr, true)}} />`);
|
|
1468
|
+
return;
|
|
1469
|
+
}
|
|
1470
|
+
// a value read that lowering kept (`{cell(r, c)}`): drawn by MarkupView once the value it reads is written as
|
|
1471
|
+
// data; printed as text it would show an object, so a read that cannot be drawn is an error
|
|
1472
|
+
if (n.kept !== undefined && this.script.markup) {
|
|
1473
|
+
const value = this.script.markup.rendered(n);
|
|
1474
|
+
if (value) {
|
|
1475
|
+
this.m.breakLine(indent);
|
|
1476
|
+
this.m.write(`<${MARKUP_VIEW} value={${this.expr(value, true)}} />`);
|
|
1477
|
+
return;
|
|
1478
|
+
}
|
|
1479
|
+
if (this.script.markup.readsWritten(n.expr)) {
|
|
1480
|
+
this.m.write('<!-- antheo-morph: not converted: markup read as a value -->');
|
|
1481
|
+
this.script.warn('jsx-in-script', `${this.comp.name} reads markup built in script code as a value where it cannot be drawn: not converted.`, 'error');
|
|
1482
|
+
return;
|
|
1483
|
+
}
|
|
1484
|
+
}
|
|
1485
|
+
if (n.markup || this.derivedMarkup(n.expr, scope)) {
|
|
1486
|
+
// markup held as a value is a snippet; anything else it may hold renders as text
|
|
1487
|
+
const value = this.expr(n.expr, true);
|
|
1488
|
+
// under its element test (`isValidElement(x) ? x : …`, `typeof x === 'function'` here) it is only a snippet
|
|
1489
|
+
if (n.markup === 'element')
|
|
1490
|
+
this.m.write(`{@render ${value}()}`);
|
|
1491
|
+
// React draws no boolean (`{true}` is nothing); Svelte would print "true", and null or undefined as nothing
|
|
1492
|
+
else
|
|
1493
|
+
this.m.write(`{#if typeof ${value} === 'function'}{@render ${value}()}{:else if typeof ${value} !== 'boolean'}{${value}}{/if}`);
|
|
1494
|
+
return;
|
|
1495
|
+
}
|
|
1496
|
+
{
|
|
1497
|
+
// React draws no boolean and draws a list's items one after another; Svelte prints `true` and `a,b`
|
|
1498
|
+
const form = testedAsText(n.expr, scope) ? null : this.textForm(n.expr);
|
|
1499
|
+
const value = this.expr(n.expr);
|
|
1500
|
+
if (form === 'boolean')
|
|
1501
|
+
this.m.write(`{#if typeof ${value} !== 'boolean'}{${value}}{/if}`);
|
|
1502
|
+
else if (form === 'list' || form === 'maybe-list')
|
|
1503
|
+
this.m.write(`{${this.expr(n.expr, true)}${form === 'maybe-list' ? '?.' : '.'}join('')}`);
|
|
1504
|
+
else
|
|
1505
|
+
this.m.write(`{${value}}`);
|
|
1506
|
+
}
|
|
1507
|
+
return;
|
|
1508
|
+
case 'fragment':
|
|
1509
|
+
this.nodes(n.children, indent, scope);
|
|
1510
|
+
return;
|
|
1511
|
+
case 'element':
|
|
1512
|
+
this.element(n, indent, scope);
|
|
1513
|
+
return;
|
|
1514
|
+
case 'if':
|
|
1515
|
+
n.branches.forEach((b, i) => {
|
|
1516
|
+
this.m.breakLine(indent);
|
|
1517
|
+
if (i === 0)
|
|
1518
|
+
this.m.write(`{#if ${this.expr(b.test ?? t.booleanLiteral(true))}}`);
|
|
1519
|
+
else if (b.test)
|
|
1520
|
+
this.m.write(`{:else if ${this.expr(b.test)}}`);
|
|
1521
|
+
else
|
|
1522
|
+
this.m.write('{:else}');
|
|
1523
|
+
// React's state is a const, so a handler inside the branch still knew what the test proved; a Svelte state
|
|
1524
|
+
// is a `let` that is assigned, so TypeScript forgets the test inside a function (see attrs)
|
|
1525
|
+
const facts = new Set();
|
|
1526
|
+
for (const before of n.branches.slice(0, i))
|
|
1527
|
+
if (before.test)
|
|
1528
|
+
nonNullFacts(before.test, false, facts);
|
|
1529
|
+
if (b.test)
|
|
1530
|
+
nonNullFacts(b.test, true, facts);
|
|
1531
|
+
const state = new Set([...scope.facts ?? [], ...[...facts].filter((p) => this.comp.bindings.get(p.split('.')[0] ?? '')?.kind === 'state')]);
|
|
1532
|
+
const text = b.test ? textTested(b.test) : null;
|
|
1533
|
+
this.nodes(b.children, indent + ' ', { ...scope, facts: state, ...(text ? { text: [...scope.text ?? [], text] } : {}) });
|
|
1534
|
+
});
|
|
1535
|
+
this.m.write('{/if}');
|
|
1536
|
+
return;
|
|
1537
|
+
case 'for': {
|
|
1538
|
+
let children = n.children;
|
|
1539
|
+
let key = n.key;
|
|
1540
|
+
const only = children.length === 1 ? children[0] : undefined;
|
|
1541
|
+
if (!key && only?.type === 'keyed') {
|
|
1542
|
+
key = only.key;
|
|
1543
|
+
children = only.children;
|
|
1544
|
+
}
|
|
1545
|
+
const item = n.item ? printInline(stripTypes(t.cloneNode(n.item, true))) : '_item';
|
|
1546
|
+
const loopNames = new Set([...scope.loopNames, ...(n.item ? patternNames(n.item) : []), ...(n.index ? [n.index] : [])]);
|
|
1547
|
+
this.m.breakLine(indent);
|
|
1548
|
+
// Svelte reads a loop's key before the row's {@const} values exist: a key built from them uses their expressions
|
|
1549
|
+
let keyExpr = key;
|
|
1550
|
+
if (keyExpr && n.locals.length) {
|
|
1551
|
+
const locals = new Map();
|
|
1552
|
+
for (const local of n.locals)
|
|
1553
|
+
for (const d of local.declarations)
|
|
1554
|
+
if (t.isIdentifier(d.id) && d.init)
|
|
1555
|
+
locals.set(d.id.name, renameFree(t.cloneNode(d.init, true), locals));
|
|
1556
|
+
keyExpr = renameFree(t.cloneNode(keyExpr, true), locals);
|
|
1557
|
+
}
|
|
1558
|
+
// a cast the value keeps (`as const`) is parenthesised, so its `as` is not read as the block's own
|
|
1559
|
+
const iterable = this.expr(n.iterable, false, (e) => (t.isTSAsExpression(e) ? t.parenthesizedExpression(e) : e));
|
|
1560
|
+
this.m.write(`{#each ${iterable} as ${item}${n.index ? `, ${n.index}` : ''}${keyExpr ? ` (${this.expr(keyExpr)})` : ''}}`);
|
|
1561
|
+
for (const local of n.locals) {
|
|
1562
|
+
for (const d of local.declarations) {
|
|
1563
|
+
if (d.init)
|
|
1564
|
+
this.m.write(`{@const ${printExpr(stripTypes(t.cloneNode(d.id, true)))} = ${this.expr(this.domSpreadLocal(d, children) ?? d.init)}}`);
|
|
1565
|
+
}
|
|
1566
|
+
}
|
|
1567
|
+
this.nodes(children, indent + ' ', { loopNames });
|
|
1568
|
+
this.m.write('{/each}');
|
|
1569
|
+
return;
|
|
1570
|
+
}
|
|
1571
|
+
case 'slot': {
|
|
1572
|
+
const prop = this.comp.props.find((p) => p.local === n.prop);
|
|
1573
|
+
const name = this.comp.propsObject ? `${this.comp.propsObject}.${n.prop}` : n.prop;
|
|
1574
|
+
if (n.args) {
|
|
1575
|
+
// a render prop called with values: the caller's snippet, rendered with them
|
|
1576
|
+
this.m.write(`{@render ${name}?.(${n.args.map((a) => this.expr(a, true)).join(', ')})}`);
|
|
1577
|
+
return;
|
|
1578
|
+
}
|
|
1579
|
+
// children React types as text: the text, as React renders it (its default is the prop's own)
|
|
1580
|
+
if (prop?.kind === 'children' && textChildren(this.comp)) {
|
|
1581
|
+
this.m.write(`{${name}}`);
|
|
1582
|
+
return;
|
|
1583
|
+
}
|
|
1584
|
+
if (prop?.kind === 'node') {
|
|
1585
|
+
// React draws nothing for a boolean (`icon={false}`), and its default only for undefined
|
|
1586
|
+
this.m.write(`{#if typeof ${name} === 'function'}{@render ${name}()}{:else if typeof ${name} === 'boolean'}{:else if ${name} !== undefined}{${name}}{:else}`);
|
|
1587
|
+
this.nodes(n.fallback, indent, scope);
|
|
1588
|
+
this.m.write('{/if}');
|
|
1589
|
+
return;
|
|
1590
|
+
}
|
|
1591
|
+
if (n.fallback.length) {
|
|
1592
|
+
this.m.write(`{#if ${name}}{@render ${name}()}{:else}`);
|
|
1593
|
+
this.nodes(n.fallback, indent, scope);
|
|
1594
|
+
this.m.write('{/if}');
|
|
1595
|
+
}
|
|
1596
|
+
else
|
|
1597
|
+
this.m.write(`{@render ${name}?.()}`);
|
|
1598
|
+
return;
|
|
1599
|
+
}
|
|
1600
|
+
case 'keyed':
|
|
1601
|
+
// a key that never changes never re-creates anything
|
|
1602
|
+
if (constantKey(n.key)) {
|
|
1603
|
+
this.nodes(n.children, indent, scope);
|
|
1604
|
+
return;
|
|
1605
|
+
}
|
|
1606
|
+
this.m.write(`{#key ${this.expr(n.key)}}`);
|
|
1607
|
+
this.nodes(n.children, indent, scope);
|
|
1608
|
+
this.m.write('{/key}');
|
|
1609
|
+
return;
|
|
1610
|
+
case 'presence': {
|
|
1611
|
+
this.script.warn('animate-presence', 'AnimatePresence has no Svelte counterpart: the exits of its children are out: transitions, which Svelte plays when the condition, row or key around them goes.', 'info');
|
|
1612
|
+
// initial={false} on the children this file renders is exact (see enterPlacements); another file's are not followed
|
|
1613
|
+
const unfollowed = this.inline.unfollowed?.(n) ?? [];
|
|
1614
|
+
if (unfollowed.length)
|
|
1615
|
+
this.script.warn('presence-initial', `AnimatePresence initial={false}: ${unfollowed.map((c) => `<${c}>`).join(', ')} ${unfollowed.length > 1 ? 'are' : 'is'} declared in another file, whose motion elements play their initial animation when they first render on Svelte; React shows them at their animate values.`);
|
|
1616
|
+
this.nodes(n.children, indent, scope);
|
|
1617
|
+
return;
|
|
1618
|
+
}
|
|
1619
|
+
}
|
|
1620
|
+
}
|
|
1621
|
+
/** Whether a variable used as a tag holds a tag name (`'div'`) rather than a component, from its type or its value. */
|
|
1622
|
+
holdsTagName(name) {
|
|
1623
|
+
const stringish = (type) => {
|
|
1624
|
+
if (t.isTSStringKeyword(type) || (t.isTSLiteralType(type) && t.isStringLiteral(type.literal)) || t.isTSTypeOperator(type))
|
|
1625
|
+
return true;
|
|
1626
|
+
if (t.isTSUnionType(type))
|
|
1627
|
+
return type.types.some((x) => !t.isTSUndefinedKeyword(x) && !t.isTSNullKeyword(x) && stringish(x));
|
|
1628
|
+
// React.ElementType / ElementType<P> is usually an `as` prop: a tag name by default
|
|
1629
|
+
if (t.isTSTypeReference(type)) {
|
|
1630
|
+
const id = type.typeName;
|
|
1631
|
+
const last = t.isIdentifier(id) ? id.name : id.right.name;
|
|
1632
|
+
return last === 'ElementType';
|
|
1633
|
+
}
|
|
1634
|
+
return false;
|
|
1635
|
+
};
|
|
1636
|
+
const kind = this.script.ctx.oracle?.tagKind(this.script.ctx.sourceFile, this.comp.name, name) ?? null;
|
|
1637
|
+
if (kind)
|
|
1638
|
+
return kind === 'tag';
|
|
1639
|
+
const type = this.script.ctx.oracle?.typeOf(this.script.ctx.sourceFile, this.comp.name, name) ?? null;
|
|
1640
|
+
if (type)
|
|
1641
|
+
return stringish(type);
|
|
1642
|
+
const prop = this.comp.props.find((p) => p.local === name);
|
|
1643
|
+
if (prop?.type)
|
|
1644
|
+
return stringish(prop.type);
|
|
1645
|
+
if (prop?.defaultValue)
|
|
1646
|
+
return t.isStringLiteral(prop.defaultValue);
|
|
1647
|
+
// a value built from components (`icons[kind]`, `open ? ChevronUp : ChevronDown`) is a component
|
|
1648
|
+
for (const item of this.comp.items) {
|
|
1649
|
+
if (item.kind !== 'derived' || !item.names.includes(name))
|
|
1650
|
+
continue;
|
|
1651
|
+
let component = false;
|
|
1652
|
+
t.traverseFast(item.init, (x) => {
|
|
1653
|
+
if (t.isIdentifier(x) && /^[A-Z]/.test(x.name))
|
|
1654
|
+
component = true;
|
|
1655
|
+
});
|
|
1656
|
+
if (component)
|
|
1657
|
+
return false;
|
|
1658
|
+
}
|
|
1659
|
+
return true;
|
|
1660
|
+
}
|
|
1661
|
+
/**
|
|
1662
|
+
* createPortal(children, container): the children rendered here, moved under the container by an attachment that
|
|
1663
|
+
* removes them again (see SVELTE_PORTAL_SOURCE). One DOM element carries the attachment itself; anything else (text,
|
|
1664
|
+
* several nodes, a component) is wrapped in a `display: contents` element that does.
|
|
1665
|
+
*/
|
|
1666
|
+
portal(n, container, indent, scope) {
|
|
1667
|
+
if (!this.script.portalName) {
|
|
1668
|
+
this.script.portalName = this.script.alloc.has('portal') ? this.script.alloc.alloc('portal') : 'portal';
|
|
1669
|
+
this.script.alloc.reserve(this.script.portalName);
|
|
1670
|
+
}
|
|
1671
|
+
const target = this.expr(container, true);
|
|
1672
|
+
const attach = `{@attach ${this.script.portalName}(${target})}`;
|
|
1673
|
+
const only = n.children.length === 1 ? n.children[0] : undefined;
|
|
1674
|
+
this.m.breakLine(indent);
|
|
1675
|
+
this.m.write(`{#key ${target}}`);
|
|
1676
|
+
if (only?.type === 'element' && !only.component && !only.portal)
|
|
1677
|
+
this.element(only, indent, scope, [attach]);
|
|
1678
|
+
else {
|
|
1679
|
+
this.m.write(`<div style="display: contents" ${attach}`);
|
|
1680
|
+
this.m.bracket('>', '>');
|
|
1681
|
+
this.nodes(n.children, indent + ' ', scope);
|
|
1682
|
+
this.m.breakLine(indent);
|
|
1683
|
+
this.m.write('</div');
|
|
1684
|
+
this.m.bracket('>', '>');
|
|
1685
|
+
}
|
|
1686
|
+
this.m.write('{/key}');
|
|
1687
|
+
}
|
|
1688
|
+
/** A markup value of the module (ModuleIR.markupValues): a top-level snippet its data names, reading module names only. */
|
|
1689
|
+
markupValue(name, template) {
|
|
1690
|
+
return this.snippetText(name, '', [template], { loopNames: new Set() });
|
|
1691
|
+
}
|
|
1692
|
+
/** A snippet of markup on its own (`{#snippet name(params)}…{/snippet}`), printed apart from the current markup. */
|
|
1693
|
+
snippetText(name, params, children, scope) {
|
|
1694
|
+
const saved = this.m;
|
|
1695
|
+
this.m = new Markup();
|
|
1696
|
+
try {
|
|
1697
|
+
this.m.write(`{#snippet ${name}(${params})}`);
|
|
1698
|
+
this.nodes(children, ' ', scope);
|
|
1699
|
+
this.m.write('{/snippet}');
|
|
1700
|
+
return this.m.done();
|
|
1701
|
+
}
|
|
1702
|
+
finally {
|
|
1703
|
+
this.m = saved;
|
|
1704
|
+
}
|
|
1705
|
+
}
|
|
1706
|
+
/** Whether passed markup can be a snippet at the top of the file: it reads no name of a loop row or a snippet. */
|
|
1707
|
+
hoistable(s, scope) {
|
|
1708
|
+
if (this.asSnippet || this.inFragment)
|
|
1709
|
+
return false;
|
|
1710
|
+
const nodes = [...(s.when ? [s.when] : []), ...s.children.flatMap((c) => templateExpressions(c))];
|
|
1711
|
+
const read = namesIn(nodes);
|
|
1712
|
+
return ![...scope.loopNames].some((n) => read.has(n));
|
|
1713
|
+
}
|
|
1714
|
+
/** A render function's parameters as a snippet's: `picked: Row[], count: number` (the types React gave them). */
|
|
1715
|
+
snippetParams(fn) {
|
|
1716
|
+
return fn.params
|
|
1717
|
+
.map((p) => {
|
|
1718
|
+
const copy = t.cloneNode(p, true);
|
|
1719
|
+
const annotated = (t.isIdentifier(copy) || t.isObjectPattern(copy) || t.isArrayPattern(copy)) && t.isTSTypeAnnotation(copy.typeAnnotation) ? copy : null;
|
|
1720
|
+
if (annotated && t.isTSTypeAnnotation(annotated.typeAnnotation)) {
|
|
1721
|
+
const type = this.script.type(annotated.typeAnnotation.typeAnnotation);
|
|
1722
|
+
if (type) {
|
|
1723
|
+
for (const name of namesIn([type]))
|
|
1724
|
+
this.inline.used.add(name);
|
|
1725
|
+
annotated.typeAnnotation = t.tsTypeAnnotation(type);
|
|
1726
|
+
this.typedMarkup = true;
|
|
1727
|
+
}
|
|
1728
|
+
else
|
|
1729
|
+
annotated.typeAnnotation = null;
|
|
1730
|
+
}
|
|
1731
|
+
const head = printInline(t.arrowFunctionExpression([copy], t.blockStatement([])));
|
|
1732
|
+
return head.slice(head.indexOf('(') + 1, head.lastIndexOf(') =>'));
|
|
1733
|
+
})
|
|
1734
|
+
.join(', ');
|
|
1735
|
+
}
|
|
1736
|
+
element(n, indent, scope, extra = []) {
|
|
1737
|
+
if (n.portal) {
|
|
1738
|
+
this.portal(n, n.portal, indent, scope);
|
|
1739
|
+
return;
|
|
1740
|
+
}
|
|
1741
|
+
if (n.asChild && !this.slotted.has(n)) {
|
|
1742
|
+
this.asChildElement(n, n.asChild, indent, scope, extra);
|
|
1743
|
+
return;
|
|
1744
|
+
}
|
|
1745
|
+
if (n.component)
|
|
1746
|
+
this.passSlotChild(n);
|
|
1747
|
+
const inlined = n.component ? this.inline.comps.get(n.tag) : undefined;
|
|
1748
|
+
if (inlined) {
|
|
1749
|
+
this.inlined(n, inlined, indent, scope);
|
|
1750
|
+
return;
|
|
1751
|
+
}
|
|
1752
|
+
let tag = n.tag;
|
|
1753
|
+
let component = n.component;
|
|
1754
|
+
if (component && tag === this.facts.nextImage) {
|
|
1755
|
+
tag = 'img';
|
|
1756
|
+
component = false;
|
|
1757
|
+
n.attrs = n.attrs.filter((a) => !('name' in a) || !/^(priority|quality|placeholder|blurDataURL|loader|unoptimized|fill|sizes)$/.test(a.name));
|
|
1758
|
+
}
|
|
1759
|
+
else if (component && tag === this.facts.nextLink) {
|
|
1760
|
+
tag = 'a';
|
|
1761
|
+
component = false;
|
|
1762
|
+
n.attrs = n.attrs.filter((a) => !('name' in a) || !/^(prefetch|replace|scroll|shallow|passHref|legacyBehavior)$/.test(a.name));
|
|
1763
|
+
}
|
|
1764
|
+
const attrs = [];
|
|
1765
|
+
// a tag held in a variable: a component there renders as `<Icon />` (Svelte 5 components are values), a tag name
|
|
1766
|
+
// (`as = 'div'`) needs <svelte:element>
|
|
1767
|
+
const dynamic = holdsMotionTag(n) || (component && !!this.comp.bindings.get(tag) && this.comp.bindings.get(tag)?.kind !== 'function' && this.holdsTagName(tag));
|
|
1768
|
+
if (!component && (tag === 'style' || tag === 'script')) {
|
|
1769
|
+
// a <style> in the markup would be parsed as the component's own CSS
|
|
1770
|
+
attrs.push(`this="${tag}"`);
|
|
1771
|
+
tag = 'svelte:element';
|
|
1772
|
+
}
|
|
1773
|
+
if (dynamic) {
|
|
1774
|
+
this.tagNames.add(tag);
|
|
1775
|
+
attrs.push(`this={${tag}}`);
|
|
1776
|
+
tag = 'svelte:element';
|
|
1777
|
+
this.script.warn('dynamic-tag', 'A tag held in a variable becomes <svelte:element>, which expects a tag name (a component would need {@const} and <Component>).', 'info');
|
|
1778
|
+
}
|
|
1779
|
+
let styleValues = [];
|
|
1780
|
+
if (n.motion) {
|
|
1781
|
+
for (const name of Object.keys(n.motion)) {
|
|
1782
|
+
const what = UNCONVERTED.get(name);
|
|
1783
|
+
// M2: layout, layoutId and drag are played by motion-layout.ts (below)
|
|
1784
|
+
if (what && !playsLayoutOrDrag(name))
|
|
1785
|
+
this.script.warn('motion-prop', `Framer Motion ${what} are not converted for Svelte.`);
|
|
1786
|
+
}
|
|
1787
|
+
// `{...animationProps}`: motion props spread from an object reach the element as attributes, not the action that
|
|
1788
|
+
// animates it. React's types say which ones the object may carry: one it always carries is an error, one it may
|
|
1789
|
+
// carry (an optional member, as `MotionProps` has) a warning
|
|
1790
|
+
for (const a of n.attrs) {
|
|
1791
|
+
if (a.kind !== 'spread')
|
|
1792
|
+
continue;
|
|
1793
|
+
const members = this.script.ctx.oracle?.propertiesOf(this.script.ctx.sourceFile, a.expr.loc) ?? null;
|
|
1794
|
+
const carried = members ? [...members].filter(([k]) => ACTION_PROPS.has(k) || UNCONVERTED.has(k) || k === 'exit') : [];
|
|
1795
|
+
if (!carried.length)
|
|
1796
|
+
continue;
|
|
1797
|
+
const always = carried.filter(([, optional]) => !optional).map(([k]) => k);
|
|
1798
|
+
const spread = printExpr(a.expr);
|
|
1799
|
+
if (always.length)
|
|
1800
|
+
this.script.warn('motion-spread', `{...${spread}} on <motion.${n.tag}> carries Framer Motion props (${always.join(', ')}); Svelte animates only the motion props written on the element, so these would become plain attributes. Not converted: write them on <motion.${n.tag}>.`, 'error', a.expr.loc?.start.line);
|
|
1801
|
+
else
|
|
1802
|
+
this.script.warn('motion-spread', `{...${spread}} on <motion.${n.tag}> may carry Framer Motion props (${carried.slice(0, 4).map(([k]) => k).join(', ')}…, by its type); Svelte animates only the motion props written on the element, so spread ones become plain attributes and do not animate.`, 'warning', a.expr.loc?.start.line);
|
|
1803
|
+
}
|
|
1804
|
+
styleValues = this.motionStyleValues(n);
|
|
1805
|
+
}
|
|
1806
|
+
attrs.push(...this.attrs(n.attrs, tag, component || dynamic, scope.facts), ...extra);
|
|
1807
|
+
if (n.motion) {
|
|
1808
|
+
// the exit is played by the action (motion's own animation, as React plays it) and kept in the page by `out:`
|
|
1809
|
+
const exit = n.motion.exit ? (this.inline.exits?.get(n) ?? { kind: 'differs', why: 'it is markup held in data, rendered wherever that is read' }) : null;
|
|
1810
|
+
const plays = !!exit && exit.kind !== 'never';
|
|
1811
|
+
// AnimatePresence initial={false} above: the element starts at `animate`, and `in:` plays its initial animation
|
|
1812
|
+
// when it is added later (see enterPlacements)
|
|
1813
|
+
const enter = this.inline.enters?.get(n);
|
|
1814
|
+
const presence = enter?.kind === 'skip' ? { skipInitial: true } : enter?.kind === 'deferred' ? { skipInitial: enter.skip, waitForExit: enter.wait } : {};
|
|
1815
|
+
const hasAction = plays || enter?.kind === 'deferred' || Object.keys(n.motion).some((k) => ACTION_PROPS.has(k)) || styleValues.length > 0;
|
|
1816
|
+
const params = actionParams(n.motion, styleValues, plays, presence);
|
|
1817
|
+
if (hasAction) {
|
|
1818
|
+
this.script.helpers.add('motion');
|
|
1819
|
+
for (const f of motionFeatures(params, n.tag))
|
|
1820
|
+
this.script.motion.add(f);
|
|
1821
|
+
attrs.push(`use:${MOTION_ACTION}={${this.expr(params)}}`);
|
|
1822
|
+
}
|
|
1823
|
+
// M2: layout / layoutId / drag through motion's own engines, in the conversion's motion-layout.ts
|
|
1824
|
+
const layoutDrag = layoutDragParams(n, this.comp.items);
|
|
1825
|
+
for (const w of layoutDrag.warnings)
|
|
1826
|
+
this.script.warn('motion-prop', w.message, 'warning', w.line);
|
|
1827
|
+
if (layoutDrag.layout) {
|
|
1828
|
+
layoutActions(this.script).add(MOTION_LAYOUT);
|
|
1829
|
+
attrs.push(`use:${MOTION_LAYOUT}={${this.expr(layoutDrag.layout)}}`);
|
|
1830
|
+
}
|
|
1831
|
+
if (layoutDrag.drag) {
|
|
1832
|
+
layoutActions(this.script).add(MOTION_DRAG);
|
|
1833
|
+
attrs.push(`use:${MOTION_DRAG}={${this.expr(layoutDrag.drag)}}`);
|
|
1834
|
+
}
|
|
1835
|
+
if (layoutDrag.features.length)
|
|
1836
|
+
useLayoutHelper(this.script.ctx.diagnostics, layoutDrag.features);
|
|
1837
|
+
// `in:` before `out:`: an element that comes back while it leaves resumes its transitions in that order, and the
|
|
1838
|
+
// enter must see that it is still leaving
|
|
1839
|
+
if (enter?.kind === 'deferred') {
|
|
1840
|
+
this.script.helpers.add('motionEnter');
|
|
1841
|
+
this.script.motion.add('enter');
|
|
1842
|
+
attrs.push(`in:${MOTION_ENTER}`);
|
|
1843
|
+
}
|
|
1844
|
+
if (enter?.kind === 'differs')
|
|
1845
|
+
this.script.warn('presence-initial', `The initial animation of <motion.${n.tag}> under AnimatePresence initial={false} does not play when React plays it: ${enter.why}.`);
|
|
1846
|
+
if (plays) {
|
|
1847
|
+
this.script.helpers.add('motionExit');
|
|
1848
|
+
attrs.push(`out:${MOTION_EXIT}`);
|
|
1849
|
+
}
|
|
1850
|
+
if (exit?.kind === 'differs')
|
|
1851
|
+
this.script.warn('motion-exit', `The exit of <motion.${n.tag}> is motion's own animation, as in React, with one difference: ${exit.why}.`);
|
|
1852
|
+
if (exit?.kind === 'never' && exit.why)
|
|
1853
|
+
this.script.warn('motion-exit', `The exit of <motion.${n.tag}> is not played: ${exit.why}.`);
|
|
1854
|
+
}
|
|
1855
|
+
// markup passed only while a test holds: a snippet of the file passed under that test (`art={ink ? art : undefined}`)
|
|
1856
|
+
const conditional = component ? n.attrs.filter((a) => a.kind === 'slotProp' && !!a.when && this.hoistable(a, scope)) : [];
|
|
1857
|
+
for (const s of conditional) {
|
|
1858
|
+
const name = this.script.alloc.alloc(`${s.name}Snippet`);
|
|
1859
|
+
this.hoisted.push(this.snippetText(name, '', s.children, scope));
|
|
1860
|
+
attrs.push(`${s.name}={${this.expr(t.conditionalExpression(s.when ?? t.booleanLiteral(true), t.identifier(name), t.identifier('undefined')), true)}}`);
|
|
1861
|
+
}
|
|
1862
|
+
// markup for a prop the receiving component never renders as markup would be lost
|
|
1863
|
+
const receiver = component ? this.script.childOf(n.tag) : null;
|
|
1864
|
+
for (const a of n.attrs)
|
|
1865
|
+
if (a.kind === 'slotProp' && receiver && !rendersSlot(receiver, a.name) && !(a.name === SLOT_CHILD && (slotChildProp(receiver) || passesBitsChild(receiver))))
|
|
1866
|
+
this.script.warn('slot-prop', droppedSlotMessage(n.tag, a.name), 'error');
|
|
1867
|
+
const slotProps = n.attrs.filter((a) => a.kind === 'slotProp' && !conditional.includes(a));
|
|
1868
|
+
for (const s of slotProps) {
|
|
1869
|
+
if (s.when)
|
|
1870
|
+
this.script.warn('slot-presence', `"${s.name}" on <${n.tag}> is markup React passes only while a test holds; it reads names of a loop or a snippet, so Svelte passes the snippet always and <${n.tag}> sees it as there.`);
|
|
1871
|
+
}
|
|
1872
|
+
const html = n.attrs.find((a) => a.kind === 'html');
|
|
1873
|
+
let children = this.forwarded.has(n) ? [] : n.children;
|
|
1874
|
+
// a component whose children React types as text takes them as its `children` prop
|
|
1875
|
+
if (receiver && textChildren(receiver) && children.length) {
|
|
1876
|
+
const passed = this.textChildrenAttr(n.tag, children);
|
|
1877
|
+
if (passed)
|
|
1878
|
+
attrs.push(passed);
|
|
1879
|
+
children = [];
|
|
1880
|
+
}
|
|
1881
|
+
const empty = !children.length && !slotProps.length && !html;
|
|
1882
|
+
const inner = indent + ' ';
|
|
1883
|
+
this.m.breakLine(indent);
|
|
1884
|
+
const long = attrs.join(' ').length > 90;
|
|
1885
|
+
this.m.write(`<${tag}`);
|
|
1886
|
+
for (const a of attrs)
|
|
1887
|
+
this.m.write(long ? `\n${inner}${a}` : ` ${a}`);
|
|
1888
|
+
if (empty && (VOID_TAGS.has(tag) || component || SVG_TAGS.has(n.tag))) {
|
|
1889
|
+
this.m.bracket(' />', '/>', long ? indent : null);
|
|
1890
|
+
return;
|
|
1891
|
+
}
|
|
1892
|
+
this.m.bracket('>', '>', long ? indent : null);
|
|
1893
|
+
for (const s of slotProps) {
|
|
1894
|
+
this.m.breakLine(inner);
|
|
1895
|
+
if (s.render) {
|
|
1896
|
+
// a render prop: a snippet with the function's parameters, typed as React typed them
|
|
1897
|
+
this.m.write(`{#snippet ${s.name}(${this.snippetParams(s.render)})}`);
|
|
1898
|
+
const loopNames = new Set([...scope.loopNames, ...s.render.params.flatMap((p) => patternNames(p))]);
|
|
1899
|
+
this.nodes(s.children, inner, { ...scope, loopNames });
|
|
1900
|
+
}
|
|
1901
|
+
else {
|
|
1902
|
+
this.m.write(`{#snippet ${s.name}()}`);
|
|
1903
|
+
this.nodes(s.children, inner, scope);
|
|
1904
|
+
}
|
|
1905
|
+
this.m.write('{/snippet}');
|
|
1906
|
+
}
|
|
1907
|
+
if (html) {
|
|
1908
|
+
this.script.warn('inner-html', innerHtmlWarning(tag, html.expr, '{@html}'), 'warning', html.expr.loc?.start.line);
|
|
1909
|
+
this.m.write(`{@html ${this.expr(html.expr)}}`);
|
|
1910
|
+
}
|
|
1911
|
+
else
|
|
1912
|
+
this.nodes(children, inner, scope);
|
|
1913
|
+
this.m.breakLine(indent);
|
|
1914
|
+
this.m.write(`</${tag}`);
|
|
1915
|
+
this.m.bracket('>', '>');
|
|
1916
|
+
}
|
|
1917
|
+
/** Elements printed inside their Slot test (see asChildElement). */
|
|
1918
|
+
slotted = new Set();
|
|
1919
|
+
/**
|
|
1920
|
+
* Radix's Slot (ir/as-child): while the test holds, the caller's `child` snippet renders, given the element's
|
|
1921
|
+
* attributes as `props` to spread on its own element (bits-ui's convention); otherwise the element itself.
|
|
1922
|
+
*/
|
|
1923
|
+
asChildElement(n, test, indent, scope, extra) {
|
|
1924
|
+
this.slotted.add(n);
|
|
1925
|
+
const props = extra.length ? null : attrsObject(n.attrs);
|
|
1926
|
+
const child = !slotChildProp(this.comp) ? null : this.comp.propsStyle === 'object' && this.comp.propsObject ? `${this.comp.propsObject}.${SLOT_CHILD}` : SLOT_CHILD;
|
|
1927
|
+
if (!props || !child) {
|
|
1928
|
+
this.script.warn('as-child', `<${n.tag}> becomes a Radix Slot when ${printInline(test)} holds; its attributes ${props ? 'have no `child` snippet prop to go to (the component takes a prop of that name, or no props object)' : 'include a style, a ref or markup, which the `child` snippet is not given'}: not converted, the component renders its own <${n.tag}> either way.`, 'error');
|
|
1929
|
+
this.element(n, indent, scope, extra);
|
|
1930
|
+
return;
|
|
1931
|
+
}
|
|
1932
|
+
const inner = indent + ' ';
|
|
1933
|
+
this.m.breakLine(indent);
|
|
1934
|
+
this.m.write(`{#if ${this.expr(test)}}`);
|
|
1935
|
+
this.m.breakLine(inner);
|
|
1936
|
+
this.m.write(`{@render ${child}?.({ props: ${this.expr(props)} })}`);
|
|
1937
|
+
this.m.breakLine(indent);
|
|
1938
|
+
this.m.write('{:else}');
|
|
1939
|
+
this.element(n, inner, scope, extra);
|
|
1940
|
+
this.m.breakLine(indent);
|
|
1941
|
+
this.m.write('{/if}');
|
|
1942
|
+
}
|
|
1943
|
+
/**
|
|
1944
|
+
* `<Button asChild><a href="/docs" className="link">Docs</a></Button>` where Button renders a Radix Slot: the element
|
|
1945
|
+
* becomes Button's `child` snippet, spreading the attributes it is given first so its own win, its class joined after
|
|
1946
|
+
* theirs and each of its handlers run before theirs, as Radix merges them. While `asChild` may be false the element
|
|
1947
|
+
* stays the children as well (Button then renders it inside its own element).
|
|
1948
|
+
*/
|
|
1949
|
+
passSlotChild(n) {
|
|
1950
|
+
const receiver = this.script.childOf(n.tag);
|
|
1951
|
+
const key = receiver?.asChildProp;
|
|
1952
|
+
if (!receiver || !key || !slotChildProp(receiver) || n.attrs.some((a) => a.kind === 'slotProp' && a.name === SLOT_CHILD))
|
|
1953
|
+
return;
|
|
1954
|
+
const flag = n.attrs.find((a) => (a.kind === 'bool' || a.kind === 'expr') && a.name === key);
|
|
1955
|
+
const always = flag?.kind === 'bool' || (flag?.kind === 'expr' && t.isBooleanLiteral(unwrap(flag.expr), { value: true }));
|
|
1956
|
+
if (!flag || (flag.kind === 'expr' && t.isBooleanLiteral(unwrap(flag.expr), { value: false })))
|
|
1957
|
+
return;
|
|
1958
|
+
const content = n.children.filter((c) => !(c.type === 'text' && !c.value.trim()));
|
|
1959
|
+
const only = content[0];
|
|
1960
|
+
// M3: a component as the one child: no `child` snippet is written for it, so the Slot (while asChild holds) would
|
|
1961
|
+
// render nothing; refused, located, where its props cannot be merged onto the component's element
|
|
1962
|
+
if (content.length === 1 && only?.type === 'element' && only.component && !only.portal) {
|
|
1963
|
+
const line = [...n.attrs, ...only.attrs].map((a) => (a.kind === 'event' ? a.handler : 'expr' in a ? a.expr : null)?.loc?.start.line).find((l) => l !== undefined);
|
|
1964
|
+
this.script.warn('as-child', `<${n.tag} ${key}> merges its attributes (class, handlers, the rest) onto the one element its child <${only.tag}> renders, as Radix's Slot does; a component's element cannot be given them through Svelte's \`child\` snippet, and <${n.tag}> would render nothing in its place. Not converted.`, 'error', line);
|
|
1965
|
+
return;
|
|
1966
|
+
}
|
|
1967
|
+
if (content.length !== 1 || only?.type !== 'element' || only.component || only.portal)
|
|
1968
|
+
return;
|
|
1969
|
+
if (only.attrs.some((a) => a.kind === 'style' || a.kind === 'spread' || a.kind === 'html')) {
|
|
1970
|
+
this.script.warn('as-child', `<${n.tag} ${key}> merges its attributes onto <${only.tag}>; a style or a spread of <${only.tag}> would need merging with them at run time, which the \`child\` snippet does not do: not converted (Svelte renders <${only.tag}> inside <${n.tag}>'s own element).`, 'error');
|
|
1971
|
+
return;
|
|
1972
|
+
}
|
|
1973
|
+
let local = 'props';
|
|
1974
|
+
for (let i = 2; this.comp.bindings.has(local) || this.comp.props.some((p) => p.local === local) || this.comp.propsObject === local; i++)
|
|
1975
|
+
local = `slotProps${i === 2 ? '' : i}`;
|
|
1976
|
+
const given = (member) => t.memberExpression(t.identifier(local), t.identifier(member));
|
|
1977
|
+
const attrs = [{ kind: 'spread', expr: t.identifier(local) }];
|
|
1978
|
+
for (const a of only.attrs) {
|
|
1979
|
+
if ((a.kind === 'static' || a.kind === 'expr') && a.name === 'class') {
|
|
1980
|
+
const own = a.kind === 'static' ? t.stringLiteral(a.value) : a.expr;
|
|
1981
|
+
const joined = t.callExpression(t.memberExpression(t.callExpression(t.memberExpression(t.arrayExpression([given('class'), own]), t.identifier('filter')), [t.identifier('Boolean')]), t.identifier('join')), [t.stringLiteral(' ')]);
|
|
1982
|
+
attrs.push({ kind: 'expr', name: 'class', expr: joined });
|
|
1983
|
+
}
|
|
1984
|
+
else if (a.kind === 'event') {
|
|
1985
|
+
// the element's own handler first, then the one it is given (Radix's order)
|
|
1986
|
+
const event = t.identifier('event');
|
|
1987
|
+
const theirs = given(`on${a.name}${a.capture ? 'capture' : ''}`);
|
|
1988
|
+
const own = unwrap(a.handler);
|
|
1989
|
+
// `() => go()` runs as `go()`; a handler that takes nothing is called with nothing (as TypeScript requires), any
|
|
1990
|
+
// other with the event
|
|
1991
|
+
const first = t.isArrowFunctionExpression(own) && !own.params.length && t.isExpression(own.body) ? own.body : t.callExpression(a.handler, handlerArity(own, this.comp) === 0 ? [] : [event]);
|
|
1992
|
+
const body = t.blockStatement([
|
|
1993
|
+
t.expressionStatement(first),
|
|
1994
|
+
t.ifStatement(t.binaryExpression('===', t.unaryExpression('typeof', theirs), t.stringLiteral('function')), t.expressionStatement(t.callExpression(t.cloneNode(theirs), [event]))),
|
|
1995
|
+
]);
|
|
1996
|
+
attrs.push({ ...a, handler: t.arrowFunctionExpression([event], body) });
|
|
1997
|
+
}
|
|
1998
|
+
else
|
|
1999
|
+
attrs.push(a);
|
|
2000
|
+
}
|
|
2001
|
+
const param = t.objectPattern([t.objectProperty(t.identifier('props'), t.identifier(local), false, local === 'props')]);
|
|
2002
|
+
param.typeAnnotation = t.tsTypeAnnotation(t.tsTypeLiteral([t.tsPropertySignature(t.identifier('props'), t.tsTypeAnnotation(t.tsTypeReference(t.identifier('Record'), t.tsTypeParameterInstantiation([t.tsStringKeyword(), t.tsUnknownKeyword()]))))]));
|
|
2003
|
+
const merged = { ...only, attrs };
|
|
2004
|
+
n.attrs.push({ kind: 'slotProp', name: SLOT_CHILD, children: [merged], render: t.arrowFunctionExpression([param], t.nullLiteral()) });
|
|
2005
|
+
if (always)
|
|
2006
|
+
n.children = [];
|
|
2007
|
+
}
|
|
2008
|
+
/** Motion values in a motion element's style (`style={{ x }}` with `x = useMotionValue(0)`) bind through the action. */
|
|
2009
|
+
motionStyleValues(n) {
|
|
2010
|
+
const style = n.attrs.find((a) => a.kind === 'style');
|
|
2011
|
+
const obj = style ? unwrap(style.expr) : null;
|
|
2012
|
+
if (!style || !t.isObjectExpression(obj))
|
|
2013
|
+
return [];
|
|
2014
|
+
const moved = [];
|
|
2015
|
+
obj.properties = obj.properties.filter((p) => {
|
|
2016
|
+
if (!t.isObjectProperty(p) || !t.isIdentifier(p.value))
|
|
2017
|
+
return true;
|
|
2018
|
+
if (holdsMotionValue(this.comp, p.value.name)) {
|
|
2019
|
+
moved.push(p);
|
|
2020
|
+
return false;
|
|
2021
|
+
}
|
|
2022
|
+
return true;
|
|
2023
|
+
});
|
|
2024
|
+
if (!obj.properties.length)
|
|
2025
|
+
n.attrs = n.attrs.filter((a) => a !== style);
|
|
2026
|
+
return moved;
|
|
2027
|
+
}
|
|
2028
|
+
/**
|
|
2029
|
+
* A spread onto a DOM element, with the DOM's names (dom-spread.ts). The component's own props and their rest arrive
|
|
2030
|
+
* with them already (its callers pass `class` and `onclick`), as does a row's object domSpreadLocal wrote; an object
|
|
2031
|
+
* written at the spread is rewritten; any other object is renamed when it arrives, by the helper domProps.
|
|
2032
|
+
*/
|
|
2033
|
+
domSpread(e, tag, attrs) {
|
|
2034
|
+
const inner = unwrap(e);
|
|
2035
|
+
// an object the conversion wrote itself has no place in the React source (a Radix `child` snippet's props, which
|
|
2036
|
+
// bits-ui and the Slot pass already DOM-named): spread as it is
|
|
2037
|
+
if (!e.loc)
|
|
2038
|
+
return this.expr(e);
|
|
2039
|
+
const name = t.isIdentifier(inner) ? (this.comp.refs.get(inner) ?? inner.name) : null;
|
|
2040
|
+
const svg = SVG_TAGS.has(tag);
|
|
2041
|
+
// (an SVG element's props still arrive in React's camelCase: a caller passes `strokeWidth` as it was written)
|
|
2042
|
+
if (name !== null && (((name === this.comp.rest || name === this.comp.propsObject) && !svg) || this.domLocals.has(name)))
|
|
2043
|
+
return this.expr(e);
|
|
2044
|
+
const change = changeEvent(tag, attrs);
|
|
2045
|
+
const dropped = [];
|
|
2046
|
+
const styled = (value) => {
|
|
2047
|
+
this.script.helpers.add('toStyleString');
|
|
2048
|
+
return t.callExpression(t.identifier('toStyleString'), [value]);
|
|
2049
|
+
};
|
|
2050
|
+
// a constant whose literal has only the element's own names (motion props, `role`, `aria-*`) is spread as it is
|
|
2051
|
+
const literal = name !== null && t.isIdentifier(inner) ? this.constObject(inner.name) : null;
|
|
2052
|
+
if (literal && alreadyDomNamed(literal, svg, change))
|
|
2053
|
+
return this.expr(e);
|
|
2054
|
+
const written = staticDomProps(cloneWithRefs(e, this.comp), svg, change, styled, dropped);
|
|
2055
|
+
const lost = [...new Set(dropped)].filter((k) => k !== 'key' && !k.startsWith('suppress'));
|
|
2056
|
+
const shown = printInline(e).replace(/\s+/g, ' ');
|
|
2057
|
+
if (lost.length)
|
|
2058
|
+
this.script.warn('dom-spread', `{...${shown.length > 60 ? `${shown.slice(0, 57)}...` : shown}} on <${tag}> carries ${lost.join(', ')}, which React applies (a ref attached, children or HTML rendered) and a Svelte spread would set as attributes: left out here.`, 'warning', e.loc?.start.line);
|
|
2059
|
+
// React's onChange on a field reads `e.target` as the field, which Svelte types through `currentTarget` (as an
|
|
2060
|
+
// onChange written on the element)
|
|
2061
|
+
const fieldHandlers = (x) => {
|
|
2062
|
+
if (t.isConditionalExpression(x))
|
|
2063
|
+
return t.conditionalExpression(x.test, fieldHandlers(x.consequent), fieldHandlers(x.alternate));
|
|
2064
|
+
if (t.isLogicalExpression(x))
|
|
2065
|
+
return t.logicalExpression(x.operator, x.left, fieldHandlers(x.right));
|
|
2066
|
+
if (!t.isObjectExpression(x))
|
|
2067
|
+
return x;
|
|
2068
|
+
for (const p of x.properties)
|
|
2069
|
+
if (t.isObjectProperty(p) && t.isIdentifier(p.key, { name: `on${change}` }) && t.isExpression(p.value))
|
|
2070
|
+
p.value = changeTargetIsField(p.value);
|
|
2071
|
+
return x;
|
|
2072
|
+
};
|
|
2073
|
+
if (written)
|
|
2074
|
+
return this.expr(written, false, FIELD_TAGS.has(tag) ? fieldHandlers : undefined);
|
|
2075
|
+
this.script.helpers.add('domProps');
|
|
2076
|
+
this.script.helpers.add('toStyleString');
|
|
2077
|
+
if (svg)
|
|
2078
|
+
this.script.helpers.add('domPropsSvg');
|
|
2079
|
+
const args = [e, ...(change === 'input' ? [t.stringLiteral('input')] : [])];
|
|
2080
|
+
return this.expr(t.callExpression(t.identifier('domProps'), args));
|
|
2081
|
+
}
|
|
2082
|
+
/** The object literal a `const` of the component or of the module holds (`const ROW = { … }`), else null. */
|
|
2083
|
+
constObject(name) {
|
|
2084
|
+
const literal = (init) => {
|
|
2085
|
+
const inner = init && (t.isTSAsExpression(init) || t.isTSSatisfiesExpression(init) ? init.expression : init);
|
|
2086
|
+
return inner && t.isObjectExpression(inner) ? inner : null;
|
|
2087
|
+
};
|
|
2088
|
+
for (const item of this.comp.items) {
|
|
2089
|
+
if (item.kind === 'derived' && item.declKind === 'const' && t.isIdentifier(item.id, { name }))
|
|
2090
|
+
return literal(item.init);
|
|
2091
|
+
}
|
|
2092
|
+
if (this.comp.bindings.has(name) || this.comp.props.some((p) => p.local === name))
|
|
2093
|
+
return null;
|
|
2094
|
+
const body = this.script.ctx.moduleOf?.(this.script.ctx.sourceFile)?.moduleBody ?? [];
|
|
2095
|
+
for (const s of body) {
|
|
2096
|
+
const decl = t.isExportNamedDeclaration(s) ? s.declaration : s;
|
|
2097
|
+
if (!t.isVariableDeclaration(decl) || decl.kind !== 'const')
|
|
2098
|
+
continue;
|
|
2099
|
+
for (const d of decl.declarations)
|
|
2100
|
+
if (t.isIdentifier(d.id, { name }))
|
|
2101
|
+
return literal(d.init);
|
|
2102
|
+
}
|
|
2103
|
+
return null;
|
|
2104
|
+
}
|
|
2105
|
+
attrs(attrs, tag, component, facts) {
|
|
2106
|
+
const out = [];
|
|
2107
|
+
// an attribute passed to a component whose props are an element's attributes takes the attribute's name (dom-spread)
|
|
2108
|
+
const receiver = component ? this.script.childOf(tag) : null;
|
|
2109
|
+
const html = receiver?.extendsHtml ?? null;
|
|
2110
|
+
// (a prop it names itself, declared or destructured, keeps its name: `let { htmlFor, ...rest } = $props()`)
|
|
2111
|
+
const own = (key) => !!receiver && (receiver.declared.has(key) || receiver.props.some((p) => p.key === key));
|
|
2112
|
+
const named = (a) => {
|
|
2113
|
+
if (!html || !('name' in a) || (a.kind !== 'static' && a.kind !== 'bool' && a.kind !== 'expr') || own(a.name))
|
|
2114
|
+
return a;
|
|
2115
|
+
const name = inheritedAttributeName(a.name, !html.anyElement && SVG_TAGS.has(html.element));
|
|
2116
|
+
return name === a.name ? a : { ...a, name };
|
|
2117
|
+
};
|
|
2118
|
+
for (const a of attrs.map(named)) {
|
|
2119
|
+
switch (a.kind) {
|
|
2120
|
+
case 'static':
|
|
2121
|
+
out.push(`${a.name}="${this.quote(a.value)}"`);
|
|
2122
|
+
break;
|
|
2123
|
+
case 'bool':
|
|
2124
|
+
out.push(component ? `${a.name}={true}` : a.name);
|
|
2125
|
+
break;
|
|
2126
|
+
case 'expr': {
|
|
2127
|
+
// `text={children}`: React's children passed on as a value (text). A Svelte component's children are a
|
|
2128
|
+
// snippet, which has no text to read: said, not hidden
|
|
2129
|
+
const children = this.comp.props.find((p) => p.kind === 'children');
|
|
2130
|
+
const inner = unwrap(a.expr);
|
|
2131
|
+
if (children && t.isIdentifier(inner, { name: children.local }) && !textChildren(this.comp)) {
|
|
2132
|
+
this.script.warn('children-value', `"${children.local}" is passed on as a value (${a.name}); a Svelte component's children are a snippet, which has no text to read. Pass the text as a prop.`);
|
|
2133
|
+
}
|
|
2134
|
+
const e = this.expr(a.expr);
|
|
2135
|
+
out.push(e === a.name ? `{${e}}` : `${a.name}={${e}}`);
|
|
2136
|
+
break;
|
|
2137
|
+
}
|
|
2138
|
+
case 'spread':
|
|
2139
|
+
out.push(`{...${component ? this.expr(a.expr) : this.domSpread(a.expr, tag, attrs)}}`);
|
|
2140
|
+
break;
|
|
2141
|
+
case 'event': {
|
|
2142
|
+
// React's onFocus and onBlur bubble (React listens to focusin and focusout); the DOM's focus and blur do not
|
|
2143
|
+
const bubbling = !component && (a.react === 'onFocus' || a.react === 'onBlur');
|
|
2144
|
+
const dom = bubbling ? (a.name === 'focus' ? 'focusin' : 'focusout') : a.name;
|
|
2145
|
+
const name = component ? (isDomEventProp(a.name) ? a.name.toLowerCase() : a.name) : `on${dom}${a.capture ? 'capture' : ''}`;
|
|
2146
|
+
// React's wheel listener is passive (preventDefault there does nothing and the page scrolls); Svelte's
|
|
2147
|
+
// onwheel is not (touchstart and touchmove are passive in both): the same only for a handler that never stops it
|
|
2148
|
+
if (!component && a.name === 'wheel' && this.mayPreventDefault(a.handler)) {
|
|
2149
|
+
this.script.warn('wheel-passive', `<${tag}> onWheel: React listens to wheel passively, so its preventDefault() does nothing and the page still scrolls; Svelte's onwheel is not passive, so here preventDefault() stops the scroll.`);
|
|
2150
|
+
}
|
|
2151
|
+
const typed = component ? undefined : a.react === 'onChange' && FIELD_TAGS.has(tag) ? changeTargetIsField : UNTYPED_ELEMENT_EVENTS.has(a.name) && tag !== 'svelte:element' ? currentTargetIs(tag) : undefined;
|
|
2152
|
+
// React's `e.nativeEvent` is the DOM event itself, which a Svelte element handler is given
|
|
2153
|
+
// React's onChange listens to other DOM events (click on a checkbox, input on a text field): its nativeEvent is
|
|
2154
|
+
// that event (a click's shiftKey), where Svelte's onchange is given the change event
|
|
2155
|
+
if (!component && a.react === 'onChange' && readsNativeEvent(a.handler)) {
|
|
2156
|
+
this.script.warn('native-event', `<${tag}> onChange reads e.nativeEvent: React's onChange is fired by another DOM event (a click on a checkbox or radio, input on a text field) and nativeEvent is that event; Svelte's onchange is given the change event, so what is read from it (shiftKey, inputType) differs.`);
|
|
2157
|
+
}
|
|
2158
|
+
const post = component ? undefined : (x) => nativeEventIsEvent(typed ? typed(x) : x, a.react);
|
|
2159
|
+
// a handler written inside an {#if} on state reads it as the branch proved it (see the `if` node)
|
|
2160
|
+
const fn = unwrap(a.handler);
|
|
2161
|
+
let handler = a.handler;
|
|
2162
|
+
if (facts?.size && (t.isArrowFunctionExpression(fn) || t.isFunctionExpression(fn))) {
|
|
2163
|
+
const copy = cloneWithRefs(fn, this.comp);
|
|
2164
|
+
assertPaths(copy.body, facts);
|
|
2165
|
+
handler = copy;
|
|
2166
|
+
}
|
|
2167
|
+
const h = this.expr(handler, false, post);
|
|
2168
|
+
out.push(h === name ? `{${h}}` : `${name}={${h}}`);
|
|
2169
|
+
break;
|
|
2170
|
+
}
|
|
2171
|
+
case 'ref':
|
|
2172
|
+
out.push(this.ref(a.expr, tag, component));
|
|
2173
|
+
break;
|
|
2174
|
+
case 'style':
|
|
2175
|
+
// style: directives are for elements; a component receives its style as a string prop
|
|
2176
|
+
if (component) {
|
|
2177
|
+
this.script.helpers.add('toStyleString');
|
|
2178
|
+
out.push(`style={toStyleString(${this.styleArgs(a.expr)})}`);
|
|
2179
|
+
}
|
|
2180
|
+
else
|
|
2181
|
+
out.push(...this.style(a.expr));
|
|
2182
|
+
break;
|
|
2183
|
+
case 'html':
|
|
2184
|
+
case 'slotProp':
|
|
2185
|
+
break;
|
|
2186
|
+
}
|
|
2187
|
+
}
|
|
2188
|
+
return out.filter(Boolean);
|
|
2189
|
+
}
|
|
2190
|
+
ref(e, tag, component = false) {
|
|
2191
|
+
const inner = unwrap(e);
|
|
2192
|
+
// `ref={undefined}` (a component written in place whose caller passes no ref prop): React attaches no ref, and
|
|
2193
|
+
// neither does Svelte without one
|
|
2194
|
+
if ((t.isIdentifier(inner, { name: 'undefined' }) && !this.comp.bindings.has('undefined')) || t.isNullLiteral(inner))
|
|
2195
|
+
return '';
|
|
2196
|
+
if (t.isIdentifier(inner)) {
|
|
2197
|
+
const b = this.comp.bindings.get(inner.name);
|
|
2198
|
+
// a ref on a component that hands it one of its elements: the child's `ref` prop (see forwardOf)
|
|
2199
|
+
const child = component && b?.kind === 'ref' ? this.script.childOf(tag) : null;
|
|
2200
|
+
if (child && forwardsElement(child) && !b?.escapes)
|
|
2201
|
+
return `bind:ref={${inner.name}}`;
|
|
2202
|
+
if (this.comp.forwardRef === inner.name) {
|
|
2203
|
+
if (this.script.forward?.local === inner.name)
|
|
2204
|
+
return `bind:this={${inner.name}}`;
|
|
2205
|
+
const passed = component ? this.script.passedHandle(this.comp, tag) : null;
|
|
2206
|
+
if (passed)
|
|
2207
|
+
return `bind:this={${passed}}`;
|
|
2208
|
+
const branch = component ? this.script.passedBranch(this.comp, tag) : null;
|
|
2209
|
+
if (branch)
|
|
2210
|
+
return `bind:this={${branch}}`;
|
|
2211
|
+
this.script.warn('forward-ref', `The ref is forwarded to <${tag}>, another component: ${this.script.forwardProblem(tag)}`);
|
|
2212
|
+
return '';
|
|
2213
|
+
}
|
|
2214
|
+
if (b?.kind === 'ref' && b.refKind === 'dom' && !b.escapes)
|
|
2215
|
+
return `bind:this={${inner.name}}`;
|
|
2216
|
+
if (b && (b.kind === 'ref' || b.kind === 'hook' || b.kind === 'prop'))
|
|
2217
|
+
return `bind:this={${inner.name}.current}`;
|
|
2218
|
+
}
|
|
2219
|
+
if (t.isArrowFunctionExpression(inner) || t.isFunctionExpression(inner) || t.isIdentifier(inner)) {
|
|
2220
|
+
// a callback ref on a component of the conversion that hands its ref a handle: React calls it with the handle
|
|
2221
|
+
// (and, for a function written inline, again with null and the handle after every render of this component);
|
|
2222
|
+
// an attachment on a Svelte component reaches an element only, and only one the component spreads its props on
|
|
2223
|
+
const handleChild = component ? this.script.childOf(tag) : null;
|
|
2224
|
+
if (handleChild && !forwardsElement(handleChild) && reachedMembers(handleChild, (parent, name) => this.script.childOfAny(parent, name))) {
|
|
2225
|
+
this.script.warn('component-callback-ref', `The callback ref on <${tag}> receives its imperative handle in React, called again with null and the handle after every render when the function is written inline; a Svelte component has no per-render call and its attachments reach elements only, so the callback is not converted.`);
|
|
2226
|
+
return '';
|
|
2227
|
+
}
|
|
2228
|
+
// written inline, React calls it again (null, then the element) after every render; the attachment re-runs only
|
|
2229
|
+
// when a value the call read changes (see ref-callback.ts)
|
|
2230
|
+
if (!t.isIdentifier(inner) && !settlesLikeReact(inner)) {
|
|
2231
|
+
this.script.warn('ref-callback', `The callback ref on <${tag}> is written inline, so React calls it again after every render of this component (with null, then the element); the Svelte attachment runs it when the element mounts, again only when a reactive value it read changes, and with null when the element goes. Its body does more than store the element, so those extra calls change what it does: keep the callback to storing the element (\`x = el\`, \`map.set(key, el)\` / \`map.delete(key)\`).`);
|
|
2232
|
+
}
|
|
2233
|
+
const fn = this.expr(e);
|
|
2234
|
+
// typed as React types a callback ref: the element, or null when it goes
|
|
2235
|
+
return `{@attach (${attachParam(tag)}) => { const set: (el: ${printInline(domElementType(tag))} | null) => void = ${fn}; set(node); return () => set(null); }}`;
|
|
2236
|
+
}
|
|
2237
|
+
// a ref given only while a test holds (`ref={after ? afterEl : undefined}`): an attachment while it holds, which
|
|
2238
|
+
// fills the ref and empties it when it goes (the test turning false re-creates the attachment, as React re-attaches)
|
|
2239
|
+
if (t.isConditionalExpression(inner) && !component) {
|
|
2240
|
+
const empty = (x) => t.isNullLiteral(unwrap(x)) || t.isIdentifier(unwrap(x), { name: 'undefined' });
|
|
2241
|
+
const target = (x) => {
|
|
2242
|
+
const id = unwrap(x);
|
|
2243
|
+
const b = t.isIdentifier(id) ? this.comp.bindings.get(id.name) : undefined;
|
|
2244
|
+
if (!t.isIdentifier(id) || b?.kind !== 'ref' || this.comp.forwardRef === id.name)
|
|
2245
|
+
return null;
|
|
2246
|
+
return b.refKind === 'dom' && !b.escapes ? id.name : `${id.name}.current`;
|
|
2247
|
+
};
|
|
2248
|
+
const [yes, no] = [target(inner.consequent), target(inner.alternate)];
|
|
2249
|
+
const set = yes && empty(inner.alternate) ? yes : no && empty(inner.consequent) ? no : null;
|
|
2250
|
+
if (set) {
|
|
2251
|
+
const attach = `(${attachParam(tag)}) => { ${set} = node; return () => { ${set} = null; }; }`;
|
|
2252
|
+
const test = this.expr(inner.test);
|
|
2253
|
+
return `{@attach ${yes === set ? `${test} ? ${attach} : undefined` : `${test} ? undefined : ${attach}`}}`;
|
|
2254
|
+
}
|
|
2255
|
+
}
|
|
2256
|
+
this.script.warn('ref-expression', `An unusual ref on <${tag}> is not converted.`, 'error');
|
|
2257
|
+
return '';
|
|
2258
|
+
}
|
|
2259
|
+
/** React adds px to numeric style values; Svelte style directives do not. */
|
|
2260
|
+
style(e) {
|
|
2261
|
+
const obj = unwrap(e);
|
|
2262
|
+
if (t.isObjectExpression(obj) && obj.properties.every((p) => t.isObjectProperty(p) && styleKey(p) !== null)) {
|
|
2263
|
+
return obj.properties.map((p) => {
|
|
2264
|
+
const key = styleKey(p) ?? '';
|
|
2265
|
+
const num = numericLiteral(p.value);
|
|
2266
|
+
let value;
|
|
2267
|
+
if (num !== null)
|
|
2268
|
+
value = `"${String(reactStyleValue(key, num))}"`;
|
|
2269
|
+
else if (t.isStringLiteral(p.value))
|
|
2270
|
+
value = `"${this.quote(p.value.value)}"`;
|
|
2271
|
+
else if (!isUnitless(key) && t.isExpression(p.value) && !isStringy(unwrap(p.value))) {
|
|
2272
|
+
this.script.helpers.add('toPx');
|
|
2273
|
+
value = `{toPx(${this.expr(p.value)})}`;
|
|
2274
|
+
}
|
|
2275
|
+
else
|
|
2276
|
+
value = `{${this.expr(p.value)}}`;
|
|
2277
|
+
return `style:${kebabCase(key)}=${value}`;
|
|
2278
|
+
});
|
|
2279
|
+
}
|
|
2280
|
+
this.script.helpers.add('toStyleString');
|
|
2281
|
+
return [`style={toStyleString(${this.styleArgs(e)})}`];
|
|
2282
|
+
}
|
|
2283
|
+
/**
|
|
2284
|
+
* The arguments of toStyleString for a style object. A Svelte component receives its `style` as a string (its parent
|
|
2285
|
+
* passes toStyleString's result), so a spread of that prop (`{ ...base, ...style }`) becomes a part of its own,
|
|
2286
|
+
* in order: `toStyleString({ ...base }, style)`.
|
|
2287
|
+
*/
|
|
2288
|
+
styleArgs(e) {
|
|
2289
|
+
const obj = unwrap(e);
|
|
2290
|
+
if (this.asSnippet || !t.isObjectExpression(obj) || !obj.properties.some((p) => t.isSpreadElement(p) && this.isStyleProp(p.argument)))
|
|
2291
|
+
return this.expr(e);
|
|
2292
|
+
const parts = [];
|
|
2293
|
+
let run = [];
|
|
2294
|
+
for (const p of obj.properties) {
|
|
2295
|
+
if (t.isSpreadElement(p) && this.isStyleProp(p.argument)) {
|
|
2296
|
+
if (run.length)
|
|
2297
|
+
parts.push(t.objectExpression(run));
|
|
2298
|
+
run = [];
|
|
2299
|
+
parts.push(p.argument);
|
|
2300
|
+
}
|
|
2301
|
+
else
|
|
2302
|
+
run.push(p);
|
|
2303
|
+
}
|
|
2304
|
+
if (run.length)
|
|
2305
|
+
parts.push(t.objectExpression(run));
|
|
2306
|
+
return parts.map((p) => this.expr(p)).join(', ');
|
|
2307
|
+
}
|
|
2308
|
+
/** The component's own `style` prop (`style`, or `props.style`), while it holds the string the parent passed. */
|
|
2309
|
+
isStyleProp(e) {
|
|
2310
|
+
if (this.styleObject)
|
|
2311
|
+
return false;
|
|
2312
|
+
if (t.isIdentifier(e))
|
|
2313
|
+
return this.comp.props.some((p) => p.kind === 'style' && p.local === e.name);
|
|
2314
|
+
return !!this.comp.propsObject && t.isMemberExpression(e) && !e.computed && t.isIdentifier(e.object, { name: this.comp.propsObject }) && t.isIdentifier(e.property, { name: 'style' });
|
|
2315
|
+
}
|
|
2316
|
+
}
|
|
2317
|
+
/**
|
|
2318
|
+
* `<Child {...rest} />`: React forwards whatever children the rest carries, and the compiler adds a default slot (and an
|
|
2319
|
+
* undeclared `children` prop) to say so. A Svelte component's children are a prop like any other, so the rest forwards
|
|
2320
|
+
* them itself: when every such slot sits alone in a component that spreads the rest, `children` stays in the rest and
|
|
2321
|
+
* the slots are dropped (the child then gets exactly what React's rest gave it, typed by its own props). Returns those
|
|
2322
|
+
* component elements, or null.
|
|
2323
|
+
*/
|
|
2324
|
+
function restForwardedChildren(comp) {
|
|
2325
|
+
const prop = comp.props.find((p) => p.key === 'children' && p.kind === 'children' && p.inherited);
|
|
2326
|
+
if (!prop || !comp.rest || comp.propsStyle !== 'destructured')
|
|
2327
|
+
return null;
|
|
2328
|
+
const rest = comp.rest;
|
|
2329
|
+
const forwarded = new Set();
|
|
2330
|
+
let other = false;
|
|
2331
|
+
const spreadsRest = (n) => n.attrs.some((a) => a.kind === 'spread' && t.isIdentifier(unwrap(a.expr), { name: rest }));
|
|
2332
|
+
const visit = (n, parent, siblings) => {
|
|
2333
|
+
switch (n.type) {
|
|
2334
|
+
case 'slot':
|
|
2335
|
+
if (n.prop === prop.local) {
|
|
2336
|
+
if (parent?.component && siblings === 1 && spreadsRest(parent))
|
|
2337
|
+
forwarded.add(parent);
|
|
2338
|
+
else
|
|
2339
|
+
other = true;
|
|
2340
|
+
}
|
|
2341
|
+
n.fallback.forEach((c) => visit(c, null, 0));
|
|
2342
|
+
return;
|
|
2343
|
+
case 'element':
|
|
2344
|
+
for (const a of n.attrs)
|
|
2345
|
+
if (a.kind === 'slotProp')
|
|
2346
|
+
a.children.forEach((c) => visit(c, null, 0));
|
|
2347
|
+
n.children.forEach((c) => visit(c, n, n.children.length));
|
|
2348
|
+
return;
|
|
2349
|
+
case 'if':
|
|
2350
|
+
n.branches.forEach((b) => b.children.forEach((c) => visit(c, null, 0)));
|
|
2351
|
+
return;
|
|
2352
|
+
case 'for':
|
|
2353
|
+
case 'fragment':
|
|
2354
|
+
case 'keyed':
|
|
2355
|
+
case 'presence':
|
|
2356
|
+
n.children.forEach((c) => visit(c, null, 0));
|
|
2357
|
+
return;
|
|
2358
|
+
default:
|
|
2359
|
+
return;
|
|
2360
|
+
}
|
|
2361
|
+
};
|
|
2362
|
+
visit(comp.template, null, 0);
|
|
2363
|
+
return forwarded.size && !other ? forwarded : null;
|
|
2364
|
+
}
|
|
2365
|
+
/**
|
|
2366
|
+
* A Svelte component receives `style` as a string (its parent passes `style={toStyleString(...)}`), where React's got an
|
|
2367
|
+
* object. When the component's script reads it as one (`{ ...base, ...style }`, `style.width`), the string is read back
|
|
2368
|
+
* into the object React had, once, where the props arrive: returns that prop, or null when the markup alone uses it
|
|
2369
|
+
* (there `toStyleString` takes the string as it is).
|
|
2370
|
+
*/
|
|
2371
|
+
function styleObjectProp(comp) {
|
|
2372
|
+
if (comp.propsStyle !== 'destructured')
|
|
2373
|
+
return null;
|
|
2374
|
+
const p = comp.props.find((x) => x.key === 'style' && x.kind === 'style' && !x.defaultValue);
|
|
2375
|
+
if (!p)
|
|
2376
|
+
return null;
|
|
2377
|
+
const declared = comp.declared.get('style');
|
|
2378
|
+
// a `style` prop of some other type (`style?: 'solid' | 'dashed'`) is not a style object
|
|
2379
|
+
const text = (x) => t.isTSStringKeyword(x) || t.isTSLiteralType(x) || t.isTSNumberKeyword(x) || (t.isTSUnionType(x) && x.types.every((y) => text(y) || t.isTSUndefinedKeyword(y)));
|
|
2380
|
+
if (declared?.type && text(declared.type))
|
|
2381
|
+
return null;
|
|
2382
|
+
const nodes = [];
|
|
2383
|
+
for (const item of comp.items) {
|
|
2384
|
+
if (item.kind === 'state' || item.kind === 'ref')
|
|
2385
|
+
nodes.push(...(item.init ? [item.init] : []));
|
|
2386
|
+
else if (item.kind === 'reducer')
|
|
2387
|
+
nodes.push(item.reducer, item.init);
|
|
2388
|
+
else if (item.kind === 'derived')
|
|
2389
|
+
nodes.push(item.init);
|
|
2390
|
+
else if (item.kind === 'block')
|
|
2391
|
+
nodes.push(...item.statements);
|
|
2392
|
+
else if (item.kind === 'function')
|
|
2393
|
+
nodes.push(item.node);
|
|
2394
|
+
else if (item.kind === 'effect')
|
|
2395
|
+
nodes.push(item.body, ...(item.deps ?? []));
|
|
2396
|
+
else if (item.kind === 'hook')
|
|
2397
|
+
nodes.push(item.call);
|
|
2398
|
+
else if (item.kind === 'statement')
|
|
2399
|
+
nodes.push(item.node);
|
|
2400
|
+
else if (item.kind === 'expose')
|
|
2401
|
+
nodes.push(item.object);
|
|
2402
|
+
}
|
|
2403
|
+
if (nodes.some((n) => bindingsUsed(n, comp).has(p.local)))
|
|
2404
|
+
return p;
|
|
2405
|
+
// in the markup, a style attribute takes the string as it is (`style={style}`, `{ ...base, ...style }`): any other
|
|
2406
|
+
// use (`cardStyle(style)`, `style.width`) wants the object
|
|
2407
|
+
const asAttribute = new Set();
|
|
2408
|
+
const other = [];
|
|
2409
|
+
const isStyle = (e) => t.isIdentifier(e) && comp.refs.get(e) === p.local;
|
|
2410
|
+
const walk = (value) => {
|
|
2411
|
+
if (!value || typeof value !== 'object')
|
|
2412
|
+
return;
|
|
2413
|
+
if (Array.isArray(value))
|
|
2414
|
+
return value.forEach(walk);
|
|
2415
|
+
const node = value;
|
|
2416
|
+
// Babel's node types are PascalCase; the template's own nodes and attributes are lower case
|
|
2417
|
+
if (typeof node.type === 'string' && /^[A-Z]/.test(node.type)) {
|
|
2418
|
+
other.push(value);
|
|
2419
|
+
return;
|
|
2420
|
+
}
|
|
2421
|
+
if (node.kind === 'style' && node.expr && typeof node.expr === 'object') {
|
|
2422
|
+
const style = unwrap(node.expr);
|
|
2423
|
+
if (isStyle(style))
|
|
2424
|
+
asAttribute.add(style);
|
|
2425
|
+
else if (t.isObjectExpression(style))
|
|
2426
|
+
for (const q of style.properties)
|
|
2427
|
+
if (t.isSpreadElement(q) && isStyle(q.argument))
|
|
2428
|
+
asAttribute.add(q.argument);
|
|
2429
|
+
}
|
|
2430
|
+
for (const v of Object.values(value))
|
|
2431
|
+
walk(v);
|
|
2432
|
+
};
|
|
2433
|
+
walk(comp.template);
|
|
2434
|
+
let read = false;
|
|
2435
|
+
for (const n of other) {
|
|
2436
|
+
t.traverseFast(n, (x) => {
|
|
2437
|
+
if (isStyle(x) && !asAttribute.has(x))
|
|
2438
|
+
read = true;
|
|
2439
|
+
});
|
|
2440
|
+
}
|
|
2441
|
+
return read ? p : null;
|
|
2442
|
+
}
|
|
2443
|
+
/** A render prop's type as a snippet's: `(picked: Row[], count?: number) => ReactNode` is `Snippet<[Row[], number?]>`. */
|
|
2444
|
+
function snippetType(params, script) {
|
|
2445
|
+
script.typeImports.push({ source: 'svelte', name: 'Snippet' });
|
|
2446
|
+
const members = params.map((p) => {
|
|
2447
|
+
const type = script.type(p.type) ?? t.tsUnknownKeyword();
|
|
2448
|
+
return p.optional ? t.tsOptionalType(type) : type;
|
|
2449
|
+
});
|
|
2450
|
+
return t.tsTypeReference(t.identifier('Snippet'), members.length ? t.tsTypeParameterInstantiation([t.tsTupleType(members)]) : null);
|
|
2451
|
+
}
|
|
2452
|
+
/**
|
|
2453
|
+
* An element's attributes as the object a Slot's `child` snippet receives (`{ 'data-slot': 'button', class: …,
|
|
2454
|
+
* onclick: …, ...rest }`), keyed as Svelte writes them on an element; null when one has no place there (a style, a ref,
|
|
2455
|
+
* markup).
|
|
2456
|
+
*/
|
|
2457
|
+
function attrsObject(attrs) {
|
|
2458
|
+
const out = [];
|
|
2459
|
+
const key = (name) => (/^[A-Za-z_$][\w$]*$/.test(name) ? t.identifier(name) : t.stringLiteral(name));
|
|
2460
|
+
for (const a of attrs) {
|
|
2461
|
+
switch (a.kind) {
|
|
2462
|
+
case 'static':
|
|
2463
|
+
out.push(t.objectProperty(key(a.name), t.stringLiteral(a.value)));
|
|
2464
|
+
break;
|
|
2465
|
+
case 'bool':
|
|
2466
|
+
out.push(t.objectProperty(key(a.name), t.booleanLiteral(true)));
|
|
2467
|
+
break;
|
|
2468
|
+
case 'expr':
|
|
2469
|
+
out.push(t.objectProperty(key(a.name), a.expr));
|
|
2470
|
+
break;
|
|
2471
|
+
case 'spread':
|
|
2472
|
+
out.push(t.spreadElement(a.expr));
|
|
2473
|
+
break;
|
|
2474
|
+
case 'event':
|
|
2475
|
+
out.push(t.objectProperty(key(`on${a.name}${a.capture ? 'capture' : ''}`), a.handler));
|
|
2476
|
+
break;
|
|
2477
|
+
default:
|
|
2478
|
+
return null;
|
|
2479
|
+
}
|
|
2480
|
+
}
|
|
2481
|
+
return t.objectExpression(out);
|
|
2482
|
+
}
|
|
2483
|
+
/** How many parameters a handler takes, when the component's code says (a function, a prop typed as one); else null. */
|
|
2484
|
+
function handlerArity(handler, comp) {
|
|
2485
|
+
if (t.isFunction(handler))
|
|
2486
|
+
return handler.params.length;
|
|
2487
|
+
if (!t.isIdentifier(handler))
|
|
2488
|
+
return null;
|
|
2489
|
+
const name = comp.refs.get(handler) ?? handler.name;
|
|
2490
|
+
const prop = comp.props.find((p) => p.local === name);
|
|
2491
|
+
const declared = prop ? (comp.declared.get(prop.key)?.type ?? prop.type) : null;
|
|
2492
|
+
if (declared && t.isTSFunctionType(declared))
|
|
2493
|
+
return declared.parameters.length;
|
|
2494
|
+
for (const item of comp.items) {
|
|
2495
|
+
if (item.kind === 'function' && item.name === name)
|
|
2496
|
+
return item.node.params.length;
|
|
2497
|
+
if (item.kind === 'derived' && item.names.length === 1 && item.names[0] === name && t.isFunction(unwrap(item.init)))
|
|
2498
|
+
return handlerArity(unwrap(item.init), comp);
|
|
2499
|
+
}
|
|
2500
|
+
return null;
|
|
2501
|
+
}
|
|
2502
|
+
/** The snippet prop a component rendering Radix's Slot takes the element in (bits-ui's name for it). */
|
|
2503
|
+
const SLOT_CHILD = 'child';
|
|
2504
|
+
/** Whether a component renders a Radix Slot (ir/as-child) and can take the `child` snippet prop for it. */
|
|
2505
|
+
function slotChildProp(comp) {
|
|
2506
|
+
if (!asChildElements(comp).length)
|
|
2507
|
+
return false;
|
|
2508
|
+
if (comp.props.some((p) => p.key === SLOT_CHILD || p.local === SLOT_CHILD) || comp.declared.has(SLOT_CHILD) || comp.bindings.has(SLOT_CHILD))
|
|
2509
|
+
return false;
|
|
2510
|
+
return comp.propsStyle === 'destructured' || (comp.propsStyle === 'object' && !!comp.propsObject);
|
|
2511
|
+
}
|
|
2512
|
+
/** `Snippet<[{ props: Record<string, unknown> }]>`: the snippet receives the attributes to spread on its element. */
|
|
2513
|
+
function slotChildType() {
|
|
2514
|
+
const props = t.tsPropertySignature(t.identifier('props'), t.tsTypeAnnotation(t.tsTypeReference(t.identifier('Record'), t.tsTypeParameterInstantiation([t.tsStringKeyword(), t.tsUnknownKeyword()]))));
|
|
2515
|
+
return t.tsTypeReference(t.identifier('Snippet'), t.tsTypeParameterInstantiation([t.tsTupleType([t.tsTypeLiteral([props])])]));
|
|
2516
|
+
}
|
|
2517
|
+
/** The `$props()` declaration and the Props type, Svelte-style (`class` and lower-case DOM events). */
|
|
2518
|
+
function propsDeclaration(comp, script, restChildren = false, styleAttr = null) {
|
|
2519
|
+
const members = [];
|
|
2520
|
+
const add = (key, type, optional) => {
|
|
2521
|
+
const sig = t.tsPropertySignature(/^[A-Za-z_$][\w$]*$/.test(key) ? t.identifier(key) : t.stringLiteral(key), t.tsTypeAnnotation(type ?? t.tsUnknownKeyword()));
|
|
2522
|
+
sig.optional = optional;
|
|
2523
|
+
members.push(sig);
|
|
2524
|
+
};
|
|
2525
|
+
const outKey = (key) => (key === 'className' ? 'class' : isDomEventProp(key) ? key.toLowerCase() : key);
|
|
2526
|
+
const kinds = new Map(comp.props.map((p) => [p.key, p.kind]));
|
|
2527
|
+
// `ComponentProps<'input'>`: the tag's own attributes (Svelte's SvelteHTMLElements['input']), whatever the tag
|
|
2528
|
+
const byTag = !!comp.extendsHtml && !comp.extendsHtml.anyElement && /^(ComponentProps\w*|DetailedHTMLProps)$/.test(comp.extendsHtml.react);
|
|
2529
|
+
// the rest lands on the element it is spread onto (`ComponentProps<'div'>` spread on a <kbd>): Svelte types each
|
|
2530
|
+
// element's attributes, handlers included, so they are that element's
|
|
2531
|
+
const spreadTag = byTag ? restElementTag(comp) : null;
|
|
2532
|
+
// (an SVG tag's element is the DOM's SVG one: `SVGProps<SVGSVGElement>` is SVGAttributes<SVGSVGElement>)
|
|
2533
|
+
const elementParam = (html) => byTag ? t.tsLiteralType(t.stringLiteral(spreadTag ?? html.element)) : !html.anyElement && SVG_TAGS.has(html.element) ? domElementType(html.element) : t.tsTypeReference(t.identifier(html.anyElement ? 'HTMLElement' : `HTML${elementTypeName(html.element)}Element`));
|
|
2534
|
+
const htmlType = comp.extendsHtml ? mapReactTypes(t.tsTypeReference(t.tsQualifiedName(t.identifier('React'), t.identifier(byTag ? 'ComponentProps' : comp.extendsHtml.react)), comp.extendsHtml.element ? t.tsTypeParameterInstantiation([elementParam(comp.extendsHtml)]) : null), 'svelte', new Set(), script.typeImports) : null;
|
|
2535
|
+
const seen = new Set();
|
|
2536
|
+
for (const [key, m] of comp.declared) {
|
|
2537
|
+
if (key === 'ref' || key === 'key')
|
|
2538
|
+
continue;
|
|
2539
|
+
seen.add(key);
|
|
2540
|
+
if (key === 'children' && textChildren(comp)) {
|
|
2541
|
+
// children React types as text: a prop holding the text, as the parent passes it
|
|
2542
|
+
add('children', script.type(m.type), m.optional);
|
|
2543
|
+
continue;
|
|
2544
|
+
}
|
|
2545
|
+
if (key === 'children') {
|
|
2546
|
+
// children as a render function (`(close) => ReactNode`) is a snippet taking its values
|
|
2547
|
+
const render = renderSignature(m.type);
|
|
2548
|
+
script.typeImports.push({ source: 'svelte', name: 'Snippet' });
|
|
2549
|
+
add('children', render ? snippetType(render, script) : t.tsTypeReference(t.identifier('Snippet')), render ? m.optional : true);
|
|
2550
|
+
continue;
|
|
2551
|
+
}
|
|
2552
|
+
const render = renderSignature(m.type);
|
|
2553
|
+
const type = render
|
|
2554
|
+
? snippetType(render, script)
|
|
2555
|
+
: kinds.get(key) === 'node' && !m.type
|
|
2556
|
+
? (script.typeImports.push({ source: 'svelte', name: 'Snippet' }), t.tsUnionType([t.tsTypeReference(t.identifier('Snippet')), t.tsStringKeyword(), t.tsNumberKeyword()]))
|
|
2557
|
+
: script.type(m.type);
|
|
2558
|
+
// a style object arrives as the string its parent's toStyleString made
|
|
2559
|
+
add(outKey(key), key === 'style' && isStyleObjectType(type) ? t.tsStringKeyword() : type, m.optional);
|
|
2560
|
+
}
|
|
2561
|
+
// the members the interface's own `extends` give (`extends Omit<CpuCanvasProps, 'layers'>`): the Props type keeps
|
|
2562
|
+
// them through the heritage it intersects, typed as written there
|
|
2563
|
+
let inheritedKeys = null;
|
|
2564
|
+
const heritageOf = (key) => {
|
|
2565
|
+
if (!inheritedKeys) {
|
|
2566
|
+
inheritedKeys = new Map();
|
|
2567
|
+
for (const h of comp.propsHeritage) {
|
|
2568
|
+
const printed = script.type(h);
|
|
2569
|
+
if (!printed)
|
|
2570
|
+
continue;
|
|
2571
|
+
for (const k of script.ctx.types.members(h, script.ctx.sourceFile)?.keys() ?? [])
|
|
2572
|
+
if (!inheritedKeys.has(k))
|
|
2573
|
+
inheritedKeys.set(k, printed);
|
|
2574
|
+
}
|
|
2575
|
+
}
|
|
2576
|
+
return inheritedKeys.get(key) ?? null;
|
|
2577
|
+
};
|
|
2578
|
+
const fromHeritage = (key) => heritageOf(key) !== null;
|
|
2579
|
+
for (const p of comp.props) {
|
|
2580
|
+
if (seen.has(p.key) || p.key === 'ref' || p.key === 'key')
|
|
2581
|
+
continue;
|
|
2582
|
+
if (htmlType && p.inherited)
|
|
2583
|
+
continue;
|
|
2584
|
+
// (children stay a snippet here: the heritage types them as React's node)
|
|
2585
|
+
if (p.inherited && p.key !== 'children' && outKey(p.key) === p.key && fromHeritage(p.key))
|
|
2586
|
+
continue;
|
|
2587
|
+
if (p.key === 'children') {
|
|
2588
|
+
script.typeImports.push({ source: 'svelte', name: 'Snippet' });
|
|
2589
|
+
add('children', t.tsTypeReference(t.identifier('Snippet')), true);
|
|
2590
|
+
}
|
|
2591
|
+
else if (p.key === 'style')
|
|
2592
|
+
add('style', t.tsStringKeyword(), true);
|
|
2593
|
+
else {
|
|
2594
|
+
// a handler the heritage declares under React's name (`onChange?: (id, tier, index) => void`) arrives under
|
|
2595
|
+
// Svelte's lower-case one, typed as the heritage types it: `onchange?: BuildTierCardProps['onChange']`
|
|
2596
|
+
const inherited = p.inherited && outKey(p.key) !== p.key && isDomEventProp(p.key) ? heritageOf(p.key) : null;
|
|
2597
|
+
add(outKey(p.key), inherited ? t.tsIndexedAccessType(t.cloneNode(inherited, true), t.tsLiteralType(t.stringLiteral(p.key))) : inheritedAttrType(p.key, p.defaultValue), true);
|
|
2598
|
+
}
|
|
2599
|
+
}
|
|
2600
|
+
// Radix's Slot (ir/as-child): the caller passes the element to merge onto as the `child` snippet, given the attributes
|
|
2601
|
+
if (slotChildProp(comp)) {
|
|
2602
|
+
script.typeImports.push({ source: 'svelte', name: 'Snippet' });
|
|
2603
|
+
add(SLOT_CHILD, slotChildType(), true);
|
|
2604
|
+
}
|
|
2605
|
+
// props read off the object (`props.className` reads `props.class`): the heritage's React-named members arrive under
|
|
2606
|
+
// Svelte's names, typed as the heritage types them (`class?: EditorSliderProps['className']`)
|
|
2607
|
+
if (comp.propsStyle === 'object' && comp.propsObject) {
|
|
2608
|
+
const named = new Set(members.map((m) => (t.isIdentifier(m.key) ? m.key.name : t.isStringLiteral(m.key) ? m.key.value : '')));
|
|
2609
|
+
for (const h of comp.propsHeritage) {
|
|
2610
|
+
for (const k of script.ctx.types.members(h, script.ctx.sourceFile)?.keys() ?? []) {
|
|
2611
|
+
const out = outKey(k);
|
|
2612
|
+
const holder = heritageOf(k);
|
|
2613
|
+
if (out === k || named.has(out) || !holder || (k !== 'className' && !isDomEventProp(k)))
|
|
2614
|
+
continue;
|
|
2615
|
+
named.add(out);
|
|
2616
|
+
add(out, t.tsIndexedAccessType(t.cloneNode(holder, true), t.tsLiteralType(t.stringLiteral(k))), true);
|
|
2617
|
+
}
|
|
2618
|
+
}
|
|
2619
|
+
}
|
|
2620
|
+
const forward = script.forward;
|
|
2621
|
+
if (forward)
|
|
2622
|
+
add('ref', orNull(forward.type), true);
|
|
2623
|
+
const heritage = comp.propsHeritage.map((h) => script.type(h) ?? t.tsUnknownKeyword());
|
|
2624
|
+
const parts = [...(htmlType ? [htmlType] : []), ...heritage, t.tsTypeLiteral(members)];
|
|
2625
|
+
const statements = [t.tsTypeAliasDeclaration(t.identifier('Props'), null, parts.length > 1 ? t.tsIntersectionType(parts) : (parts[0] ?? t.tsTypeLiteral([])))];
|
|
2626
|
+
const propsCall = t.callExpression(t.identifier('$props'), []);
|
|
2627
|
+
if (comp.propsStyle === 'object' && comp.propsObject) {
|
|
2628
|
+
const id = t.identifier(comp.propsObject);
|
|
2629
|
+
id.typeAnnotation = t.tsTypeAnnotation(t.tsTypeReference(t.identifier('Props')));
|
|
2630
|
+
statements.push(t.variableDeclaration('let', [t.variableDeclarator(id, propsCall)]));
|
|
2631
|
+
script.propRenames.set('className', 'class');
|
|
2632
|
+
for (const p of comp.props)
|
|
2633
|
+
if (isDomEventProp(p.key))
|
|
2634
|
+
script.propRenames.set(p.key, p.key.toLowerCase());
|
|
2635
|
+
for (const [key] of comp.declared)
|
|
2636
|
+
if (isDomEventProp(key))
|
|
2637
|
+
script.propRenames.set(key, key.toLowerCase());
|
|
2638
|
+
return statements;
|
|
2639
|
+
}
|
|
2640
|
+
if (comp.propsStyle !== 'destructured' && !forward)
|
|
2641
|
+
return statements;
|
|
2642
|
+
const props = [];
|
|
2643
|
+
const text = textChildren(comp);
|
|
2644
|
+
for (const p of comp.props) {
|
|
2645
|
+
if (p.key === 'ref' || p.key === 'key')
|
|
2646
|
+
continue;
|
|
2647
|
+
// left in the rest, which forwards it (see restForwardedChildren)
|
|
2648
|
+
if (restChildren && p.key === 'children' && p.inherited)
|
|
2649
|
+
continue;
|
|
2650
|
+
const key = outKey(p.key);
|
|
2651
|
+
const keyNode = /^[A-Za-z_$][\w$]*$/.test(key) ? t.identifier(key) : t.stringLiteral(key);
|
|
2652
|
+
// the style string arrives under its own name; the component's own name holds it as an object (styleObjectProp)
|
|
2653
|
+
const local = styleAttr && p.kind === 'style' ? styleAttr : p.local;
|
|
2654
|
+
// a snippet's default is markup (the slot's fallback); text children default as any prop does
|
|
2655
|
+
const defaulted = !!p.defaultValue && (p.kind !== 'children' || text);
|
|
2656
|
+
const value = defaulted && p.defaultValue ? t.assignmentPattern(t.identifier(local), t.cloneNode(p.defaultValue, true)) : t.identifier(local);
|
|
2657
|
+
props.push(t.objectProperty(keyNode, value, false, t.isIdentifier(keyNode) && keyNode.name === local && !defaulted));
|
|
2658
|
+
}
|
|
2659
|
+
if (forward) {
|
|
2660
|
+
props.push(t.objectProperty(t.identifier('ref'), t.assignmentPattern(t.identifier(forward.local), t.callExpression(t.identifier('$bindable'), [t.nullLiteral()])), false, forward.local === 'ref'));
|
|
2661
|
+
}
|
|
2662
|
+
if (slotChildProp(comp))
|
|
2663
|
+
props.push(t.objectProperty(t.identifier(SLOT_CHILD), t.identifier(SLOT_CHILD), false, true));
|
|
2664
|
+
if (comp.rest) {
|
|
2665
|
+
props.push(t.restElement(t.identifier(comp.rest)));
|
|
2666
|
+
// `rest.className` reads the rest's `class`
|
|
2667
|
+
script.propRenames.set('className', 'class');
|
|
2668
|
+
}
|
|
2669
|
+
const pattern = t.objectPattern(props);
|
|
2670
|
+
pattern.typeAnnotation = t.tsTypeAnnotation(t.tsTypeReference(t.identifier('Props')));
|
|
2671
|
+
statements.push(t.variableDeclaration('let', [t.variableDeclarator(pattern, propsCall)]));
|
|
2672
|
+
return statements;
|
|
2673
|
+
}
|
|
2674
|
+
/**
|
|
2675
|
+
* A prop typed `ElementType` (mapped to `Component`) that the markup renders as `<svelte:element this={…}>`, directly
|
|
2676
|
+
* or through a value built from it (`const Tag = as || 'div'`), takes a tag name: `<svelte:element>` renders no
|
|
2677
|
+
* component. Its type says so (`keyof SvelteHTMLElements`), as the `dynamic-tag` note does.
|
|
2678
|
+
*/
|
|
2679
|
+
function narrowTagProps(statements, comp, tagNames, script) {
|
|
2680
|
+
if (!tagNames.size)
|
|
2681
|
+
return;
|
|
2682
|
+
const locals = new Set();
|
|
2683
|
+
for (const name of tagNames) {
|
|
2684
|
+
if (comp.props.some((p) => p.local === name))
|
|
2685
|
+
locals.add(name);
|
|
2686
|
+
for (const item of comp.items) {
|
|
2687
|
+
if (item.kind !== 'derived' || !item.names.includes(name))
|
|
2688
|
+
continue;
|
|
2689
|
+
t.traverseFast(item.init, (n) => {
|
|
2690
|
+
if (t.isIdentifier(n) && comp.props.some((p) => p.local === n.name))
|
|
2691
|
+
locals.add(n.name);
|
|
2692
|
+
});
|
|
2693
|
+
}
|
|
2694
|
+
}
|
|
2695
|
+
const keys = new Set(comp.props.filter((p) => locals.has(p.local)).map((p) => p.key));
|
|
2696
|
+
const alias = statements.find((s) => t.isTSTypeAliasDeclaration(s) && s.id.name === 'Props');
|
|
2697
|
+
const literals = !alias ? [] : t.isTSIntersectionType(alias.typeAnnotation) ? alias.typeAnnotation.types : [alias.typeAnnotation];
|
|
2698
|
+
const tagType = () => {
|
|
2699
|
+
script.typeImports.push({ source: 'svelte/elements', name: 'SvelteHTMLElements' });
|
|
2700
|
+
const op = t.tsTypeOperator(t.tsTypeReference(t.identifier('SvelteHTMLElements')));
|
|
2701
|
+
op.operator = 'keyof';
|
|
2702
|
+
return op;
|
|
2703
|
+
};
|
|
2704
|
+
const isComponent = (type) => t.isTSTypeReference(type) && t.isIdentifier(type.typeName, { name: 'Component' });
|
|
2705
|
+
for (const lit of literals) {
|
|
2706
|
+
if (!t.isTSTypeLiteral(lit))
|
|
2707
|
+
continue;
|
|
2708
|
+
for (const m of lit.members) {
|
|
2709
|
+
if (!t.isTSPropertySignature(m) || !t.isIdentifier(m.key) || !keys.has(m.key.name) || !m.typeAnnotation)
|
|
2710
|
+
continue;
|
|
2711
|
+
const type = m.typeAnnotation.typeAnnotation;
|
|
2712
|
+
if (isComponent(type))
|
|
2713
|
+
m.typeAnnotation.typeAnnotation = tagType();
|
|
2714
|
+
else if (t.isTSUnionType(type) && type.types.some(isComponent))
|
|
2715
|
+
type.types = type.types.map((x) => (isComponent(x) ? tagType() : x));
|
|
2716
|
+
}
|
|
2717
|
+
}
|
|
2718
|
+
}
|
|
2719
|
+
/**
|
|
2720
|
+
* The element a parent's ref reaches, bound to a `ref = $bindable()` prop: the one `ref={ref}` forwards to, or the
|
|
2721
|
+
* element ref a handle hands over (`() => inputRef.current!`, then `inputRef` is the prop's own name).
|
|
2722
|
+
*/
|
|
2723
|
+
function forwardOf(comp, script) {
|
|
2724
|
+
const handed = comp.items.find((i) => i.kind === 'forward');
|
|
2725
|
+
if (handed) {
|
|
2726
|
+
const b = comp.bindings.get(handed.ref);
|
|
2727
|
+
const item = comp.items.find((i) => i.kind === 'ref' && i.name === handed.ref);
|
|
2728
|
+
if (b?.refKind !== 'dom' || b.escapes || !item) {
|
|
2729
|
+
script.warn('imperative-handle', `The handle is ${handed.ref}.current, which is not an element ref the markup binds: not exposed.`, 'error');
|
|
2730
|
+
return null;
|
|
2731
|
+
}
|
|
2732
|
+
return { local: handed.ref, type: script.type(item.type) ?? t.tsTypeReference(t.identifier('HTMLElement')) };
|
|
2733
|
+
}
|
|
2734
|
+
const el = forwardedElement(comp);
|
|
2735
|
+
if (!comp.forwardRef || el?.node.component || comp.propsStyle !== 'destructured')
|
|
2736
|
+
return null;
|
|
2737
|
+
if (el)
|
|
2738
|
+
return { local: comp.forwardRef, type: tagElementType(el.node.tag) };
|
|
2739
|
+
// a handle is reached through the component's exports (bind:this); a ref put nowhere stays bindable and empty, as
|
|
2740
|
+
// React leaves the parent's ref empty
|
|
2741
|
+
if (comp.items.some((i) => i.kind === 'expose' || i.kind === 'handle'))
|
|
2742
|
+
return null;
|
|
2743
|
+
return { local: comp.forwardRef, type: t.tsTypeReference(t.identifier(comp.extendsHtml && !comp.extendsHtml.anyElement ? `HTML${elementTypeName(comp.extendsHtml.element)}Element` : 'HTMLElement')) };
|
|
2744
|
+
}
|
|
2745
|
+
/** The DOM's type for an element of a tag (`HTMLDivElement`), as lib.dom names it. */
|
|
2746
|
+
function domElementType(tag) {
|
|
2747
|
+
const named = {
|
|
2748
|
+
div: 'HTMLDivElement', span: 'HTMLSpanElement', button: 'HTMLButtonElement', input: 'HTMLInputElement', canvas: 'HTMLCanvasElement',
|
|
2749
|
+
img: 'HTMLImageElement', a: 'HTMLAnchorElement', ul: 'HTMLUListElement', ol: 'HTMLOListElement', li: 'HTMLLIElement', p: 'HTMLParagraphElement',
|
|
2750
|
+
textarea: 'HTMLTextAreaElement', select: 'HTMLSelectElement', label: 'HTMLLabelElement', form: 'HTMLFormElement', video: 'HTMLVideoElement',
|
|
2751
|
+
audio: 'HTMLAudioElement', iframe: 'HTMLIFrameElement', svg: 'SVGSVGElement', g: 'SVGGElement', path: 'SVGPathElement',
|
|
2752
|
+
circle: 'SVGCircleElement', rect: 'SVGRectElement',
|
|
2753
|
+
};
|
|
2754
|
+
const name = named[tag];
|
|
2755
|
+
if (name)
|
|
2756
|
+
return t.tsTypeReference(t.identifier(name));
|
|
2757
|
+
const map = SVG_TAGS.has(tag) ? 'SVGElementTagNameMap' : /^[a-z][a-z0-9]*$/.test(tag) ? 'HTMLElementTagNameMap' : null;
|
|
2758
|
+
return map ? t.tsIndexedAccessType(t.tsTypeReference(t.identifier(map)), t.tsLiteralType(t.stringLiteral(tag))) : t.tsTypeReference(t.identifier('HTMLElement'));
|
|
2759
|
+
}
|
|
2760
|
+
/**
|
|
2761
|
+
* The parameter of an attachment on an element. svelte/elements types attachments (`[key: symbol]: Attachment<T>`) on
|
|
2762
|
+
* HTML attributes only, so on an SVG element the node has no type from context: it is named there.
|
|
2763
|
+
*/
|
|
2764
|
+
function attachParam(tag) {
|
|
2765
|
+
return SVG_TAGS.has(tag) ? `node: ${printInline(domElementType(tag))}` : 'node';
|
|
2766
|
+
}
|
|
2767
|
+
/** Events whose handler svelte/elements types for any Element, not for the element it is on. */
|
|
2768
|
+
const UNTYPED_ELEMENT_EVENTS = new Set(['load', 'error']);
|
|
2769
|
+
/**
|
|
2770
|
+
* React types an `onLoad` / `onError` handler's `currentTarget` as its element (`ReactEventHandler<HTMLImageElement>`);
|
|
2771
|
+
* svelte/elements says only `Element`. An inline handler's `e.currentTarget` is cast to the element it is on: a narrow
|
|
2772
|
+
* cast that states what React's types knew.
|
|
2773
|
+
*/
|
|
2774
|
+
function currentTargetIs(tag) {
|
|
2775
|
+
return (handler) => {
|
|
2776
|
+
const fn = unwrap(handler);
|
|
2777
|
+
if (!(t.isArrowFunctionExpression(fn) || t.isFunctionExpression(fn)) || !t.isIdentifier(fn.params[0]))
|
|
2778
|
+
return handler;
|
|
2779
|
+
const name = fn.params[0].name;
|
|
2780
|
+
return transform(t.cloneNode(fn, true), (n, parent) => {
|
|
2781
|
+
if (!t.isMemberExpression(n) || n.computed || !t.isIdentifier(n.object, { name }) || !t.isIdentifier(n.property, { name: 'currentTarget' }))
|
|
2782
|
+
return null;
|
|
2783
|
+
// `e.currentTarget.x = ...` stays a member of the cast value; the cast is never an assignment target itself
|
|
2784
|
+
if ((t.isAssignmentExpression(parent) && parent.left === n) || t.isTSAsExpression(parent))
|
|
2785
|
+
return null;
|
|
2786
|
+
return t.tsAsExpression(n, domElementType(tag));
|
|
2787
|
+
});
|
|
2788
|
+
};
|
|
2789
|
+
}
|
|
2790
|
+
function elementTypeName(tag) {
|
|
2791
|
+
const map = { a: 'Anchor', img: 'Image', p: 'Paragraph', textarea: 'TextArea', ul: 'UList', ol: 'OList', li: 'LI', svg: '', h1: 'Heading', h2: 'Heading', h3: 'Heading' };
|
|
2792
|
+
if (tag in map)
|
|
2793
|
+
return map[tag] ?? '';
|
|
2794
|
+
return tag.charAt(0).toUpperCase() + tag.slice(1);
|
|
2795
|
+
}
|
|
2796
|
+
/** A custom hook as a rune function in a .svelte.ts module: reactive results are returned through getters. */
|
|
2797
|
+
function emitHook(hook, script) {
|
|
2798
|
+
const items = script.items();
|
|
2799
|
+
const cut = cutLeftoverJsx(items);
|
|
2800
|
+
const params = hook.params.filter((p) => !t.isTSParameterProperty(p)).map((p) => script.r(mapReactTypes(t.cloneNode(p, true), 'svelte', script.facts.reactNames, script.typeImports)));
|
|
2801
|
+
const body = [...items];
|
|
2802
|
+
if (hook.returns)
|
|
2803
|
+
body.push(t.returnStatement(runeReturn(hook, script, hook.returns)));
|
|
2804
|
+
if (cutLeftoverJsx(body) + cut)
|
|
2805
|
+
script.warn('jsx-in-script', `${hook.name} returns or builds elements, which have no form outside a template.`, 'error');
|
|
2806
|
+
const fn = t.functionDeclaration(t.identifier(hook.name), params, t.blockStatement(body));
|
|
2807
|
+
if (hook.typeParams)
|
|
2808
|
+
fn.typeParameters = t.cloneNode(hook.typeParams, true);
|
|
2809
|
+
return hook.exported ? t.exportNamedDeclaration(fn) : fn;
|
|
2810
|
+
}
|
|
2811
|
+
/**
|
|
2812
|
+
* A live argument (a hook parameter read through its getter, `size()`) read more than once in one getter is read once
|
|
2813
|
+
* into a local first: one read per evaluation, as React's one value per render, and TypeScript narrows the local
|
|
2814
|
+
* (`urls && urls.length ? [...urls] : []`, where `urls() && urls().length` narrows nothing). Replaces the calls in
|
|
2815
|
+
* `value` and returns the declarations to put before it.
|
|
2816
|
+
*/
|
|
2817
|
+
function readOnce(hook, script, value) {
|
|
2818
|
+
const params = new Set(hook.params.flatMap((p) => (t.isIdentifier(p) ? [p.name] : [])));
|
|
2819
|
+
const calls = new Map();
|
|
2820
|
+
t.traverse(value, (n, ancestors) => {
|
|
2821
|
+
if (!t.isCallExpression(n) || !t.isIdentifier(n.callee) || n.arguments.length || !params.has(n.callee.name))
|
|
2822
|
+
return;
|
|
2823
|
+
// a nested function may run later, or more than once: its reads stay its own
|
|
2824
|
+
if (ancestors.some(({ node }) => t.isFunction(node)))
|
|
2825
|
+
return;
|
|
2826
|
+
const set = calls.get(n.callee.name) ?? new Set();
|
|
2827
|
+
set.add(n);
|
|
2828
|
+
calls.set(n.callee.name, set);
|
|
2829
|
+
});
|
|
2830
|
+
const out = [];
|
|
2831
|
+
const locals = new Map();
|
|
2832
|
+
for (const [name, set] of calls) {
|
|
2833
|
+
if (set.size < 2)
|
|
2834
|
+
continue;
|
|
2835
|
+
const local = script.alloc.alloc(`${name}Value`);
|
|
2836
|
+
out.push(t.variableDeclaration('const', [t.variableDeclarator(t.identifier(local), t.callExpression(t.identifier(name), []))]));
|
|
2837
|
+
for (const call of set)
|
|
2838
|
+
locals.set(call, local);
|
|
2839
|
+
}
|
|
2840
|
+
if (locals.size)
|
|
2841
|
+
transform(value, (n) => (locals.has(n) ? t.identifier(locals.get(n) ?? '') : null));
|
|
2842
|
+
return out;
|
|
2843
|
+
}
|
|
2844
|
+
function runeReturn(hook, script, ret) {
|
|
2845
|
+
const getter = (key, value) => t.objectMethod('get', typeof key === 'number' ? t.numericLiteral(key) : t.identifier(key), [], t.blockStatement([...readOnce(hook, script, value), t.returnStatement(value)]));
|
|
2846
|
+
const r = unwrap(ret);
|
|
2847
|
+
const members = hook.returnShape.members;
|
|
2848
|
+
if (t.isObjectExpression(r)) {
|
|
2849
|
+
r.properties = r.properties.map((p) => {
|
|
2850
|
+
if (!t.isObjectProperty(p) || !t.isIdentifier(p.key) || !t.isExpression(p.value))
|
|
2851
|
+
return p;
|
|
2852
|
+
const member = members.find((m) => m.name === p.key.name);
|
|
2853
|
+
const value = script.r(p.value);
|
|
2854
|
+
return member?.reactive ? getter(p.key.name, value) : t.objectProperty(t.identifier(p.key.name), value, false, t.isIdentifier(value) && value.name === p.key.name);
|
|
2855
|
+
});
|
|
2856
|
+
return r;
|
|
2857
|
+
}
|
|
2858
|
+
if (t.isArrayExpression(r)) {
|
|
2859
|
+
if (!members.some((m) => m.reactive))
|
|
2860
|
+
return script.r(r);
|
|
2861
|
+
// an array cannot carry getters: return an indexed object, read as result[0], result[1]
|
|
2862
|
+
return t.objectExpression(r.elements.map((el, i) => (el && t.isExpression(el) ? (members[i]?.reactive ? getter(i, script.r(el)) : t.objectProperty(t.numericLiteral(i), script.r(el))) : t.objectProperty(t.numericLiteral(i), t.identifier('undefined')))));
|
|
2863
|
+
}
|
|
2864
|
+
// React's array or object, held in a name by the time it is returned (a pass kept the returned literal as a derived
|
|
2865
|
+
// value, `const v = $derived.by(() => [x, set] as const)`): the callers read it as lowering's return shape says
|
|
2866
|
+
// (`result[0]`, `result.name`), so each member is a getter that reads the name, never `{ value }`
|
|
2867
|
+
if ((hook.returnShape.kind === 'array' || hook.returnShape.kind === 'object') && members.length && t.isIdentifier(r)) {
|
|
2868
|
+
const held = script.r(r);
|
|
2869
|
+
return t.objectExpression(members.map((m, i) => {
|
|
2870
|
+
const key = hook.returnShape.kind === 'array' ? i : m.name;
|
|
2871
|
+
const read = typeof key === 'number' ? t.memberExpression(t.cloneNode(held, true), t.numericLiteral(key), true) : t.memberExpression(t.cloneNode(held, true), t.identifier(key));
|
|
2872
|
+
return t.objectMethod('get', typeof key === 'number' ? t.numericLiteral(key) : t.identifier(key), [], t.blockStatement([t.returnStatement(read)]));
|
|
2873
|
+
}));
|
|
2874
|
+
}
|
|
2875
|
+
const member = members[0];
|
|
2876
|
+
// a context the hook checked is there: returned as React's types see it after the check
|
|
2877
|
+
const read = guardedContext(hook, r) && t.isIdentifier(r) ? t.tsAsExpression(t.identifier(r.name), t.tsTypeReference(t.identifier('NonNullable'), t.tsTypeParameterInstantiation([t.tsTypeQuery(t.identifier(r.name))]))) : script.r(r);
|
|
2878
|
+
return member?.reactive ? t.objectExpression([getter('value', read)]) : read;
|
|
2879
|
+
}
|
|
2880
|
+
const NL = String.fromCharCode(10);
|
|
2881
|
+
/** Components and hooks whose effect order was checked (SvelteScript.effectReorder warns once per function). */
|
|
2882
|
+
const EFFECT_ORDER_CHECKED = new WeakSet();
|
|
2883
|
+
/**
|
|
2884
|
+
* Emits one lowered module as Svelte files. A file with components becomes one main component holding the file's own
|
|
2885
|
+
* code (types, constants, rune hooks, canvas loops) in `<script module>` and its stylesheet in `<style>`; small private
|
|
2886
|
+
* components become snippets; only components that must stand alone get a file beside it.
|
|
2887
|
+
*/
|
|
2888
|
+
export function emitSvelte(mod, layout, ctx) {
|
|
2889
|
+
// Radix parts claimed by ir/radix become bits-ui's (see ./radix)
|
|
2890
|
+
prepareSvelteRadix(mod, ctx);
|
|
2891
|
+
// `motionElements[Component]` over a table of motion elements keyed by their tags: a motion element of that tag
|
|
2892
|
+
resolveMotionTables(mod);
|
|
2893
|
+
// `{...selected}` of a table of Framer props on a motion element: those props written on it
|
|
2894
|
+
resolveMotionSpreads(mod);
|
|
2895
|
+
for (const [alias, name] of mod.aliases) {
|
|
2896
|
+
if (!mod.exportedNames.has(alias) || !layout.components.has(alias))
|
|
2897
|
+
continue;
|
|
2898
|
+
ctx.diagnostics.push({ code: 'component-alias', severity: 'info', message: `${alias} is another name for ${name}: a component file exports only its component, so ${alias} is ${name}'s file, imported under that name.`, file: ctx.sourceRel, target: ctx.target });
|
|
2899
|
+
}
|
|
2900
|
+
const facts = moduleFacts(mod);
|
|
2901
|
+
// contexts: reads and providers linked to their declarations, each declaration a typed Svelte context (see shared/context)
|
|
2902
|
+
linkContexts(mod, ctx);
|
|
2903
|
+
keepProvidersFiled(mod, layout, ctx.target);
|
|
2904
|
+
const contexts = contextModuleBody(mod, 'svelte');
|
|
2905
|
+
mod.moduleBody = contexts.body;
|
|
2906
|
+
const contextImports = new ImportSet();
|
|
2907
|
+
for (const name of contexts.imports.values)
|
|
2908
|
+
contextImports.named('svelte', name);
|
|
2909
|
+
const taken = new Set([...mod.moduleJsx.moduleNames, ...mod.components.map((c) => c.name), ...mod.hooks.map((h) => h.name)]);
|
|
2910
|
+
// React's element test is Svelte's (an element value is a snippet, a function); other React runtime values are reported
|
|
2911
|
+
const rv = reactValues(mod);
|
|
2912
|
+
for (const fn of [...mod.components, ...mod.hooks]) {
|
|
2913
|
+
avoidRuneNames(fn, taken);
|
|
2914
|
+
replaceElementTests(fn, rv, (arg) => t.binaryExpression('===', t.unaryExpression('typeof', arg), t.stringLiteral('function')));
|
|
2915
|
+
reportReactRuntime(fn, rv, ctx);
|
|
2916
|
+
}
|
|
2917
|
+
// the module's render helpers declared as snippets (ir/helper-snippets) test elements the same way
|
|
2918
|
+
const helperDefs = mod.snippetHelpers?.defs ?? [];
|
|
2919
|
+
if (helperDefs.length)
|
|
2920
|
+
replaceElementTests(snippetHelperHolder(mod), rv, (arg) => t.binaryExpression('===', t.unaryExpression('typeof', arg), t.stringLiteral('function')));
|
|
2921
|
+
reportMotionValues(mod, ctx);
|
|
2922
|
+
reportMotionTemplates(mod, ctx);
|
|
2923
|
+
for (const c of mod.components)
|
|
2924
|
+
reportChildrenText(c, ctx);
|
|
2925
|
+
const files = [];
|
|
2926
|
+
const moduleTypeImports = [];
|
|
2927
|
+
// elements module code builds, held as data: the code written with records, the sites a file of snippets of their own
|
|
2928
|
+
const dataPlan = moduleDataFor(mod, layout, ctx, facts);
|
|
2929
|
+
if (dataPlan)
|
|
2930
|
+
files.push(dataPlan.file);
|
|
2931
|
+
// `Pick<HtmlProps, 'className'>`: Svelte's attribute types name it `class` (see html-keys.ts)
|
|
2932
|
+
const moduleStatements = transformModuleBody(mod.moduleBody, ctx, facts, moduleTypeImports).map((s) => svelteHtmlKeys(s, ctx));
|
|
2933
|
+
// the helper the context declarations call, written once, above them
|
|
2934
|
+
if (contexts.imports.helper)
|
|
2935
|
+
moduleStatements.unshift(...svelteContextHelper());
|
|
2936
|
+
// snippets take their props as they are given: only the components that stay components
|
|
2937
|
+
svelteProps(moduleStatements, mod.components.filter((c) => !layout.inlined.has(c.name)));
|
|
2938
|
+
// every name the module body declares, its types too (Babel lists no binding for an interface or a type alias):
|
|
2939
|
+
// a component file of the module that reads one imports it from the main file, which exports it
|
|
2940
|
+
const moduleLocal = new Set(mod.moduleBody.flatMap((s) => {
|
|
2941
|
+
const decl = t.isExportNamedDeclaration(s) ? s.declaration : s;
|
|
2942
|
+
return t.isTSInterfaceDeclaration(decl) || t.isTSTypeAliasDeclaration(decl) || t.isTSEnumDeclaration(decl) ? [decl.id.name] : Object.keys(t.getOuterBindingIdentifiers(s));
|
|
2943
|
+
}));
|
|
2944
|
+
const mutableModuleNames = moduleLets(mod.moduleBody);
|
|
2945
|
+
// interfaces and type aliases of the file: imported with `import type`
|
|
2946
|
+
const moduleTypes = new Set();
|
|
2947
|
+
for (const s of mod.moduleBody) {
|
|
2948
|
+
const decl = t.isExportNamedDeclaration(s) ? s.declaration : s;
|
|
2949
|
+
if (t.isTSInterfaceDeclaration(decl) || t.isTSTypeAliasDeclaration(decl))
|
|
2950
|
+
moduleTypes.add(decl.id.name);
|
|
2951
|
+
}
|
|
2952
|
+
for (const s of mod.moduleBody) {
|
|
2953
|
+
const decl = t.isExportNamedDeclaration(s) ? s.declaration : s;
|
|
2954
|
+
if (decl && !t.isTSInterfaceDeclaration(decl) && !t.isTSTypeAliasDeclaration(decl))
|
|
2955
|
+
for (const n of Object.keys(t.getOuterBindingIdentifiers(decl)))
|
|
2956
|
+
moduleTypes.delete(n);
|
|
2957
|
+
}
|
|
2958
|
+
// the render helpers declared as snippets of the main file: another component file of the module imports them
|
|
2959
|
+
for (const def of helperDefs)
|
|
2960
|
+
moduleLocal.add(def.name);
|
|
2961
|
+
const writtenModuleNames = new Set();
|
|
2962
|
+
for (const s of mod.moduleBody) {
|
|
2963
|
+
const decl = t.isExportNamedDeclaration(s) ? s.declaration : s;
|
|
2964
|
+
if (t.isTSInterfaceDeclaration(decl) || t.isTSTypeAliasDeclaration(decl) || t.isTSEnumDeclaration(decl))
|
|
2965
|
+
moduleLocal.add(decl.id.name);
|
|
2966
|
+
}
|
|
2967
|
+
const addTypeImports = (set, list) => {
|
|
2968
|
+
for (const ti of list)
|
|
2969
|
+
set.type(ti.source, ti.name);
|
|
2970
|
+
};
|
|
2971
|
+
const svelteImport = (set, apis) => {
|
|
2972
|
+
for (const [api, local] of apis)
|
|
2973
|
+
set.named('svelte', api, local);
|
|
2974
|
+
};
|
|
2975
|
+
const hookStatements = (exportNames) => {
|
|
2976
|
+
const statements = [];
|
|
2977
|
+
const apis = [];
|
|
2978
|
+
const typeImports = [];
|
|
2979
|
+
const imports = [contextImports];
|
|
2980
|
+
for (const hook of mod.hooks) {
|
|
2981
|
+
const alloc = new NameAllocator([...hook.bindings.keys(), ...moduleLocal, ...mod.hooks.map((h) => h.name)]);
|
|
2982
|
+
const script = new SvelteScript(hook, alloc, ctx, facts);
|
|
2983
|
+
const stmt = rewriteImportTypes(emitHook(hook, script), ctx);
|
|
2984
|
+
statements.push(exportNames.has(hook.name) && !t.isExportNamedDeclaration(stmt) ? t.exportNamedDeclaration(stmt) : stmt);
|
|
2985
|
+
for (const pair of script.svelte)
|
|
2986
|
+
apis.push(pair);
|
|
2987
|
+
typeImports.push(...script.typeImports);
|
|
2988
|
+
imports.push(script.imports);
|
|
2989
|
+
}
|
|
2990
|
+
return { statements, apis, typeImports, imports };
|
|
2991
|
+
};
|
|
2992
|
+
if (layout.kind === 'module') {
|
|
2993
|
+
const hooks = hookStatements(new Set());
|
|
2994
|
+
const outPath = layout.modulePath;
|
|
2995
|
+
const set = new ImportSet();
|
|
2996
|
+
for (const decl of mod.imports)
|
|
2997
|
+
addOriginalImport(decl, set, outPath, ctx);
|
|
2998
|
+
for (const s of hooks.imports)
|
|
2999
|
+
for (const d of s.declarations())
|
|
3000
|
+
addDeclarationTo(set, d);
|
|
3001
|
+
svelteImport(set, hooks.apis);
|
|
3002
|
+
addTypeImports(set, [...moduleTypeImports, ...hooks.typeImports]);
|
|
3003
|
+
const reexports = mod.reexports.flatMap((r) => rewriteReexport(r, outPath, ctx));
|
|
3004
|
+
const body = [...moduleStatements, ...hooks.statements, ...reexports];
|
|
3005
|
+
const used = namesIn(body);
|
|
3006
|
+
for (const ti of [...moduleTypeImports, ...hooks.typeImports])
|
|
3007
|
+
used.add(ti.name);
|
|
3008
|
+
files.push({ path: outPath, contents: printProgram([...set.declarations(used), ...body]), kind: 'module' });
|
|
3009
|
+
return files;
|
|
3010
|
+
}
|
|
3011
|
+
const inlineComps = new Map(mod.components.filter((c) => layout.inlined.has(c.name)).map((c) => [c.name, c]));
|
|
3012
|
+
// when each motion element's exit plays: where it sits, in its component and in the components that render that one
|
|
3013
|
+
const exits = exitPlacements(mod);
|
|
3014
|
+
// when the initial animations AnimatePresence initial={false} holds back play, worked out the same way
|
|
3015
|
+
const enters = enterPlacements(mod);
|
|
3016
|
+
// a component another file declares, which may animate in: a local import whose module holds such an element
|
|
3017
|
+
const animatesIn = (tag) => {
|
|
3018
|
+
const decl = mod.imports.find((d) => d.specifiers.some((s) => s.local.name === tag));
|
|
3019
|
+
const file = decl ? resolveLocal(ctx.sourceFile, decl.source.value, ctx.project) : null;
|
|
3020
|
+
if (!file)
|
|
3021
|
+
return false;
|
|
3022
|
+
const other = ctx.moduleOf?.(file) ?? null;
|
|
3023
|
+
return !other || other.reexports.length > 0 || moduleAnimatesIn(other);
|
|
3024
|
+
};
|
|
3025
|
+
const unfollowed = (presence) => unfollowedEnters(presence, mod, animatesIn);
|
|
3026
|
+
/** names the other component files read from the main file, which it therefore exports */
|
|
3027
|
+
const fromMain = new Set(layout.defaultValue ? [layout.defaultValue] : []);
|
|
3028
|
+
const importsFor = (outPath, used, self, isMain) => {
|
|
3029
|
+
const set = new ImportSet();
|
|
3030
|
+
for (const decl of mod.imports)
|
|
3031
|
+
addOriginalImport(decl, set, outPath, ctx);
|
|
3032
|
+
for (const [name, file] of layout.components)
|
|
3033
|
+
if (name !== self && used.has(name))
|
|
3034
|
+
set.defaultImport(importPath(outPath, file), name);
|
|
3035
|
+
if (isMain)
|
|
3036
|
+
return set;
|
|
3037
|
+
const main = importPath(outPath, layout.modulePath);
|
|
3038
|
+
for (const name of moduleLocal) {
|
|
3039
|
+
if (!used.has(name))
|
|
3040
|
+
continue;
|
|
3041
|
+
fromMain.add(name);
|
|
3042
|
+
if (moduleTypes.has(name))
|
|
3043
|
+
set.type(main, name);
|
|
3044
|
+
else
|
|
3045
|
+
set.named(main, name);
|
|
3046
|
+
}
|
|
3047
|
+
for (const name of writtenModuleNames) {
|
|
3048
|
+
const setterName = `set${name.charAt(0).toUpperCase()}${name.slice(1)}`;
|
|
3049
|
+
if (!used.has(setterName))
|
|
3050
|
+
continue;
|
|
3051
|
+
fromMain.add(setterName);
|
|
3052
|
+
set.named(main, setterName);
|
|
3053
|
+
}
|
|
3054
|
+
for (const h of mod.hooks) {
|
|
3055
|
+
if (!used.has(h.name))
|
|
3056
|
+
continue;
|
|
3057
|
+
fromMain.add(h.name);
|
|
3058
|
+
set.named(main, h.name);
|
|
3059
|
+
}
|
|
3060
|
+
return set;
|
|
3061
|
+
};
|
|
3062
|
+
/** The main file's module script: the file's own code, exporting what the other component files read. */
|
|
3063
|
+
const mainModuleScript = (outPath) => {
|
|
3064
|
+
const listed = new Set();
|
|
3065
|
+
for (const s of moduleStatements) {
|
|
3066
|
+
if (t.isExportNamedDeclaration(s) && !s.declaration && !s.source)
|
|
3067
|
+
for (const sp of s.specifiers)
|
|
3068
|
+
if (t.isExportSpecifier(sp))
|
|
3069
|
+
listed.add(sp.local.name);
|
|
3070
|
+
}
|
|
3071
|
+
const statements = [];
|
|
3072
|
+
for (const s of moduleStatements) {
|
|
3073
|
+
// a component file's default export is the component: a plain default value is exported by name instead
|
|
3074
|
+
if (t.isExportDefaultDeclaration(s)) {
|
|
3075
|
+
if (t.isIdentifier(s.declaration))
|
|
3076
|
+
continue;
|
|
3077
|
+
if (t.isExpression(s.declaration) && layout.defaultValue) {
|
|
3078
|
+
statements.push(t.exportNamedDeclaration(t.variableDeclaration('const', [t.variableDeclarator(t.identifier(layout.defaultValue), s.declaration)])));
|
|
3079
|
+
continue;
|
|
3080
|
+
}
|
|
3081
|
+
}
|
|
3082
|
+
// an interface or type alias binds no value, so Babel lists no names for it: its own name, for the type imports
|
|
3083
|
+
const names = t.isTSInterfaceDeclaration(s) || t.isTSTypeAliasDeclaration(s) || t.isTSEnumDeclaration(s) ? [s.id.name] : Object.keys(t.getOuterBindingIdentifiers(s));
|
|
3084
|
+
const exported = t.isExportNamedDeclaration(s) || names.some((n) => listed.has(n));
|
|
3085
|
+
statements.push(!exported && names.some((n) => fromMain.has(n)) ? exportIfLocal(s) : s);
|
|
3086
|
+
}
|
|
3087
|
+
const hooks = hookStatements(fromMain);
|
|
3088
|
+
statements.push(...hooks.statements, ...moduleSetters(writtenModuleNames), ...mod.reexports.flatMap((r) => rewriteReexport(r, outPath, ctx)));
|
|
3089
|
+
return { statements, apis: hooks.apis, typeImports: hooks.typeImports, imports: hooks.imports };
|
|
3090
|
+
};
|
|
3091
|
+
/**
|
|
3092
|
+
* The module's markup values (ModuleIR.markupValues) as snippets of a file of their own, `<Main>Markup.svelte`, with
|
|
3093
|
+
* only a module script that exports them (Svelte 5.5.0 or later): the main file's module script imports them, so its data holds
|
|
3094
|
+
* them from the start. In the main file itself a snippet would come after the module code that reads it.
|
|
3095
|
+
*/
|
|
3096
|
+
const markupValuesFile = (comp) => {
|
|
3097
|
+
const path = layout.modulePath.replace(/\.svelte$/, 'Markup.svelte');
|
|
3098
|
+
const alloc = new NameAllocator([...moduleLocal, ...mod.components.map((c) => c.name)]);
|
|
3099
|
+
const script = new SvelteScript(comp, alloc, ctx, facts);
|
|
3100
|
+
const template = new SvelteTemplate(comp, script, facts, null, { comps: new Map(), snippets: new Set(), used: new Set() });
|
|
3101
|
+
const values = mod.markupValues ?? [];
|
|
3102
|
+
const markup = values.map((v) => template.markupValue(v.name, v.template)).join(`${NL}${NL}`);
|
|
3103
|
+
const names = markupNames(markup, 'svelte');
|
|
3104
|
+
// a snippet that reads the file's own names, or needs a helper of its own, stays reported
|
|
3105
|
+
const local = [...names].filter((n) => moduleLocal.has(n));
|
|
3106
|
+
if (local.length || script.helpers.size) {
|
|
3107
|
+
ctx.diagnostics.push({ code: 'module-jsx', severity: 'error', message: `The markup the file's data holds (${values.map((v) => v.name).join(', ')}) reads ${local.length ? `the file's own ${local.join(', ')}` : 'a helper of the component'}: as snippets of their own file they cannot, so it is not converted.`, file: ctx.sourceRel, target: 'svelte' });
|
|
3108
|
+
return null;
|
|
3109
|
+
}
|
|
3110
|
+
const imports = new ImportSet();
|
|
3111
|
+
for (const decl of mod.imports)
|
|
3112
|
+
addOriginalImport(decl, imports, path, ctx);
|
|
3113
|
+
for (const [name, file] of layout.components)
|
|
3114
|
+
if (names.has(name))
|
|
3115
|
+
imports.defaultImport(importPath(path, file), name);
|
|
3116
|
+
for (const d of script.imports.declarations())
|
|
3117
|
+
addDeclarationTo(imports, d);
|
|
3118
|
+
svelteImport(imports, script.svelte);
|
|
3119
|
+
addTypeImports(imports, script.typeImports);
|
|
3120
|
+
const head = [...imports.declarations(names), t.exportNamedDeclaration(null, values.map((v) => t.exportSpecifier(t.identifier(v.name), t.identifier(v.name))))];
|
|
3121
|
+
ctx.diagnostics.push({ code: 'svelte-version', severity: 'info', message: `${path} exports snippets from its module script (the markup the file's data holds), which needs Svelte 5.5.0 or later.`, file: ctx.sourceRel, target: 'svelte' });
|
|
3122
|
+
return { path, contents: `<script module lang="ts">${NL}${printProgram(head)}${NL}</script>${NL}${NL}${markup}${NL}`, kind: 'component' };
|
|
3123
|
+
};
|
|
3124
|
+
const emitComponent = (source, outPath, isMain) => {
|
|
3125
|
+
const comp = waitsWhileRendering(source) ? asyncShell(source) : source;
|
|
3126
|
+
const alloc = new NameAllocator([...comp.bindings.keys(), ...moduleLocal, ...mod.components.map((c) => c.name), ...mod.hooks.map((h) => h.name), 'motionAction', 'motionEnter', 'motionExit', 'toPx', 'toStyleString', 'toStyleObject', 'UNITLESS']);
|
|
3127
|
+
const script = new SvelteScript(comp, alloc, ctx, facts);
|
|
3128
|
+
const forwarded = restForwardedChildren(comp);
|
|
3129
|
+
const styleProp = styleObjectProp(comp);
|
|
3130
|
+
const styleAttr = styleProp ? alloc.alloc('styleAttribute') : null;
|
|
3131
|
+
script.forward = forwardOf(comp, script);
|
|
3132
|
+
script.childOf = (tag) => childComponent(mod, tag, ctx);
|
|
3133
|
+
script.childOfAny = (parent, tag) => {
|
|
3134
|
+
const own = parent.file === ctx.sourceFile ? mod : (ctx.moduleOf?.(parent.file) ?? null);
|
|
3135
|
+
return own ? childComponent(own, tag, { ...ctx, sourceFile: parent.file }) : null;
|
|
3136
|
+
};
|
|
3137
|
+
for (const w of propWrites(comp)) {
|
|
3138
|
+
script.warn('prop-write', `${comp.name} assigns to its prop "${w.name}", which React recomputes on every render; Svelte runs that code once, so a later value from the parent is used as passed, without it. Compute a new name from the prop instead (\`const shown = $derived(typeof ${w.name} === 'string' ? … : ${w.name})\`).`, 'warning', w.line);
|
|
3139
|
+
}
|
|
3140
|
+
const props = propsDeclaration(comp, script, !!forwarded, styleAttr);
|
|
3141
|
+
if (styleProp && styleAttr) {
|
|
3142
|
+
script.helpers.add('toStyleObject');
|
|
3143
|
+
props.push(t.variableDeclaration('const', [t.variableDeclarator(t.identifier(styleProp.local), t.callExpression(t.identifier('$derived'), [t.callExpression(t.identifier('toStyleObject'), [t.identifier(styleAttr)])]))]));
|
|
3144
|
+
}
|
|
3145
|
+
script.markup = new MarkupData(mod, comp, ctx, (n) => !alloc.has(n), (n) => alloc.reserve(n));
|
|
3146
|
+
const items = script.items();
|
|
3147
|
+
if (cutLeftoverJsx(items))
|
|
3148
|
+
script.warn('jsx-in-script', `${comp.name} builds elements in script code, which have no form outside a template.`, 'error');
|
|
3149
|
+
const inline = { comps: inlineComps, snippets: new Set(), used: new Set(), exits, enters, unfollowed };
|
|
3150
|
+
const moduleWrites = isMain ? null : { names: mutableModuleNames, written: writtenModuleNames };
|
|
3151
|
+
const template = new SvelteTemplate(comp, script, facts, moduleWrites, inline);
|
|
3152
|
+
if (forwarded)
|
|
3153
|
+
template.forwarded = forwarded;
|
|
3154
|
+
template.styleObject = !!styleProp;
|
|
3155
|
+
template.node(comp.template, '', { loopNames: new Set() });
|
|
3156
|
+
let markup = template.m.done();
|
|
3157
|
+
// render helpers, as snippets beside the markup (a snippet may render another, or itself)
|
|
3158
|
+
const fragmentsPrinted = new Set();
|
|
3159
|
+
for (let name = [...template.fragmentsUsed].find((n) => !fragmentsPrinted.has(n)); name; name = [...template.fragmentsUsed].find((n) => !fragmentsPrinted.has(n))) {
|
|
3160
|
+
fragmentsPrinted.add(name);
|
|
3161
|
+
const def = comp.fragments.find((f) => f.name === name);
|
|
3162
|
+
if (!def)
|
|
3163
|
+
continue;
|
|
3164
|
+
template.fragment(def);
|
|
3165
|
+
markup += `${NL}${NL}${template.m.done()}`;
|
|
3166
|
+
}
|
|
3167
|
+
// elements built by script code: each site a snippet that draws its record (markup-data)
|
|
3168
|
+
for (const def of script.markup?.sites ?? []) {
|
|
3169
|
+
template.fragment(def);
|
|
3170
|
+
markup += `${NL}${NL}${template.m.done()}`;
|
|
3171
|
+
}
|
|
3172
|
+
narrowTagProps(props, comp, template.tagNames, script);
|
|
3173
|
+
for (const text of template.hoisted)
|
|
3174
|
+
markup += `${NL}${NL}${text}`;
|
|
3175
|
+
// markup a prop's data holds (ComponentIR.markupValues): snippets of the markup, values in the component's scope
|
|
3176
|
+
for (const v of comp.markupValues ?? [])
|
|
3177
|
+
markup += `${NL}${NL}${template.markupValue(v.name, v.template)}`;
|
|
3178
|
+
const snippetScripts = [];
|
|
3179
|
+
// the module's render helpers (ModuleIR.snippetHelpers): top-level snippets of the main file, which read nothing of
|
|
3180
|
+
// its component, printed as such (no names of its own)
|
|
3181
|
+
if (isMain && helperDefs.length) {
|
|
3182
|
+
const holder = { ...comp, bindings: new Map(), refs: new WeakMap(), items: [], props: [], propsObject: null, fragments: [], markupValues: [] };
|
|
3183
|
+
const helperScript = new SvelteScript(holder, alloc, ctx, facts);
|
|
3184
|
+
helperScript.portalName = script.portalName;
|
|
3185
|
+
const helperTemplate = new SvelteTemplate(holder, helperScript, facts, null, inline);
|
|
3186
|
+
for (const def of helperDefs) {
|
|
3187
|
+
helperTemplate.fragment(def);
|
|
3188
|
+
markup += `${NL}${NL}${helperTemplate.m.done()}`;
|
|
3189
|
+
}
|
|
3190
|
+
script.portalName = helperScript.portalName;
|
|
3191
|
+
if (helperTemplate.typedMarkup)
|
|
3192
|
+
template.typedMarkup = true;
|
|
3193
|
+
if (helperTemplate.drewData)
|
|
3194
|
+
template.drewData = true;
|
|
3195
|
+
snippetScripts.push(helperScript);
|
|
3196
|
+
}
|
|
3197
|
+
// each snippet is printed once, in the file of every component that renders it (a snippet may render others)
|
|
3198
|
+
const printed = new Set();
|
|
3199
|
+
for (let name = [...inline.snippets].find((n) => !printed.has(n)); name; name = [...inline.snippets].find((n) => !printed.has(n))) {
|
|
3200
|
+
printed.add(name);
|
|
3201
|
+
const snippetComp = inlineComps.get(name);
|
|
3202
|
+
if (!snippetComp)
|
|
3203
|
+
continue;
|
|
3204
|
+
const snippetScript = new SvelteScript(snippetComp, alloc, ctx, facts);
|
|
3205
|
+
// one portal attachment per file, whichever markup asks for it first
|
|
3206
|
+
snippetScript.portalName = script.portalName;
|
|
3207
|
+
const snippetTemplate = new SvelteTemplate(snippetComp, snippetScript, facts, moduleWrites, inline);
|
|
3208
|
+
snippetTemplate.snippet(snippetComp);
|
|
3209
|
+
script.portalName = snippetScript.portalName;
|
|
3210
|
+
if (snippetTemplate.typedMarkup)
|
|
3211
|
+
template.typedMarkup = true;
|
|
3212
|
+
if (snippetTemplate.drewData)
|
|
3213
|
+
template.drewData = true;
|
|
3214
|
+
markup += `${NL}${NL}${snippetTemplate.m.done()}`;
|
|
3215
|
+
snippetScripts.push(snippetScript);
|
|
3216
|
+
}
|
|
3217
|
+
for (const s of snippetScripts) {
|
|
3218
|
+
for (const h of s.helpers)
|
|
3219
|
+
script.helpers.add(h);
|
|
3220
|
+
for (const f of s.motion)
|
|
3221
|
+
script.motion.add(f);
|
|
3222
|
+
for (const d of s.imports.declarations())
|
|
3223
|
+
addDeclarationTo(script.imports, d);
|
|
3224
|
+
script.typeImports.push(...s.typeImports);
|
|
3225
|
+
}
|
|
3226
|
+
// elements module code holds as data, drawn by the conversion's MarkupView
|
|
3227
|
+
if (template.drewData) {
|
|
3228
|
+
script.imports.defaultImport(importPath(outPath, ctx.helperPath?.(MARKUP_VIEW_FILE) ?? MARKUP_VIEW_FILE), MARKUP_VIEW);
|
|
3229
|
+
useMarkupHelper(ctx.diagnostics);
|
|
3230
|
+
}
|
|
3231
|
+
const helpers = script.helperStatements(outPath);
|
|
3232
|
+
// types the checker wrote inline (`import('@/x/types').Point`) point at the output files
|
|
3233
|
+
let body = [...props, ...helpers, ...script.passStatements(), ...items, ...script.provides(comp)].map((st) => rewriteImportTypes(st, ctx));
|
|
3234
|
+
if (!isMain)
|
|
3235
|
+
for (const name of routeModuleWrites(body, mutableModuleNames, new Set(comp.bindings.keys())))
|
|
3236
|
+
writtenModuleNames.add(name);
|
|
3237
|
+
const moduleScript = [];
|
|
3238
|
+
const moduleTypes = [];
|
|
3239
|
+
const moduleSets = [];
|
|
3240
|
+
let moduleApis = [];
|
|
3241
|
+
if (isMain) {
|
|
3242
|
+
const main = mainModuleScript(outPath);
|
|
3243
|
+
moduleScript.push(...main.statements);
|
|
3244
|
+
moduleApis = main.apis;
|
|
3245
|
+
moduleTypes.push(...moduleTypeImports, ...main.typeImports);
|
|
3246
|
+
moduleSets.push(...main.imports);
|
|
3247
|
+
// the sites of the elements module code holds as data, and the type it names, for the module code
|
|
3248
|
+
if (dataPlan) {
|
|
3249
|
+
const set = new ImportSet();
|
|
3250
|
+
for (const def of dataPlan.plan.sites)
|
|
3251
|
+
set.named(importPath(outPath, dataPlan.file.path), def.name);
|
|
3252
|
+
if (dataPlan.plan.type())
|
|
3253
|
+
set.type(importPath(outPath, ctx.helperPath?.(MARKUP_MODULE_FILE) ?? MARKUP_MODULE_FILE), MARKUP_TYPE);
|
|
3254
|
+
moduleSets.push(set);
|
|
3255
|
+
}
|
|
3256
|
+
// the render helpers declared as snippets, exported as the file exported them or as its other files read them
|
|
3257
|
+
const exportedHelpers = helperDefs.filter((d) => mod.snippetHelpers?.exported.has(d.name) || fromMain.has(d.name)).map((d) => d.name);
|
|
3258
|
+
if (exportedHelpers.length) {
|
|
3259
|
+
moduleScript.push(t.exportNamedDeclaration(null, exportedHelpers.map((n) => t.exportSpecifier(t.identifier(n), t.identifier(n)))));
|
|
3260
|
+
ctx.diagnostics.push({ code: 'svelte-version', severity: 'info', message: `${outPath.split('/').pop() ?? outPath} exports snippets from its module script (${exportedHelpers.join(', ')}, the file's render helpers), which needs Svelte 5.5.0 or later.`, file: ctx.sourceRel, target: 'svelte' });
|
|
3261
|
+
}
|
|
3262
|
+
// the module's markup values, exported snippets of the file beside it (see markupValuesFile)
|
|
3263
|
+
if (markupFile) {
|
|
3264
|
+
const set = new ImportSet();
|
|
3265
|
+
for (const v of mod.markupValues ?? [])
|
|
3266
|
+
set.named(importPath(outPath, markupFile.path), v.name);
|
|
3267
|
+
moduleSets.push(set);
|
|
3268
|
+
}
|
|
3269
|
+
}
|
|
3270
|
+
// canvas and animation loops, framework-free, at the top of the file that runs them
|
|
3271
|
+
for (const core of script.cores)
|
|
3272
|
+
moduleScript.push(...core.module.statements.map((st) => rewriteImportTypes(mapReactTypes(st, 'svelte', facts.reactNames, moduleTypes), ctx)));
|
|
3273
|
+
const generics = comp.typeParams ? ` generics="${genericsAttr(comp.typeParams)}"` : '';
|
|
3274
|
+
// nothing the file declares stays unless the script or the markup reads it
|
|
3275
|
+
const templateNames = wordsIn(generics, markupNames(markup, 'svelte'));
|
|
3276
|
+
const [prunedModule = [], prunedBody = []] = pruneUnused([moduleScript, body], templateNames, { calls: PURE_RUNES, props: { calls: new Set(['$props']), whenUnread: 'empty', declares: new Set(['$bindable']) } });
|
|
3277
|
+
moduleScript.splice(0, moduleScript.length, ...prunedModule);
|
|
3278
|
+
body = prunedBody;
|
|
3279
|
+
// a name the component declares itself shadows the module's: never import it into the component
|
|
3280
|
+
const used = namesIn(body);
|
|
3281
|
+
for (const name of comp.bindings.keys())
|
|
3282
|
+
if (!comp.moduleNames.has(name))
|
|
3283
|
+
used.delete(name);
|
|
3284
|
+
namesIn(moduleScript, used);
|
|
3285
|
+
// names only the markup reads (components, actions, snippets) appear in no script statement
|
|
3286
|
+
for (const name of templateNames)
|
|
3287
|
+
used.add(name);
|
|
3288
|
+
const imports = importsFor(outPath, used, comp.name, isMain);
|
|
3289
|
+
for (const d of script.imports.declarations())
|
|
3290
|
+
addDeclarationTo(imports, d);
|
|
3291
|
+
svelteImport(imports, script.svelte);
|
|
3292
|
+
addTypeImports(imports, script.typeImports);
|
|
3293
|
+
const parts = [];
|
|
3294
|
+
if (moduleScript.length) {
|
|
3295
|
+
// the module script sees only its own imports; the instance script sees those too, and imports the rest
|
|
3296
|
+
const moduleUsed = namesIn(moduleScript);
|
|
3297
|
+
const moduleSet = importsFor(outPath, moduleUsed, comp.name, isMain);
|
|
3298
|
+
for (const s of moduleSets)
|
|
3299
|
+
for (const d of s.declarations())
|
|
3300
|
+
addDeclarationTo(moduleSet, d);
|
|
3301
|
+
svelteImport(moduleSet, moduleApis);
|
|
3302
|
+
addTypeImports(moduleSet, moduleTypes);
|
|
3303
|
+
const moduleDeclarations = moduleSet.declarations(moduleUsed);
|
|
3304
|
+
const provided = new Set(moduleDeclarations.flatMap((d) => d.specifiers.map((s) => s.local.name)));
|
|
3305
|
+
const sides = new Set(moduleDeclarations.filter((d) => !d.specifiers.length).map((d) => d.source.value));
|
|
3306
|
+
const instanceDeclarations = imports.declarations(new Set([...used].filter((n) => !provided.has(n)))).filter((d) => d.specifiers.length || !sides.has(d.source.value));
|
|
3307
|
+
parts.push(`<script module lang="ts">${NL}${printProgram([...moduleDeclarations, ...moduleScript])}${NL}</script>${NL}`);
|
|
3308
|
+
if (instanceDeclarations.length || body.length)
|
|
3309
|
+
parts.push(`<script lang="ts"${generics}>${NL}${printProgram([...instanceDeclarations, ...body])}${NL}</script>${NL}`);
|
|
3310
|
+
}
|
|
3311
|
+
else {
|
|
3312
|
+
const declarations = imports.declarations(used);
|
|
3313
|
+
if (declarations.length || body.length)
|
|
3314
|
+
parts.push(`<script lang="ts"${generics}>${NL}${printProgram([...declarations, ...body])}${NL}</script>${NL}`);
|
|
3315
|
+
// TypeScript in the markup parses only in a file whose script is TypeScript
|
|
3316
|
+
else if (template.typedMarkup || generics)
|
|
3317
|
+
parts.push(`<script lang="ts"${generics}></script>${NL}`);
|
|
3318
|
+
}
|
|
3319
|
+
parts.push(markup + NL);
|
|
3320
|
+
if (isMain) {
|
|
3321
|
+
const style = componentStyle('svelte', layout.styles);
|
|
3322
|
+
if (style)
|
|
3323
|
+
parts.push(style);
|
|
3324
|
+
}
|
|
3325
|
+
return { path: outPath, contents: parts.join(NL), kind: 'component' };
|
|
3326
|
+
};
|
|
3327
|
+
// the other component files first: the main file then knows which of its names they read
|
|
3328
|
+
const main = mod.components.find((c) => c.name === layout.mainComponent);
|
|
3329
|
+
const markupFile = main && mod.markupValues?.length ? markupValuesFile(main) : null;
|
|
3330
|
+
if (markupFile)
|
|
3331
|
+
files.push(markupFile);
|
|
3332
|
+
for (const comp of mod.components) {
|
|
3333
|
+
const outPath = layout.components.get(comp.name);
|
|
3334
|
+
if (outPath && comp !== main)
|
|
3335
|
+
files.push(emitComponent(comp, outPath, false));
|
|
3336
|
+
}
|
|
3337
|
+
if (main)
|
|
3338
|
+
files.unshift(emitComponent(main, layout.modulePath, true));
|
|
3339
|
+
else if (helperDefs.length)
|
|
3340
|
+
ctx.diagnostics.push({ code: 'module-jsx', severity: 'error', message: `The file's render helpers (${helperDefs.map((d) => d.name).join(', ')}) are snippets of its main component, and it has no main component file to declare them in: not converted.`, file: ctx.sourceRel, target: 'svelte' });
|
|
3341
|
+
else if (mod.markupValues?.length)
|
|
3342
|
+
ctx.diagnostics.push({ code: 'module-jsx', severity: 'error', message: `The file's data holds markup (${mod.markupValues.map((v) => v.name).join(', ')}) but it has no component file to declare it in as snippets: not converted.`, file: ctx.sourceRel, target: 'svelte' });
|
|
3343
|
+
// a module-level name like a rune is the file's to keep (others may import it): said where the rune is used
|
|
3344
|
+
for (const name of moduleLocal) {
|
|
3345
|
+
if (!RUNE_NAMES.has(name) || !files.some((f) => f.contents.includes(`$${name}`)))
|
|
3346
|
+
continue;
|
|
3347
|
+
ctx.diagnostics.push({ code: 'svelte-rune-name', severity: 'error', message: `The file declares "${name}" at module level, so Svelte reads the $${name} rune in its components as a store subscription to it: rename it to convert this file.`, file: ctx.sourceRel, target: 'svelte' });
|
|
3348
|
+
}
|
|
3349
|
+
// a binding mayUseRune kept whose rune the component calls after all
|
|
3350
|
+
for (const comp of mod.components) {
|
|
3351
|
+
const path = comp === main ? layout.modulePath : layout.components.get(comp.name);
|
|
3352
|
+
const out = files.find((f) => f.path === path);
|
|
3353
|
+
for (const name of comp.bindings.keys()) {
|
|
3354
|
+
if (!RUNE_NAMES.has(name) || !out?.contents.includes(`$${name}`))
|
|
3355
|
+
continue;
|
|
3356
|
+
ctx.diagnostics.push({ code: 'svelte-rune-name', severity: 'error', message: `${comp.name} declares "${name}", so Svelte reads its $${name} rune as a store subscription to it: rename it to convert this component.`, file: ctx.sourceRel, target: 'svelte' });
|
|
3357
|
+
}
|
|
3358
|
+
}
|
|
3359
|
+
return files;
|
|
3360
|
+
}
|
|
3361
|
+
/**
|
|
3362
|
+
* The elements the module's code builds, held as data (markup-data/module-data): the plan, and the file of its sites,
|
|
3363
|
+
* `<Main>Elements.svelte`, whose module script exports them as snippets. The plan is committed only once that file can
|
|
3364
|
+
* be written: its snippets read only their record and the file's imports (a name of the module's own, a helper, motion
|
|
3365
|
+
* or a portal would need the main file, which imports this one), so otherwise nothing changes and the code keeps its
|
|
3366
|
+
* module-jsx error.
|
|
3367
|
+
*/
|
|
3368
|
+
function moduleDataFor(mod, layout, ctx, facts) {
|
|
3369
|
+
if (layout.kind === 'module')
|
|
3370
|
+
return null;
|
|
3371
|
+
const main = mod.components.find((c) => c.name === layout.mainComponent);
|
|
3372
|
+
if (!main || layout.inlined.has(main.name))
|
|
3373
|
+
return null;
|
|
3374
|
+
const path = layout.modulePath.replace(/\.svelte$/, 'Elements.svelte');
|
|
3375
|
+
if (path === layout.modulePath || [...layout.components.values()].includes(path))
|
|
3376
|
+
return null;
|
|
3377
|
+
const taken = namesIn([...mod.moduleBody, ...mod.imports]);
|
|
3378
|
+
for (const c of mod.components) {
|
|
3379
|
+
taken.add(c.name);
|
|
3380
|
+
for (const n of c.bindings.keys())
|
|
3381
|
+
taken.add(n);
|
|
3382
|
+
}
|
|
3383
|
+
for (const h of mod.hooks)
|
|
3384
|
+
taken.add(h.name);
|
|
3385
|
+
for (const n of mod.moduleJsx.moduleNames)
|
|
3386
|
+
taken.add(n);
|
|
3387
|
+
const plan = planModuleData(mod, ctx, facts.reactNames, taken);
|
|
3388
|
+
if (!plan)
|
|
3389
|
+
return null;
|
|
3390
|
+
const holder = { ...main, bindings: new Map(), refs: new WeakMap(), items: [], props: [], propsObject: null, fragments: [], markupValues: [], keptMarkup: [] };
|
|
3391
|
+
const script = new SvelteScript(holder, new NameAllocator(taken), ctx, facts);
|
|
3392
|
+
const template = new SvelteTemplate(holder, script, facts, null);
|
|
3393
|
+
const parts = [];
|
|
3394
|
+
for (const def of plan.sites) {
|
|
3395
|
+
template.fragment(def);
|
|
3396
|
+
parts.push(template.m.done());
|
|
3397
|
+
}
|
|
3398
|
+
const markup = parts.join(`${NL}${NL}`);
|
|
3399
|
+
// the names the snippets read: their markup's, and their parameters' types
|
|
3400
|
+
const used = markupNames(markup, 'svelte');
|
|
3401
|
+
for (const header of markup.match(/\{#snippet [^\n]*/g) ?? [])
|
|
3402
|
+
for (const word of header.match(/[A-Za-z_$][\w$]*/g) ?? [])
|
|
3403
|
+
used.add(word);
|
|
3404
|
+
const local = new Set(mod.components.map((c) => c.name));
|
|
3405
|
+
for (const s of mod.moduleBody) {
|
|
3406
|
+
const decl = t.isExportNamedDeclaration(s) ? s.declaration : s;
|
|
3407
|
+
if (t.isTSInterfaceDeclaration(decl) || t.isTSTypeAliasDeclaration(decl) || t.isTSEnumDeclaration(decl))
|
|
3408
|
+
local.add(decl.id.name);
|
|
3409
|
+
else
|
|
3410
|
+
for (const n of Object.keys(t.getOuterBindingIdentifiers(s)))
|
|
3411
|
+
local.add(n);
|
|
3412
|
+
}
|
|
3413
|
+
if ([...used].some((n) => local.has(n)) || script.helpers.size || script.motion.size || script.svelte.size || script.portalName || template.drewData)
|
|
3414
|
+
return null;
|
|
3415
|
+
const imports = new ImportSet();
|
|
3416
|
+
for (const decl of mod.imports)
|
|
3417
|
+
addOriginalImport(decl, imports, path, ctx);
|
|
3418
|
+
for (const d of script.imports.declarations())
|
|
3419
|
+
addDeclarationTo(imports, d);
|
|
3420
|
+
for (const ti of script.typeImports)
|
|
3421
|
+
imports.type(ti.source, ti.name);
|
|
3422
|
+
const helper = importPath(path, ctx.helperPath?.(MARKUP_MODULE_FILE) ?? MARKUP_MODULE_FILE);
|
|
3423
|
+
imports.type(helper, MARKUP_ELEMENT_TYPE);
|
|
3424
|
+
if (plan.view) {
|
|
3425
|
+
imports.type(helper, MARKUP_TYPE);
|
|
3426
|
+
imports.defaultImport(importPath(path, ctx.helperPath?.(MARKUP_VIEW_FILE) ?? MARKUP_VIEW_FILE), MARKUP_VIEW);
|
|
3427
|
+
}
|
|
3428
|
+
plan.commit();
|
|
3429
|
+
useMarkupHelper(ctx.diagnostics);
|
|
3430
|
+
// (a side-effect import, a stylesheet, stays with the main file)
|
|
3431
|
+
const head = [...imports.declarations(used).filter((d) => d.specifiers.length), t.exportNamedDeclaration(null, plan.sites.map((d) => t.exportSpecifier(t.identifier(d.name), t.identifier(d.name))))];
|
|
3432
|
+
ctx.diagnostics.push({ code: 'svelte-version', severity: 'info', message: `${path.split('/').pop() ?? path} exports snippets from its module script (the elements the file's module code builds: ${plan.names.join(', ')}), which needs Svelte 5.5.0 or later.`, file: ctx.sourceRel, target: 'svelte' });
|
|
3433
|
+
return { plan, file: { path, contents: `<script module lang="ts">${NL}${printProgram(head)}${NL}</script>${NL}${NL}${markup}${NL}`, kind: 'component' } };
|
|
3434
|
+
}
|
|
3435
|
+
/**
|
|
3436
|
+
* The props and state (and values derived from them) an expression reads, functions included, by name in order: what
|
|
3437
|
+
* changes over a component's life and React reads again on each render.
|
|
3438
|
+
*/
|
|
3439
|
+
function reactiveReads(node, ir) {
|
|
3440
|
+
const names = new Set();
|
|
3441
|
+
t.traverseFast(node, (n) => {
|
|
3442
|
+
if (!t.isIdentifier(n))
|
|
3443
|
+
return;
|
|
3444
|
+
const name = ir.refs.get(n);
|
|
3445
|
+
const b = name ? ir.bindings.get(name) : undefined;
|
|
3446
|
+
if (!name || !b)
|
|
3447
|
+
return;
|
|
3448
|
+
if (b.kind === 'prop' || b.kind === 'propsObject' || b.kind === 'rest' || b.kind === 'state' || b.kind === 'reducer' || (b.kind === 'derived' && b.reactive))
|
|
3449
|
+
names.add(name);
|
|
3450
|
+
});
|
|
3451
|
+
return [...names];
|
|
3452
|
+
}
|
|
3453
|
+
/**
|
|
3454
|
+
* The tags of the DOM elements these nodes spread `name` onto (`<button {...props}>`), or null when the nodes read it any
|
|
3455
|
+
* other way (a component's prop, an expression, a handler) or not at all.
|
|
3456
|
+
*/
|
|
3457
|
+
function domSpreadTags(nodes, name) {
|
|
3458
|
+
const tags = new Set();
|
|
3459
|
+
let other = false;
|
|
3460
|
+
const reads = (n) => {
|
|
3461
|
+
let found = false;
|
|
3462
|
+
t.traverseFast(n, (x) => {
|
|
3463
|
+
if (t.isIdentifier(x, { name }))
|
|
3464
|
+
found = true;
|
|
3465
|
+
});
|
|
3466
|
+
return found;
|
|
3467
|
+
};
|
|
3468
|
+
const visit = (value) => {
|
|
3469
|
+
if (other || typeof value !== 'object' || value === null)
|
|
3470
|
+
return;
|
|
3471
|
+
if (Array.isArray(value)) {
|
|
3472
|
+
for (const v of value)
|
|
3473
|
+
visit(v);
|
|
3474
|
+
return;
|
|
3475
|
+
}
|
|
3476
|
+
if (t.isNode(value)) {
|
|
3477
|
+
if (reads(value))
|
|
3478
|
+
other = true;
|
|
3479
|
+
return;
|
|
3480
|
+
}
|
|
3481
|
+
if (Reflect.get(value, 'type') === 'element') {
|
|
3482
|
+
const tag = Reflect.get(value, 'tag');
|
|
3483
|
+
const component = Reflect.get(value, 'component');
|
|
3484
|
+
const attrs = Reflect.get(value, 'attrs');
|
|
3485
|
+
for (const a of Array.isArray(attrs) ? attrs : []) {
|
|
3486
|
+
if (typeof a !== 'object' || a === null)
|
|
3487
|
+
continue;
|
|
3488
|
+
const expr = Reflect.get(a, 'expr');
|
|
3489
|
+
if (Reflect.get(a, 'kind') === 'spread' && t.isNode(expr) && t.isIdentifier(expr, { name })) {
|
|
3490
|
+
if (component === true || typeof tag !== 'string' || !/^[a-z][a-z0-9]*$/.test(tag))
|
|
3491
|
+
other = true;
|
|
3492
|
+
else
|
|
3493
|
+
tags.add(tag);
|
|
3494
|
+
}
|
|
3495
|
+
else
|
|
3496
|
+
visit(a);
|
|
3497
|
+
}
|
|
3498
|
+
visit(Reflect.get(value, 'children'));
|
|
3499
|
+
visit(Reflect.get(value, 'motion'));
|
|
3500
|
+
return;
|
|
3501
|
+
}
|
|
3502
|
+
for (const v of Object.values(value))
|
|
3503
|
+
visit(v);
|
|
3504
|
+
};
|
|
3505
|
+
visit(nodes);
|
|
3506
|
+
return other ? null : tags;
|
|
3507
|
+
}
|
|
3508
|
+
/** The component is async (a React Server Component): lowering reported it (async-component). */
|
|
3509
|
+
function waitsWhileRendering(comp) {
|
|
3510
|
+
return comp.diagnostics.some((d) => d.code === 'async-component');
|
|
3511
|
+
}
|
|
3512
|
+
/**
|
|
3513
|
+
* An async component, as its file is written: no props, script or markup of its own (Svelte rejects `await` at the top
|
|
3514
|
+
* of a component, and a component that waits has no Svelte form), only a comment where its markup would be. The file
|
|
3515
|
+
* stays because it may hold the module's code that the file's other components import; the async-component error (or,
|
|
3516
|
+
* where the converted file does not use the component, the warning it became) says the component is not converted.
|
|
3517
|
+
*/
|
|
3518
|
+
function asyncShell(comp) {
|
|
3519
|
+
return {
|
|
3520
|
+
...comp,
|
|
3521
|
+
items: [],
|
|
3522
|
+
bindings: new Map(),
|
|
3523
|
+
props: [],
|
|
3524
|
+
propsObject: null,
|
|
3525
|
+
propsStyle: 'none',
|
|
3526
|
+
rest: null,
|
|
3527
|
+
declared: new Map(),
|
|
3528
|
+
propsType: null,
|
|
3529
|
+
propsTypeName: null,
|
|
3530
|
+
propsHeritage: [],
|
|
3531
|
+
extendsHtml: null,
|
|
3532
|
+
forwardRef: null,
|
|
3533
|
+
typeParams: null,
|
|
3534
|
+
template: { type: 'unconverted', reason: `${comp.name} is an async component (see the async-component diagnostic)` },
|
|
3535
|
+
fragments: [],
|
|
3536
|
+
provides: [],
|
|
3537
|
+
handleType: null,
|
|
3538
|
+
keptMarkup: [],
|
|
3539
|
+
markupValues: [],
|
|
3540
|
+
};
|
|
3541
|
+
}
|
|
3542
|
+
/** A React style object as the Svelte emitter types it (CSSProperties maps to `Record<string, ...>`). */
|
|
3543
|
+
function isStyleObjectType(type) {
|
|
3544
|
+
return !!type && t.isTSTypeReference(type) && t.isIdentifier(type.typeName, { name: 'Record' }) && t.isTSStringKeyword(type.typeParameters?.params[0]);
|
|
3545
|
+
}
|
|
3546
|
+
/**
|
|
3547
|
+
* The file's props interfaces (each component's, and the local ones they extend) as a Svelte component receives them,
|
|
3548
|
+
* as svelte/elements types them too: `children: ReactNode` is the snippet of its content (`{@render children()}`), never
|
|
3549
|
+
* a string, and a `style` object arrives as a string (a parent passes `style={toStyleString(...)}`).
|
|
3550
|
+
*/
|
|
3551
|
+
function svelteProps(statements, components) {
|
|
3552
|
+
const decls = new Map();
|
|
3553
|
+
for (const s of statements) {
|
|
3554
|
+
const decl = t.isExportNamedDeclaration(s) ? s.declaration : s;
|
|
3555
|
+
if (t.isTSInterfaceDeclaration(decl) || t.isTSTypeAliasDeclaration(decl))
|
|
3556
|
+
decls.set(decl.id.name, decl);
|
|
3557
|
+
}
|
|
3558
|
+
const names = components.flatMap((c) => (c.propsTypeName ? [c.propsTypeName] : []));
|
|
3559
|
+
const seen = new Set();
|
|
3560
|
+
const isSnippet = (x) => t.isTSTypeReference(x) && t.isIdentifier(x.typeName, { name: 'Snippet' });
|
|
3561
|
+
const fix = (members) => {
|
|
3562
|
+
for (const m of members) {
|
|
3563
|
+
if (!t.isTSPropertySignature(m) || !t.isIdentifier(m.key) || !m.typeAnnotation)
|
|
3564
|
+
continue;
|
|
3565
|
+
const type = m.typeAnnotation.typeAnnotation;
|
|
3566
|
+
if (m.key.name === 'children' && t.isTSUnionType(type) && type.types.some(isSnippet))
|
|
3567
|
+
m.typeAnnotation = t.tsTypeAnnotation(t.tsTypeReference(t.identifier('Snippet')));
|
|
3568
|
+
if (m.key.name === 'style' && isStyleObjectType(type))
|
|
3569
|
+
m.typeAnnotation = t.tsTypeAnnotation(t.tsStringKeyword());
|
|
3570
|
+
}
|
|
3571
|
+
};
|
|
3572
|
+
const visit = (type) => {
|
|
3573
|
+
if (t.isTSTypeLiteral(type))
|
|
3574
|
+
fix(type.members);
|
|
3575
|
+
else if (t.isTSIntersectionType(type))
|
|
3576
|
+
type.types.forEach(visit);
|
|
3577
|
+
else if (t.isTSTypeReference(type) && t.isIdentifier(type.typeName)) {
|
|
3578
|
+
visitName(type.typeName.name);
|
|
3579
|
+
// Omit<BaseProps, 'x'>, Partial<BaseProps>
|
|
3580
|
+
type.typeParameters?.params.forEach(visit);
|
|
3581
|
+
}
|
|
3582
|
+
};
|
|
3583
|
+
const visitName = (name) => {
|
|
3584
|
+
const decl = decls.get(name);
|
|
3585
|
+
if (!decl || seen.has(name))
|
|
3586
|
+
return;
|
|
3587
|
+
seen.add(name);
|
|
3588
|
+
if (t.isTSTypeAliasDeclaration(decl))
|
|
3589
|
+
return visit(decl.typeAnnotation);
|
|
3590
|
+
fix(decl.body.body);
|
|
3591
|
+
for (const h of decl.extends ?? []) {
|
|
3592
|
+
if (t.isIdentifier(h.expression))
|
|
3593
|
+
visitName(h.expression.name);
|
|
3594
|
+
h.typeParameters?.params.forEach(visit);
|
|
3595
|
+
}
|
|
3596
|
+
};
|
|
3597
|
+
names.forEach(visitName);
|
|
3598
|
+
}
|
|
3599
|
+
/** Exports a declaration that another component file of the same source imports. */
|
|
3600
|
+
function exportIfLocal(s) {
|
|
3601
|
+
if (t.isExportNamedDeclaration(s) || t.isExportDefaultDeclaration(s))
|
|
3602
|
+
return s;
|
|
3603
|
+
if (t.isVariableDeclaration(s) || t.isFunctionDeclaration(s) || t.isClassDeclaration(s) || t.isTSInterfaceDeclaration(s) || t.isTSTypeAliasDeclaration(s) || t.isTSEnumDeclaration(s))
|
|
3604
|
+
return t.exportNamedDeclaration(s);
|
|
3605
|
+
return s;
|
|
3606
|
+
}
|
|
3607
|
+
function addDeclarationTo(set, d) {
|
|
3608
|
+
const source = d.source.value;
|
|
3609
|
+
if (!d.specifiers.length)
|
|
3610
|
+
set.side(source);
|
|
3611
|
+
for (const s of d.specifiers) {
|
|
3612
|
+
if (t.isImportDefaultSpecifier(s))
|
|
3613
|
+
set.defaultImport(source, s.local.name);
|
|
3614
|
+
else if (t.isImportNamespaceSpecifier(s))
|
|
3615
|
+
set.namespace(source, s.local.name);
|
|
3616
|
+
else {
|
|
3617
|
+
const imported = t.isIdentifier(s.imported) ? s.imported.name : s.imported.value;
|
|
3618
|
+
if (d.importKind === 'type' || s.importKind === 'type')
|
|
3619
|
+
set.type(source, imported, s.local.name);
|
|
3620
|
+
else
|
|
3621
|
+
set.named(source, imported, s.local.name);
|
|
3622
|
+
}
|
|
3623
|
+
}
|
|
3624
|
+
}
|
|
3625
|
+
/** The plain element the component's props rest is spread onto (`<kbd {...props}>`), when there is exactly one. */
|
|
3626
|
+
function restElementTag(comp) {
|
|
3627
|
+
const rest = comp.rest;
|
|
3628
|
+
if (!rest)
|
|
3629
|
+
return null;
|
|
3630
|
+
const tags = new Set();
|
|
3631
|
+
const visit = (value) => {
|
|
3632
|
+
if (!value || typeof value !== 'object')
|
|
3633
|
+
return;
|
|
3634
|
+
if (Array.isArray(value))
|
|
3635
|
+
return value.forEach(visit);
|
|
3636
|
+
if (t.isNode(value))
|
|
3637
|
+
return;
|
|
3638
|
+
const isElement = (v) => Reflect.get(v, 'type') === 'element';
|
|
3639
|
+
if (isElement(value)) {
|
|
3640
|
+
const node = value;
|
|
3641
|
+
if (!node.component && /^[a-z][a-z0-9]*$/.test(node.tag) && node.attrs.some((a) => a.kind === 'spread' && t.isIdentifier(a.expr) && comp.refs.get(a.expr) === rest))
|
|
3642
|
+
tags.add(node.tag);
|
|
3643
|
+
}
|
|
3644
|
+
Object.values(value).forEach(visit);
|
|
3645
|
+
};
|
|
3646
|
+
visit(comp.template);
|
|
3647
|
+
return tags.size === 1 ? ([...tags][0] ?? null) : null;
|
|
3648
|
+
}
|
|
3649
|
+
/**
|
|
3650
|
+
* A Framer Motion element held as a value (`const tags = { div: motion.div }`, `const Tag = big ? motion.h1 : motion.p`)
|
|
3651
|
+
* has no Svelte form: motion in Svelte is an action on an element the markup names (`use:motionAction`), so an element
|
|
3652
|
+
* picked at run time from such a value would render with its motion props as plain attributes and never animate.
|
|
3653
|
+
* Reported as an error at the first read, rather than emitted silently wrong.
|
|
3654
|
+
*/
|
|
3655
|
+
function reportMotionValues(mod, ctx) {
|
|
3656
|
+
if (!mod.motionNames.size)
|
|
3657
|
+
return;
|
|
3658
|
+
const roots = [...mod.moduleBody];
|
|
3659
|
+
for (const fn of [...mod.components, ...mod.hooks])
|
|
3660
|
+
for (const item of fn.items)
|
|
3661
|
+
if ('node' in item && t.isNode(item.node))
|
|
3662
|
+
roots.push(item.node);
|
|
3663
|
+
for (const root of roots) {
|
|
3664
|
+
const reads = [];
|
|
3665
|
+
t.traverse(root, (n, ancestors) => {
|
|
3666
|
+
if (!t.isIdentifier(n) || !mod.motionNames.has(n.name))
|
|
3667
|
+
return;
|
|
3668
|
+
const parent = ancestors[ancestors.length - 1];
|
|
3669
|
+
const keyOf = parent && (t.isObjectProperty(parent.node) || t.isMemberExpression(parent.node) || t.isOptionalMemberExpression(parent.node)) && !parent.node.computed && (parent.key === 'key' || parent.key === 'property');
|
|
3670
|
+
if (!keyOf)
|
|
3671
|
+
reads.push(n);
|
|
3672
|
+
});
|
|
3673
|
+
const found = reads[0];
|
|
3674
|
+
if (!found)
|
|
3675
|
+
continue;
|
|
3676
|
+
ctx.diagnostics.push({
|
|
3677
|
+
code: 'motion-value',
|
|
3678
|
+
severity: 'error',
|
|
3679
|
+
message: `${found.name} (Framer Motion) is held as a value here; in Svelte motion is an action on an element the markup names, so an element picked at run time from a value would not animate. Not converted: write the choice in the markup (\`{as === 'div' ? <${found.name}.div …/> : <${found.name}.span …/>}\`).`,
|
|
3680
|
+
file: ctx.sourceRel,
|
|
3681
|
+
target: ctx.target,
|
|
3682
|
+
...(found.loc ? { line: found.loc.start.line } : {}),
|
|
3683
|
+
});
|
|
3684
|
+
return;
|
|
3685
|
+
}
|
|
3686
|
+
}
|
|
3687
|
+
/**
|
|
3688
|
+
* Framer's useMotionTemplate is a tag (`useMotionTemplate\`blur(${x}px)\``); kept in a name it is converted (see
|
|
3689
|
+
* SvelteScript.motionTemplate); written inline, `motion` has no tag of that kind (its transformValue takes a function
|
|
3690
|
+
* and makes one value at setup), so the tag mapped as it is would call transformValue with the template's parts: an
|
|
3691
|
+
* error.
|
|
3692
|
+
*/
|
|
3693
|
+
function reportMotionTemplates(mod, ctx) {
|
|
3694
|
+
const tags = new Set();
|
|
3695
|
+
for (const decl of mod.imports) {
|
|
3696
|
+
if (!MOTION_PACKAGES.has(decl.source.value))
|
|
3697
|
+
continue;
|
|
3698
|
+
for (const s of decl.specifiers)
|
|
3699
|
+
if (t.isImportSpecifier(s) && (t.isIdentifier(s.imported) ? s.imported.name : s.imported.value) === 'useMotionTemplate')
|
|
3700
|
+
tags.add(s.local.name);
|
|
3701
|
+
}
|
|
3702
|
+
if (!tags.size)
|
|
3703
|
+
return;
|
|
3704
|
+
const roots = [];
|
|
3705
|
+
for (const comp of mod.components) {
|
|
3706
|
+
templateExpressions(comp.template, roots);
|
|
3707
|
+
for (const f of comp.fragments)
|
|
3708
|
+
templateExpressions(f.template, roots);
|
|
3709
|
+
}
|
|
3710
|
+
for (const fn of [...mod.components, ...mod.hooks]) {
|
|
3711
|
+
for (const item of fn.items) {
|
|
3712
|
+
// `const bg = useMotionTemplate\`…\`` is converted (SvelteScript.motionTemplate): only its parts are searched
|
|
3713
|
+
if (item.kind === 'derived' && t.isIdentifier(item.id) && isMotionTemplate(item.init))
|
|
3714
|
+
roots.push(item.init.quasi);
|
|
3715
|
+
else
|
|
3716
|
+
for (const v of Object.values(item))
|
|
3717
|
+
if (t.isNode(v))
|
|
3718
|
+
roots.push(v);
|
|
3719
|
+
}
|
|
3720
|
+
}
|
|
3721
|
+
for (const root of roots) {
|
|
3722
|
+
let found = null;
|
|
3723
|
+
t.traverseFast(root, (n) => {
|
|
3724
|
+
if (!found && t.isTaggedTemplateExpression(n) && t.isIdentifier(n.tag) && tags.has(n.tag.name))
|
|
3725
|
+
found = n;
|
|
3726
|
+
});
|
|
3727
|
+
if (!found)
|
|
3728
|
+
continue;
|
|
3729
|
+
ctx.diagnostics.push({ code: 'motion-hook', severity: 'error', message: 'useMotionTemplate is written inline (in the markup or an expression), not kept in a name: its motion form, transformValue(() => `…${x.get()}…`), makes one motion value at setup, which needs a name of its own (`const bg = useMotionTemplate`…``). Not converted.', file: ctx.sourceRel, target: ctx.target });
|
|
3730
|
+
return;
|
|
3731
|
+
}
|
|
3732
|
+
}
|
|
3733
|
+
/** A type that is text only:`string`, `number`, literals of them, and unions of those (with `undefined` / `null`). */
|
|
3734
|
+
function isTextType(type) {
|
|
3735
|
+
if (t.isTSParenthesizedType(type))
|
|
3736
|
+
return isTextType(type.typeAnnotation);
|
|
3737
|
+
if (t.isTSUnionType(type))
|
|
3738
|
+
return type.types.some((x) => !t.isTSUndefinedKeyword(x) && !t.isTSNullKeyword(x)) && type.types.every((x) => t.isTSUndefinedKeyword(x) || t.isTSNullKeyword(x) || isTextType(x));
|
|
3739
|
+
return t.isTSStringKeyword(type) || t.isTSNumberKeyword(type) || (t.isTSLiteralType(type) && (t.isStringLiteral(type.literal) || t.isNumericLiteral(type.literal) || t.isTemplateLiteral(type.literal)));
|
|
3740
|
+
}
|
|
3741
|
+
/**
|
|
3742
|
+
* Whether React types the component's children as text only (`children: string`): Svelte's form is then a prop named
|
|
3743
|
+
* `children` holding that text (the parent passes `children="…"`), not a snippet; the component reads it as React does.
|
|
3744
|
+
*/
|
|
3745
|
+
export function textChildren(comp) {
|
|
3746
|
+
const type = comp.declared.get('children')?.type;
|
|
3747
|
+
return comp.props.some((p) => p.kind === 'children') && !!type && isTextType(type);
|
|
3748
|
+
}
|
|
3749
|
+
/**
|
|
3750
|
+
* Children read as text or data (`children.split('')`, `children.length`): React's children may be a string, a Svelte
|
|
3751
|
+
* component's are a snippet (a function), so the read would fail or mean something else at run time. Reported as an
|
|
3752
|
+
* error where it is read; the fix is the caller's: pass the text as a prop.
|
|
3753
|
+
*/
|
|
3754
|
+
function reportChildrenText(comp, ctx) {
|
|
3755
|
+
const children = comp.props.find((p) => p.kind === 'children');
|
|
3756
|
+
if (!children || textChildren(comp))
|
|
3757
|
+
return;
|
|
3758
|
+
const roots = templateExpressions(comp.template);
|
|
3759
|
+
for (const f of comp.fragments)
|
|
3760
|
+
templateExpressions(f.template, roots);
|
|
3761
|
+
for (const item of comp.items)
|
|
3762
|
+
if ('node' in item && t.isNode(item.node))
|
|
3763
|
+
roots.push(item.node);
|
|
3764
|
+
for (const root of roots) {
|
|
3765
|
+
const reads = [];
|
|
3766
|
+
t.traverseFast(root, (n) => {
|
|
3767
|
+
if ((t.isMemberExpression(n) || t.isOptionalMemberExpression(n)) && t.isIdentifier(n.object, { name: children.local }))
|
|
3768
|
+
reads.push(t.memberExpression(n.object, n.property, n.computed));
|
|
3769
|
+
});
|
|
3770
|
+
const found = reads[0];
|
|
3771
|
+
if (!found)
|
|
3772
|
+
continue;
|
|
3773
|
+
const what = t.isIdentifier(found.property) && !found.computed ? `${children.local}.${found.property.name}` : `${children.local}[…]`;
|
|
3774
|
+
ctx.diagnostics.push({
|
|
3775
|
+
code: 'children-value',
|
|
3776
|
+
severity: 'error',
|
|
3777
|
+
message: `${comp.name} reads its children as a value (${what}); a Svelte component's children are a snippet, which has no text or members to read. Not converted: take the text as a prop (\`text="…"\`) instead of children.`,
|
|
3778
|
+
file: ctx.sourceRel,
|
|
3779
|
+
target: ctx.target,
|
|
3780
|
+
...(found.object.loc ? { line: found.object.loc.start.line } : {}),
|
|
3781
|
+
});
|
|
3782
|
+
return;
|
|
3783
|
+
}
|
|
3784
|
+
}
|