The best way to control Claude Code, Codex and more from any computer or phone

main
tsx 680 lines 21.4 KB
Raw
1 import { Icon } from "@iconify/react";
2 import { useEffect, useRef, useState } from "react";
3 import { highlightTS } from "../marketing/highlightTS";
4
5 /**
6 * Showcase for the "Compose Effects and Layers..." (Effect-pilled) section.
7 *
8 * Single terminal-chromed card with a tab strip in the header and one
9 * focused example per tab. Each panel pairs a trimmed code snippet (left)
10 * with a stylized "generated artifact" panel (right) that visually proves
11 * what Alchemy wired up. Tabs auto-cycle while in view; tap to pin.
12 *
13 * Tabs:
14 * - IAM bindings — `S3.GetObject(...)` → permissions + env vars
15 * - Event sources — `DynamoDB.stream(...).process(...)` → EventSourceMapping
16 * - Durable Objects — `Cloudflare.DurableObject`
17 * - Containers — `Cloudflare.Container`
18 * - Workflows — `Cloudflare.Workflow`
19 * - Layers — `Layer.effect(JobStorage, ...)`
20 */
21
22 type Tab = "iam" | "stream" | "do" | "container" | "workflow" | "layer";
23
24 const TABS: { id: Tab; label: string }[] = [
25 { id: "iam", label: "IAM bindings" },
26 { id: "stream", label: "Event sources" },
27 { id: "do", label: "Durable Objects" },
28 { id: "container", label: "Containers" },
29 { id: "workflow", label: "Workflows" },
30 { id: "layer", label: "Layers" },
31 ];
32
33 const CYCLE_MS = 6000;
34 /** Longer dwell on the Layer tab so both impls (ddb / d1) get airtime. */
35 const LAYER_CYCLE_MS = 13000;
36 /** How long each Layer impl is "held" before the breathing cross-fade swaps. */
37 const LAYER_IMPL_SWAP_MS = 3500;
38
39 const IAM_CODE = `export default AWS.Lambda.Function(
40 "JobApi",
41 Effect.gen(function* () {
42 const getPhoto = yield* S3.GetObject(Photos);
43 const putJob = yield* DynamoDB.PutItem(Jobs);
44
45 return {
46 fetch: Effect.gen(function* () {
47 const req = yield* HttpServerRequest;
48 return yield* getPhoto({ key: req.url.slice(1) });
49 }),
50 };
51 }),
52 );`;
53
54 const STREAM_CODE = `export default AWS.Lambda.Function(
55 "JobsConsumer",
56 Effect.gen(function* () {
57 yield* DynamoDB.stream(Jobs).process((stream) =>
58 stream.pipe(
59 Stream.map((r) => r.dynamodb.NewImage),
60 Stream.tap((job) => Effect.log(\`new job: \${job.id.S}\`)),
61 Stream.runDrain,
62 ),
63 );
64 }),
65 );`;
66
67 const DO_CODE = `export default class Room extends Cloudflare.DurableObject<Room>()(
68 "Rooms",
69 Effect.gen(function* () {
70 const state = yield* Cloudflare.DurableObjectState;
71 return Effect.gen(function* () {
72 const sessions = new Map<string, Cloudflare.WebSocket>();
73
74 return {
75 fetch: Effect.gen(function* () {
76 const [response, socket] = yield* Cloudflare.upgrade();
77 sessions.set(crypto.randomUUID(), socket);
78 return response;
79 }),
80 };
81 });
82 }),
83 ) {}`;
84
85 const CONTAINER_CODE = `export class Sandbox extends Cloudflare.Container<Sandbox, {
86 exec: (cmd: string) => Effect.Effect<ExecResult>;
87 }>()("Sandbox") {}
88
89 export const SandboxLive = Sandbox.make(
90 Stack.useSync((stack) => ({
91 main: import.meta.url,
92 instanceType: stack.stage === "prod" ? "standard-1" : "dev",
93 })),
94 Effect.gen(function* () {
95 const cp = yield* ChildProcessSpawner;
96 return Sandbox.of({
97 exec: (cmd) => cp.spawn(ChildProcess.make(cmd, { shell: true })),
98 });
99 }),
100 );`;
101
102 const WORKFLOW_CODE = `export default class Notifier extends Cloudflare.Workflow<Notifier>()(
103 "Notifier",
104 Effect.gen(function* () {
105 const rooms = yield* Room;
106 return Effect.gen(function* () {
107 const { roomId, message } = (yield* Cloudflare.Workflows.WorkflowEvent).payload;
108 yield* Cloudflare.Workflows.task("store", rooms.getByName(roomId).store(message));
109 yield* Cloudflare.Workflows.task("process", processMessage(message));
110 yield* Cloudflare.Workflows.task("broadcast", rooms.getByName(roomId).broadcast(message));
111 yield* Cloudflare.Workflows.sleep("cooldown", "2 seconds");
112 yield* Cloudflare.Workflows.task("finalize", rooms.getByName(roomId).cleanup());
113 });
114 }),
115 ) {}`;
116
117 type LayerImpl = "ddb" | "d1";
118
119 /**
120 * The Layer tab renders a structural diff between JobStorageDynamoDB and
121 * JobStorageD1. The two snippets are split into segments: "common" lines
122 * stay static; each "diff" segment overlays the ddb and d1 variants in the
123 * same grid cell so the inactive one fully hides (opacity 0) and the active
124 * one occupies that space — crossfading smoothly between them.
125 *
126 * Structurally parallel layout keeps the diff readable column-for-column.
127 */
128 type LayerSegment =
129 | { kind: "common"; lines: string[] }
130 | { kind: "diff"; ddb: string[]; d1: string[] };
131
132 const LAYER_SEGMENTS: LayerSegment[] = [
133 {
134 kind: "common",
135 lines: [
136 "export class JobStorage extends Context.Service<JobStorage, {",
137 " putJob: (job: Job) => Effect.Effect<Job, PutJobError>;",
138 " getJob: (id: string) => Effect.Effect<Job | undefined, GetJobError>;",
139 '}>()("JobStorage") {}',
140 "",
141 ],
142 },
143 {
144 kind: "diff",
145 ddb: [
146 "export const JobStorageDynamoDB = Layer.effect(JobStorage, Effect.gen(function* () {",
147 ' const table = yield* DynamoDB.Table("JobsTable", { partitionKey: "id" });',
148 " const putItem = yield* DynamoDB.PutItem(table);",
149 " const getItem = yield* DynamoDB.GetItem.bind(table);",
150 ],
151 d1: [
152 "export const JobStorageD1 = Layer.effect(JobStorage, Effect.gen(function* () {",
153 ' const db = yield* Cloudflare.D1.Database("JobsDB");',
154 " const conn = yield* Cloudflare.D1.QueryDatabase(db);",
155 "",
156 ],
157 },
158 {
159 kind: "common",
160 lines: [" return JobStorage.of({"],
161 },
162 {
163 kind: "diff",
164 ddb: [
165 " putJob: (job) => putItem({ Item: { id: { S: job.id } } }),",
166 " getJob: (id) => getItem({ Key: { id: { S: id } } }),",
167 ],
168 d1: [
169 " putJob: (job) => conn.exec(`INSERT INTO jobs (id) VALUES ('${job.id}')`),",
170 " getJob: (id) => conn.exec(`SELECT * FROM jobs WHERE id = '${id}'`),",
171 ],
172 },
173 {
174 kind: "common",
175 lines: [" });", "}));"],
176 },
177 ];
178
179 const CODE_BY_TAB: Record<Exclude<Tab, "layer">, string> = {
180 iam: IAM_CODE,
181 stream: STREAM_CODE,
182 do: DO_CODE,
183 container: CONTAINER_CODE,
184 workflow: WORKFLOW_CODE,
185 };
186
187 export default function EffectPilledShowcase() {
188 const [tab, setTab] = useState<Tab>("iam");
189 const [pinned, setPinned] = useState(false);
190 const [layerImpl, setLayerImpl] = useState<LayerImpl>("ddb");
191 const wrapRef = useRef<HTMLDivElement>(null);
192
193 // Tab auto-cycle. Dwell longer on the Layer tab so both impls show
194 // before moving on to the next tab.
195 useEffect(() => {
196 if (pinned) return;
197 let cancelled = false;
198 let timer: ReturnType<typeof setTimeout> | null = null;
199
200 const schedule = () => {
201 const dwell = tab === "layer" ? LAYER_CYCLE_MS : CYCLE_MS;
202 timer = setTimeout(() => {
203 if (cancelled) return;
204 setTab((t) => {
205 const idx = TABS.findIndex((x) => x.id === t);
206 return TABS[(idx + 1) % TABS.length]!.id;
207 });
208 }, dwell);
209 };
210
211 const obs = new IntersectionObserver(
212 (entries) => {
213 for (const e of entries) {
214 if (e.isIntersecting) {
215 schedule();
216 } else if (timer) {
217 clearTimeout(timer);
218 timer = null;
219 }
220 }
221 },
222 { threshold: 0.3 },
223 );
224 if (wrapRef.current) obs.observe(wrapRef.current);
225
226 return () => {
227 cancelled = true;
228 if (timer) clearTimeout(timer);
229 obs.disconnect();
230 };
231 }, [tab, pinned]);
232
233 // Inner oscillation for the Layer tab — swap between ddb and d1
234 // implementations on a separate timer. Resets to "ddb" whenever we
235 // leave the tab so the user always sees the Dynamo example first.
236 useEffect(() => {
237 if (tab !== "layer") {
238 setLayerImpl("ddb");
239 return;
240 }
241 let cancelled = false;
242 const timer = setInterval(() => {
243 if (cancelled) return;
244 setLayerImpl((i) => (i === "ddb" ? "d1" : "ddb"));
245 }, LAYER_IMPL_SWAP_MS);
246 return () => {
247 cancelled = true;
248 clearInterval(timer);
249 };
250 }, [tab]);
251
252 const onTab = (next: Tab) => {
253 setPinned(true);
254 setTab(next);
255 };
256
257 const codeHtml = tab === "layer" ? null : highlightTS(CODE_BY_TAB[tab]);
258 // Drives the fade-in for the whole panel on tab switch. Intentionally
259 // does NOT include layerImpl — the Layer tab uses CSS transitions to
260 // breathe between its two impls without remounting.
261 const splitKey = tab;
262
263 return (
264 <div ref={wrapRef} className="eff-showcase" data-nosnippet="">
265 <div className="eff-showcase__chrome">
266 <div className="eff-showcase__header">
267 <span className="alc-code-block__dot" style={{ background: "var(--alc-danger)" }} />
268 <span className="alc-code-block__dot" style={{ background: "var(--alc-warn)" }} />
269 <span
270 className="alc-code-block__dot"
271 style={{ background: "var(--alc-accent-bright)" }}
272 />
273 <div className="eff-showcase__tabs" role="tablist">
274 {TABS.map((t) => (
275 <button
276 key={t.id}
277 type="button"
278 role="tab"
279 aria-selected={tab === t.id}
280 className="eff-showcase__tab"
281 data-active={tab === t.id}
282 onClick={() => onTab(t.id)}
283 >
284 {t.label}
285 </button>
286 ))}
287 </div>
288 </div>
289
290 <div className="eff-showcase__body">
291 <div className="eff-showcase__split" key={splitKey}>
292 <div className="eff-showcase__code">
293 {tab === "layer" ? (
294 <LayerCodeDiff impl={layerImpl} />
295 ) : (
296 <pre
297 className="eff-showcase__pre eff-showcase__fade"
298 dangerouslySetInnerHTML={{ __html: codeHtml ?? "" }}
299 />
300 )}
301 </div>
302 <div className="eff-showcase__artifact">
303 <ArtifactPanel tab={tab} layerImpl={layerImpl} />
304 </div>
305 </div>
306 </div>
307 </div>
308 <div className="eff-showcase__hint" aria-hidden>
309 {pinned ? <span>tap a tab to switch</span> : <span>cycling · tap to pin</span>}
310 </div>
311 </div>
312 );
313 }
314
315 function ArtifactPanel({ tab, layerImpl }: { tab: Tab; layerImpl: LayerImpl }) {
316 switch (tab) {
317 case "iam":
318 return <IamPanel />;
319 case "stream":
320 return <StreamPanel />;
321 case "do":
322 return <DurableObjectPanel />;
323 case "container":
324 return <ContainerPanel />;
325 case "workflow":
326 return <WorkflowPanel />;
327 case "layer":
328 return <LayerPanel impl={layerImpl} />;
329 }
330 }
331
332 /* ───────────────────────── IAM bindings ───────────────────────── */
333
334 function IamPanel() {
335 const PERMISSIONS = [
336 { icon: "logos:aws-s3", action: "s3:GetObject", target: "Photos/*" },
337 { icon: "logos:aws-dynamodb", action: "dynamodb:PutItem", target: "Jobs" },
338 ];
339 const ENV_VARS = [
340 { name: "PHOTOS_BUCKET", value: "arn:aws:s3:::photos-…" },
341 { name: "JOBS_TABLE", value: "arn:aws:dynamodb:…:table/Jobs-…" },
342 ];
343 return (
344 <>
345 <div className="eff-showcase__group">
346 <div className="eff-showcase__group-title">Permissions</div>
347 {PERMISSIONS.map((p, i) => (
348 <div
349 className="eff-showcase__perm"
350 key={p.action}
351 style={{ animationDelay: `${120 + i * 120}ms` }}
352 >
353 <Icon
354 icon={p.icon}
355 width={20}
356 height={20}
357 aria-hidden
358 className="eff-showcase__perm-icon"
359 />
360 <span className="eff-showcase__perm-action">{p.action}</span>
361 <span className="eff-showcase__perm-arrow" aria-hidden>
362 →
363 </span>
364 <span className="eff-showcase__perm-target">{p.target}</span>
365 </div>
366 ))}
367 </div>
368 <div className="eff-showcase__group">
369 <div className="eff-showcase__group-title">Environment</div>
370 <div className="eff-showcase__envs">
371 {ENV_VARS.map((e, i) => (
372 <div
373 className="eff-showcase__env"
374 key={e.name}
375 style={{ animationDelay: `${360 + i * 100}ms` }}
376 >
377 <span className="eff-showcase__env-name">{e.name}</span>
378 <span className="eff-showcase__env-eq" aria-hidden>
379 =
380 </span>
381 <span className="eff-showcase__env-value">{e.value}</span>
382 </div>
383 ))}
384 </div>
385 </div>
386 </>
387 );
388 }
389
390 /* ───────────────────────── Event sources ───────────────────────── */
391
392 function StreamPanel() {
393 return (
394 <div className="eff-showcase__group">
395 <div className="eff-showcase__group-title">Wired event source</div>
396 <div className="eff-showcase__flow">
397 <FlowNode icon="logos:aws-dynamodb" label="Jobs" sub="DynamoDB.Table" delay={120} />
398 <FlowEdge label="stream" delay={260} />
399 <FlowNode
400 icon="logos:aws-lambda"
401 label="EventSourceMapping"
402 sub="created by alchemy"
403 accent
404 delay={320}
405 />
406 <FlowEdge label="invoke" delay={440} />
407 <FlowNode icon="mdi:lambda" label="handler" sub="your function" delay={500} />
408 </div>
409 </div>
410 );
411 }
412
413 /* ───────────────────────── Durable Objects ───────────────────────── */
414
415 function DurableObjectPanel() {
416 const FEATURES = [
417 {
418 icon: "logos:cloudflare-icon",
419 label: "Cloudflare.DurableObject",
420 sub: "one instance per name · single-threaded",
421 },
422 {
423 icon: "mdi:database",
424 label: "DurableObjectState",
425 sub: "per-instance SQLite, persists across restarts",
426 },
427 {
428 icon: "mdi:transit-connection-variant",
429 label: "WebSocket sessions",
430 sub: "hibernation-safe via serializeAttachment",
431 },
432 ];
433 return (
434 <div className="eff-showcase__group">
435 <div className="eff-showcase__group-title">Generated DO</div>
436 {FEATURES.map((f, i) => (
437 <FeatureRow key={f.label} {...f} delay={120 + i * 120} />
438 ))}
439 </div>
440 );
441 }
442
443 /* ───────────────────────── Containers ───────────────────────── */
444
445 function ContainerPanel() {
446 const FEATURES = [
447 {
448 icon: "logos:docker-icon",
449 label: "Image",
450 sub: "Dockerfile generated · platform builds",
451 },
452 {
453 icon: "mdi:server",
454 label: "Instance",
455 sub: "dev → 256 MB · prod → standard-1",
456 },
457 {
458 icon: "mdi:console",
459 label: "exec(cmd)",
460 sub: "typed Effect · spawns via ChildProcessSpawner",
461 },
462 ];
463 return (
464 <div className="eff-showcase__group">
465 <div className="eff-showcase__group-title">Generated container</div>
466 {FEATURES.map((f, i) => (
467 <FeatureRow key={f.label} {...f} delay={120 + i * 120} />
468 ))}
469 </div>
470 );
471 }
472
473 /* ───────────────────────── Workflows ───────────────────────── */
474
475 function WorkflowPanel() {
476 const STEPS = [
477 { label: "store", sub: "task · durable retry" },
478 { label: "process", sub: "task · pure transform" },
479 { label: "broadcast", sub: "task · DO call" },
480 { label: "cooldown", sub: "sleep · 2 seconds" },
481 { label: "finalize", sub: "task · DO call" },
482 ];
483 return (
484 <div className="eff-showcase__group">
485 <div className="eff-showcase__group-title">Workflow steps</div>
486 <div className="eff-showcase__steps">
487 {STEPS.map((s, i) => (
488 <div
489 className="eff-showcase__step"
490 key={s.label}
491 style={{ animationDelay: `${100 + i * 90}ms` }}
492 >
493 <span className="eff-showcase__step-num">{i + 1}</span>
494 <span className="eff-showcase__step-label">{s.label}</span>
495 <span className="eff-showcase__step-sub">{s.sub}</span>
496 </div>
497 ))}
498 </div>
499 </div>
500 );
501 }
502
503 /* ───────────────────────── Layers ───────────────────────── */
504
505 function LayerPanel({ impl }: { impl: LayerImpl }) {
506 // The "Composed from" group overlays the ddb and d1 row-stacks in the
507 // same grid cell so only the active variant is visible. Same crossfade
508 // pattern as the code diff on the left.
509 return (
510 <>
511 <div className="eff-showcase__group">
512 <div className="eff-showcase__group-title">Provides</div>
513 <FeatureRow
514 icon="mdi:layers-triple"
515 label="JobStorage"
516 sub="Context.Service · putJob · getJob"
517 delay={120}
518 />
519 </div>
520 <div className="eff-showcase__group">
521 <div className="eff-showcase__group-title">Composed from</div>
522 <div className="eff-showcase__variant-stack">
523 <div
524 className="eff-showcase__variant"
525 data-active={impl === "ddb"}
526 aria-hidden={impl !== "ddb"}
527 >
528 <FeatureRow
529 icon="logos:aws-dynamodb"
530 label="DynamoDB.Table"
531 sub='"JobsTable" · partitionKey: "id"'
532 delay={240}
533 />
534 <FeatureRow
535 icon="mdi:key"
536 label="GetItem · PutItem"
537 sub="bound capabilities · IAM auto-generated"
538 delay={340}
539 />
540 </div>
541 <div
542 className="eff-showcase__variant"
543 data-active={impl === "d1"}
544 aria-hidden={impl !== "d1"}
545 >
546 <FeatureRow
547 icon="logos:cloudflare-icon"
548 label="Cloudflare.D1.Database"
549 sub='"JobsDB" · serverless SQL'
550 delay={240}
551 />
552 <FeatureRow
553 icon="mdi:database-cog"
554 label="D1Connection"
555 sub="bound capability · prepare · exec · batch"
556 delay={340}
557 />
558 </div>
559 </div>
560 </div>
561 </>
562 );
563 }
564
565 /**
566 * Layer-tab code panel. Common lines render statically; each diff segment is
567 * an overlay (CSS grid with both variants in the same grid cell) so only the
568 * active variant is visible while the inactive one fades to opacity 0. The
569 * slot's height is the max of both variants, so the panel stays stable as
570 * the active impl swaps.
571 */
572 function LayerCodeDiff({ impl }: { impl: LayerImpl }) {
573 return (
574 <div className="eff-showcase__diff">
575 {LAYER_SEGMENTS.map((seg, i) => {
576 if (seg.kind === "common") {
577 return (
578 <div key={i} className="eff-diff__common">
579 {seg.lines.map((line, j) => (
580 <CodeLine key={j} text={line} kind="common" />
581 ))}
582 </div>
583 );
584 }
585 return (
586 <div key={i} className="eff-diff__slot">
587 <div
588 className="eff-diff__variant"
589 data-active={impl === "ddb"}
590 aria-hidden={impl !== "ddb"}
591 >
592 {seg.ddb.map((line, j) => (
593 <CodeLine key={j} text={line} kind="ddb" />
594 ))}
595 </div>
596 <div
597 className="eff-diff__variant"
598 data-active={impl === "d1"}
599 aria-hidden={impl !== "d1"}
600 >
601 {seg.d1.map((line, j) => (
602 <CodeLine key={j} text={line} kind="d1" />
603 ))}
604 </div>
605 </div>
606 );
607 })}
608 </div>
609 );
610 }
611
612 function CodeLine({ text, kind }: { text: string; kind: "common" | "ddb" | "d1" }) {
613 const html = highlightTS(text) || "&nbsp;";
614 return (
615 <div className={`eff-diff__line eff-diff__line--${kind}`}>
616 <span className="eff-diff__marker" aria-hidden />
617 <span className="eff-diff__content" dangerouslySetInnerHTML={{ __html: html }} />
618 </div>
619 );
620 }
621
622 /* ───────────────────────── Reusable building blocks ───────────────────────── */
623
624 function FeatureRow({
625 icon,
626 label,
627 sub,
628 delay = 0,
629 }: {
630 icon: string;
631 label: string;
632 sub: string;
633 delay?: number;
634 }) {
635 return (
636 <div className="eff-showcase__feature" style={{ animationDelay: `${delay}ms` }}>
637 <Icon icon={icon} width={22} height={22} aria-hidden className="eff-showcase__feature-icon" />
638 <div className="eff-showcase__feature-text">
639 <div className="eff-showcase__feature-label">{label}</div>
640 <div className="eff-showcase__feature-sub">{sub}</div>
641 </div>
642 </div>
643 );
644 }
645
646 function FlowNode({
647 icon,
648 label,
649 sub,
650 accent,
651 delay = 0,
652 }: {
653 icon: string;
654 label: string;
655 sub: string;
656 accent?: boolean;
657 delay?: number;
658 }) {
659 return (
660 <div
661 className={`eff-showcase__node${accent ? " eff-showcase__node--accent" : ""}`}
662 style={{ animationDelay: `${delay}ms` }}
663 >
664 <Icon icon={icon} width={22} height={22} aria-hidden />
665 <div className="eff-showcase__node-label">{label}</div>
666 <div className="eff-showcase__node-sub">{sub}</div>
667 </div>
668 );
669 }
670
671 function FlowEdge({ label, delay = 0 }: { label: string; delay?: number }) {
672 return (
673 <div
674 className="eff-showcase__edge"
675 data-label={label}
676 style={{ animationDelay: `${delay}ms` }}
677 aria-hidden
678 />
679 );
680 }