astro-magic-move 0.1.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jacob Cable
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export { default as MagicMove } from "./src/MagicMove.astro";
2
+ export type { MagicMoveProps } from "./src/types";
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "astro-magic-move",
3
+ "version": "0.1.0",
4
+ "description": "Animated code morphing for Astro, powered by Shiki Magic Move. Build-time tokenization, zero-framework client JS, CSS-variable theming.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "Jacob Cable",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/cabljac/astro-magic-move"
11
+ },
12
+ "homepage": "https://astro-magic-move.dev",
13
+ "exports": {
14
+ ".": "./index.ts",
15
+ "./styles": "./styles/magic-move.css"
16
+ },
17
+ "files": [
18
+ "index.ts",
19
+ "src/",
20
+ "styles/",
21
+ "LICENSE"
22
+ ],
23
+ "keywords": [
24
+ "astro-component",
25
+ "withastro",
26
+ "shiki",
27
+ "code-animation",
28
+ "magic-move"
29
+ ],
30
+ "peerDependencies": {
31
+ "astro": "^5.0.0 || ^6.0.0"
32
+ },
33
+ "dependencies": {
34
+ "shiki": "^3.0.0",
35
+ "shiki-magic-move": "^1.3.0"
36
+ }
37
+ }
@@ -0,0 +1,184 @@
1
+ ---
2
+ import type { MagicMoveProps } from "./types";
3
+ import { cssVarTheme } from "./theme";
4
+ import { createHighlighter, type HighlighterGeneric } from "shiki";
5
+ import { codeToKeyedTokens, createMagicMoveMachine } from "shiki-magic-move/core";
6
+
7
+ interface Props extends MagicMoveProps {}
8
+
9
+ const {
10
+ before,
11
+ after,
12
+ steps: stepsProp,
13
+ lang = "typescript",
14
+ trigger = "scroll",
15
+ duration = 800,
16
+ stagger = 0.3,
17
+ threshold = 0.4,
18
+ lineNumbers = false,
19
+ class: className,
20
+ } = Astro.props;
21
+
22
+ // Resolve steps from props
23
+ let steps: string[];
24
+ if (stepsProp) {
25
+ if (stepsProp.length < 2) {
26
+ throw new Error("[astro-magic-move] `steps` must contain at least 2 items.");
27
+ }
28
+ steps = stepsProp;
29
+ } else if (before != null && after != null) {
30
+ steps = [before, after];
31
+ } else {
32
+ throw new Error(
33
+ "[astro-magic-move] Provide either `before` + `after` or `steps` (min 2 items).",
34
+ );
35
+ }
36
+
37
+ // Module-level highlighter cache (survives HMR via globalThis)
38
+ const CACHE_KEY = "__astro_magic_move_hl";
39
+ type HLCache = Map<string, HighlighterGeneric<string, string>>;
40
+ const hlCache: HLCache = ((globalThis as Record<string, unknown>)[CACHE_KEY] ??= new Map()) as HLCache;
41
+
42
+ let highlighter = hlCache.get(lang);
43
+ if (!highlighter) {
44
+ highlighter = await createHighlighter({
45
+ themes: [cssVarTheme],
46
+ langs: [lang],
47
+ });
48
+ hlCache.set(lang, highlighter);
49
+ }
50
+
51
+ // Build the magic move machine and compile all steps at build time
52
+ const machine = createMagicMoveMachine(
53
+ (code) =>
54
+ codeToKeyedTokens(highlighter, code, { lang, theme: "css-variables" }, lineNumbers),
55
+ {},
56
+ );
57
+
58
+ const compiledSteps = steps.map((code) => machine.commit(code).current);
59
+
60
+ const stepsJson = JSON.stringify(compiledSteps);
61
+ ---
62
+
63
+ <magic-move
64
+ class:list={["magic-move", className]}
65
+ data-trigger={trigger}
66
+ data-duration={duration}
67
+ data-stagger={stagger}
68
+ data-threshold={threshold}
69
+ data-lang={lang}
70
+ {...(lineNumbers ? { "data-line-numbers": "" } : {})}
71
+ >
72
+ <pre class="shiki-magic-move-container"><code>{steps[0]}</code></pre>
73
+ <script is:inline type="application/json" set:html={stepsJson} />
74
+ </magic-move>
75
+
76
+ <script>
77
+ import { MagicMoveRenderer } from "shiki-magic-move/renderer";
78
+
79
+ class MagicMoveElement extends HTMLElement {
80
+ private renderer: MagicMoveRenderer | null = null;
81
+ private steps: any[] = [];
82
+ private currentStep = 0;
83
+ private observer: IntersectionObserver | null = null;
84
+
85
+ connectedCallback() {
86
+ const dataScript = this.querySelector('script[type="application/json"]');
87
+ if (!dataScript?.textContent) return;
88
+ this.steps = JSON.parse(dataScript.textContent);
89
+ dataScript.remove();
90
+
91
+ const container = this.querySelector("pre");
92
+ if (!container) return;
93
+ container.innerHTML = "";
94
+
95
+ const duration = Number(this.dataset.duration ?? 800);
96
+ const stagger = Number(this.dataset.stagger ?? 0.3);
97
+ const threshold = Number(this.dataset.threshold ?? 0.4);
98
+ const trigger = this.dataset.trigger ?? "scroll";
99
+ const lineNumbers = this.hasAttribute("data-line-numbers");
100
+
101
+ this.renderer = new MagicMoveRenderer(container, {
102
+ duration,
103
+ stagger,
104
+ lineNumbers,
105
+ animateContainer: true,
106
+ });
107
+
108
+ // replace() for instant initial display (no animation, no empty frame)
109
+ this.renderer.replace(this.steps[0]);
110
+ this.currentStep = 0;
111
+ this.setupTrigger(trigger, threshold);
112
+ }
113
+
114
+ disconnectedCallback() {
115
+ this.observer?.disconnect();
116
+ }
117
+
118
+ private setupTrigger(trigger: string, threshold: number) {
119
+ switch (trigger) {
120
+ case "scroll":
121
+ this.setupScrollTrigger(threshold);
122
+ break;
123
+ case "click":
124
+ this.style.cursor = "pointer";
125
+ this.addEventListener("click", () => {
126
+ const next = (this.currentStep + 1) % this.steps.length;
127
+ this.animateToStep(next);
128
+ });
129
+ break;
130
+ case "auto":
131
+ requestAnimationFrame(() => {
132
+ this.animateToStep(1);
133
+ });
134
+ break;
135
+ }
136
+ }
137
+
138
+ private setupScrollTrigger(threshold: number) {
139
+ this.observer = new IntersectionObserver(
140
+ ([entry]) => {
141
+ if (entry.isIntersecting) {
142
+ this.animateToStep(1);
143
+ this.observer?.disconnect();
144
+ }
145
+ },
146
+ { threshold },
147
+ );
148
+ this.observer.observe(this);
149
+ }
150
+
151
+ private async animateToStep(stepIndex: number) {
152
+ if (!this.renderer || stepIndex === this.currentStep) return;
153
+ if (stepIndex < 0 || stepIndex >= this.steps.length) return;
154
+
155
+ await this.renderer.render(this.steps[stepIndex]);
156
+ this.currentStep = stepIndex;
157
+
158
+ this.dispatchEvent(
159
+ new CustomEvent("magic-move:step", {
160
+ detail: { step: stepIndex, total: this.steps.length },
161
+ bubbles: true,
162
+ }),
163
+ );
164
+ }
165
+ }
166
+
167
+ if (!customElements.get("magic-move")) {
168
+ customElements.define("magic-move", MagicMoveElement);
169
+ }
170
+ </script>
171
+
172
+ <style is:global>
173
+ magic-move {
174
+ display: block;
175
+ position: relative;
176
+ }
177
+
178
+ magic-move .shiki-magic-move-container {
179
+ margin: 0;
180
+ overflow-x: auto;
181
+ overflow-y: hidden;
182
+ scrollbar-width: thin;
183
+ }
184
+ </style>
package/src/theme.ts ADDED
@@ -0,0 +1,25 @@
1
+ import { createCssVariablesTheme } from "shiki/core";
2
+
3
+ /**
4
+ * A shared CSS-variables theme. Colors are driven by `--shiki-*` custom
5
+ * properties. Sensible defaults are provided so the component looks good
6
+ * out of the box — consumers override as many or as few as they want.
7
+ */
8
+ export const cssVarTheme = createCssVariablesTheme({
9
+ name: "css-variables",
10
+ variablePrefix: "--shiki-",
11
+ variableDefaults: {
12
+ foreground: "#d4d4d4",
13
+ background: "#1e1e1e",
14
+ "token-keyword": "#c586c0",
15
+ "token-string": "#ce9178",
16
+ "token-function": "#dcdcaa",
17
+ "token-comment": "#6a9955",
18
+ "token-constant": "#4fc1ff",
19
+ "token-parameter": "#9cdcfe",
20
+ "token-punctuation": "#d4d4d4",
21
+ "token-string-expression": "#ce9178",
22
+ "token-link": "#4fc1ff",
23
+ },
24
+ fontStyle: true,
25
+ });
package/src/types.ts ADDED
@@ -0,0 +1,46 @@
1
+ export interface MagicMoveProps {
2
+ /** Code for the initial state. Shorthand for two-step usage. */
3
+ before?: string;
4
+
5
+ /** Code for the final state. Shorthand for two-step usage. */
6
+ after?: string;
7
+
8
+ /**
9
+ * Array of code strings for multi-step morphing.
10
+ * Takes precedence over before/after if provided.
11
+ * Must contain at least 2 items.
12
+ */
13
+ steps?: string[];
14
+
15
+ /** Language for syntax highlighting. Default: `'typescript'` */
16
+ lang?: string;
17
+
18
+ /**
19
+ * How the animation is triggered:
20
+ * - `'scroll'`: animate when element enters viewport (default)
21
+ * - `'click'`: toggle forward on click, wraps around
22
+ * - `'auto'`: animate immediately when the element mounts
23
+ */
24
+ trigger?: "scroll" | "click" | "auto";
25
+
26
+ /** Animation duration in ms. Default: `800` */
27
+ duration?: number;
28
+
29
+ /** Stagger delay for token entrance. Default: `0.3` */
30
+ stagger?: number;
31
+
32
+ /**
33
+ * IntersectionObserver threshold (0–1). Only used when trigger='scroll'.
34
+ * Default: `0.4`
35
+ */
36
+ threshold?: number;
37
+
38
+ /** Whether to animate line numbers. Default: `false` */
39
+ lineNumbers?: boolean;
40
+
41
+ /**
42
+ * CSS class(es) applied to the outer `<magic-move>` element.
43
+ * Use this for all visual styling (bg, border, rounded, shadow, padding, width, etc).
44
+ */
45
+ class?: string;
46
+ }
@@ -0,0 +1,23 @@
1
+ /* Core transition CSS from shiki-magic-move */
2
+ @import "shiki-magic-move/style.css";
3
+
4
+ /* Structural defaults — consumers can override via class prop */
5
+ magic-move {
6
+ display: block;
7
+ position: relative;
8
+ }
9
+
10
+ .shiki-magic-move-container {
11
+ margin: 0;
12
+ overflow-x: auto;
13
+ overflow-y: hidden;
14
+ padding: 1rem 1.25rem;
15
+ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas,
16
+ "Liberation Mono", "Courier New", monospace;
17
+ font-size: 0.875rem;
18
+ line-height: 1.7;
19
+ text-align: left;
20
+ background: var(--shiki-background, #1e1e1e);
21
+ color: var(--shiki-foreground, #d4d4d4);
22
+ scrollbar-width: thin;
23
+ }