@vercel/geistdocs 1.4.1 → 1.5.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/dist/cli/index.js CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
2
  import{program as T}from"commander";import{access as ce,copyFile as le}from"fs/promises";import{join as pe}from"path";import{cancel as de,intro as ge,isCancel as ue,log as fe,outro as me,spinner as he,text as we}from"@clack/prompts";import{spawn as te}from"child_process";import{readFileSync as se}from"fs";import{cp as ne,readFile as ae,rename as re,writeFile as ie}from"fs/promises";import{join as $}from"path";import{fileURLToPath as oe}from"url";var g="@vercel/geistdocs",m=(e,t=[],s={})=>new Promise((n,a)=>{let r=te(e,t,{stdio:"inherit",...s});r.on("error",a),r.on("close",i=>{if(i===0){n();return}a(new Error(`Command failed with exit code ${i}: ${[e,...t].join(" ")}`))})}),A=["dependencies","devDependencies","optionalDependencies","peerDependencies"],_=()=>JSON.parse(se(new URL("../../package.json",import.meta.url),"utf8")).version,P=async e=>{let t=$(e,"package.json"),s=await ae(t,"utf8");return JSON.parse(s)},x=async(e,t)=>{let s=$(e,"package.json");await ie(s,`${JSON.stringify(t,null,2)}
3
- `,"utf8")},R=(e,t)=>{for(let s of A){let n=e[s];if(n&&t in n)return n[t]}},V=(e,t)=>!!R(e,t),b=(e,t,s)=>{let n=!1;for(let a of A){let r=e[a];r&&t in r&&(r[t]=s,n=!0)}return n},j=()=>oe(new URL("../../template",import.meta.url)),F=async e=>{await ne(j(),e,{recursive:!0});let t=$(e,".gitignore"),s=$(e,"_gitignore");try{await re(s,t)}catch{}};var ye=async e=>{await F(e)},Pe=async e=>{try{return await ce(e),!0}catch{return!1}},ve=async()=>{await Pe(".env.example")&&await le(".env.example",".env.local")},Te=async e=>{let t=await P(e),s=_();return b(t,g,s)?(await x(e,t),!0):!1},ke=async e=>{await m("pnpm",["install"],{cwd:e,env:process.env,stdio:"inherit"})},$e=async e=>{await m("git",["init"],{cwd:e,env:process.env,stdio:"inherit"}),await m("git",["add","."],{cwd:e,env:process.env,stdio:"inherit"}),await m("git",["commit","-m","\u2728 Initial commit"],{cwd:e,env:process.env,stdio:"inherit"})},xe=async()=>{let e=await we({message:"What is your project named?",placeholder:"my-app",validate(t){if(t.length===0)return"Please enter a project name."}});return ue(e)&&(de("Operation cancelled."),process.exit(0)),e.toString()},G=async e=>{try{ge("Let's start a Geistdocs project!");let t=process.cwd(),s=e.name||await xe(),n=he(),a=pe(t,s);n.start("Copying bundled template..."),await ye(s),n.message("Setting up environment variables..."),process.chdir(a),await ve(),n.message("Rewriting package dependency versions..."),await Te(a),n.message("Installing dependencies..."),await ke(a),e.disableGit||(n.message("Initializing Git repository..."),await $e(a)),n.stop("Project initialized successfully!"),me("Run `pnpm dev` to start the development server.")}catch(t){let s=t instanceof Error?t.message:`Failed to initialize project: ${t}`;fe.error(s),process.exit(1)}};import{readFileSync as be,writeFileSync as Fe}from"fs";import{mkdir as De,readFile as N,writeFile as Se}from"fs/promises";import{dirname as Ce,extname as Re,relative as M,resolve as S}from"path";import{intro as je,isCancel as Ee,log as h,multiselect as Ne,outro as D,spinner as Ue}from"@clack/prompts";import{glob as Oe}from"glob";import{Node as v,Project as Ie,SyntaxKind as Je}from"ts-morph";var Le="geistdocs.tsx",Ae="content/docs/**/*.mdx",U=".translation-cache.json",E=8,B=()=>({version:1,entries:{}}),_e=async e=>{let t=await N(e),{createHash:s}=await import("crypto");return s("sha256").update(t).digest("hex")},Ve=e=>{let t=S(process.cwd(),e);return be(t,"utf8")},z=e=>v.isObjectLiteralExpression(e)?e.getProperties().flatMap(t=>{if(v.isPropertyAssignment(t)){let s=t.getNameNode();if(v.isIdentifier(s)||v.isStringLiteral(s))return[s.getText().replaceAll(/['"]/g,"")]}return[]}).filter(Boolean):[],Ge=e=>{try{let t=new Ie({compilerOptions:{allowJs:!0,jsx:4,module:99,target:10},skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!0}),s=Ve(e),r=t.createSourceFile(e,s,{overwrite:!0}).getVariableDeclarations().find(l=>l.getName()==="translations")?.getInitializer();if(!r)return[];if(v.isObjectLiteralExpression(r))return z(r);let i=r.getFirstDescendantByKind(Je.ObjectLiteralExpression);return i?z(i):[]}catch(t){let s=t instanceof Error?t.message:`${t}`;return h.warn(`Failed to read locales from ${e}: ${s}`),[]}},Be=async()=>{let e=await Ne({message:"Which locales should be translated?",options:[{value:"cn",label:"Chinese (cn)"},{value:"jp",label:"Japanese (jp)"},{value:"es",label:"Spanish (es)"},{value:"fr",label:"French (fr)"},{value:"de",label:"German (de)"}],required:!0});return Ee(e)&&(D("Translation cancelled"),process.exit(0)),e},ze=async e=>(await Oe(e,{cwd:process.cwd(),absolute:!0,nodir:!0})).sort(),He=async()=>{let e=S(process.cwd(),U);try{let t=await N(e,"utf8"),s=JSON.parse(t);return s.version!==1||!s.entries?B():{version:1,entries:s.entries}}catch{return B()}},H=e=>{let t=S(process.cwd(),U),s=JSON.stringify(e,null,2);Fe(t,s,"utf8")},Me=async e=>{let t=await Promise.all(e.map(async s=>[s,await _e(s)]));return Object.fromEntries(t)},Ke=(e,t)=>{let s=Re(e);return`${e.slice(0,-s.length)}.${t}${s}`},K=(e,t)=>`${M(process.cwd(),e)}::${t}`,qe=(e,t,s,n,a=!1)=>{let r=[],i=0;for(let l of t){let c=s[l];for(let o of e){let d=Ke(l,o),u=K(l,o),f=n.entries[u];if(!a&&f?.hash===c){i+=1;continue}r.push({locale:o,sourceFile:l,sourceHash:c,targetFile:d})}}return{tasks:r,skippedCount:i}},Xe=async e=>{await De(Ce(e),{recursive:!0})},We=async(e,t,s)=>{let n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:t,locale:s})});if(!n.ok){let r=await n.text();throw new Error(`API request failed (${n.status}): ${r}`)}let a=await n.json();if(!a.translation)throw new Error("API response did not include a translation");return a.translation},Ye=async(e,t,s)=>{let n=await N(e.sourceFile,"utf8"),a=await We(t,n,e.locale);await Xe(e.targetFile),await Se(e.targetFile,a,"utf8"),s.entries[K(e.sourceFile,e.locale)]={hash:e.sourceHash,updatedAt:new Date().toISOString()}},q=async(e,t)=>{je("Translate MDX content");let s=e??Ae,n=t.url||process.env.GEISTDOCS_TRANSLATE_URL||"https://geistdocs.com/translate",a=Ge(t.config??Le),r=await ze(s);r.length===0&&(h.error(`No MDX files found matching pattern: ${s}`),D("Translation cancelled"),process.exit(1)),h.info(`Found ${r.length} MDX file(s) matching pattern`),a.length===0&&(a=await Be());let i=S(process.cwd(),U),l=await He();await H(l),h.info(`Using cache: ${i}`);let c=await Me(r),{tasks:o,skippedCount:d}=qe(a,r,c,l,t.force);if(o.length===0){h.success("All translations are up to date!"),D(`Skipped ${d} file(s) (unchanged)`);return}let u=[];for(let y=0;y<o.length;y+=E)u.push(o.slice(y,y+E));h.info(`Processing ${o.length} translation(s) in ${u.length} batch(es) of up to ${E}`),d>0&&h.info(`Skipped ${d} translation(s) (unchanged)`);let f=Ue();f.start("Translating content...");let k=0;for(let y of u)await Promise.all(y.map(async L=>{await Ye(L,n,l),k+=1,f.message(`Translated ${k}/${o.length}: ${M(process.cwd(),L.targetFile)}`)})),await H(l);f.stop("Translation complete!"),D(`Created/updated ${o.length} file(s)`)};import{access as Ze,copyFile as Qe,mkdir as Z,rm as J}from"fs/promises";import{dirname as et,join as w}from"path";import{intro as tt,log as p,outro as C,spinner as Q}from"@clack/prompts";import{glob as st}from"glob";var nt=["**/*"],at=["content/docs/**"],O=".geistdocs-tmp",rt=async(e,t)=>{let s=w(e,t);await J(s,{recursive:!0,force:!0}),await Z(s,{recursive:!0})},I=async e=>await J(e,{recursive:!0,force:!0}),X=async(e,t,s)=>(await st(e,{cwd:s,nodir:!0,dot:!0,ignore:[".git/**",...t]})).sort(),it=async e=>{try{return await Ze(e),!0}catch{return!1}},ot=async(e,t,s)=>{let n=w(t,e),a=w(s,e);return await it(n)?(await Qe(n,a),{success:!0}):{success:!1,error:`Source file not found: ${n}`}},ct=async(e,t)=>{let s=w(t,e);return await J(s,{force:!0}),{success:!0}},W=20,Y=async(e,t,s)=>{let n=[];for(let a=0;a<e.length;a+=s){let r=e.slice(a,a+s),i=await Promise.all(r.map(t));n.push(...i)}return n},lt=async(e,t,s,n,a)=>{let r={success:[],deleted:[],failed:[]},i=[...new Set(e.map(c=>et(w(n,c))))];a.message(`Creating ${i.length} directories...`),await Promise.all(i.map(c=>Z(c,{recursive:!0}))),a.message(`Updating ${e.length} files...`);let l=await Y(e,async c=>{let o=await ot(c,s,n);return{file:c,...o}},W);for(let{file:c,success:o,error:d}of l)o?r.success.push(c):r.failed.push({file:c,error:d??"Unknown error"});if(t.length>0){a.message(`Deleting ${t.length} files...`);let c=await Y(t,async o=>{try{return await ct(o,n),{file:o,success:!0}}catch(d){let u=d instanceof Error?d.message:`${d}`;return{file:o,success:!1,error:u}}},W);for(let o of c)o.success?r.deleted.push(o.file):r.failed.push({file:o.file,error:o.error})}return r},pt=e=>{if(e.success.length>0){p.success(`Successfully updated ${e.success.length} files:`);for(let t of e.success)p.info(` \u2713 ${t}`)}if(e.deleted.length>0){p.success(`Deleted ${e.deleted.length} files:`);for(let t of e.deleted)p.info(` \u{1F5D1} ${t}`)}if(e.failed.length>0){p.warn(`Failed to update ${e.failed.length} files:`);for(let{file:t,error:s}of e.failed)p.error(` \u2717 ${t}: ${s}`)}},dt=e=>e.includes("canary")?"canary":"latest",gt=async e=>{let t=await fetch(`https://registry.npmjs.org/${encodeURIComponent(g)}`);if(!t.ok)throw new Error(`Failed to resolve ${g}@${e}`);let n=(await t.json())["dist-tags"]?.[e];if(!n)throw new Error(`Could not find dist-tag ${e} for ${g}`);return n},ut=async e=>{let t=await P(e),s=R(t,g);if(!s)return{currentVersion:s,nextVersion:void 0,updated:!1};let n=dt(s),a=await gt(n);return s===a?{currentVersion:s,nextVersion:a,updateTag:n,updated:!1}:(b(t,g,a),await x(e,t),{currentVersion:s,nextVersion:a,updateTag:n,updated:!0})},ft=async(e,t,s)=>{let n=await P(e);if(!V(n,g))return!1;t&&t.length>0&&p.warn("Ignoring file patterns for a package-based site. This update will bump the package version instead."),s?.sync&&p.warn("Ignoring --sync for a package-based site. Runtime updates now come from the package version.");let{currentVersion:a,nextVersion:r,updateTag:i,updated:l}=await ut(e);if(!l)return p.success(a?`@vercel/geistdocs is already at ${r} (${i}).`:"No package version update was needed."),C("Package-based site is already up to date."),!0;p.info(`Bumping ${g} from ${a} to ${r} (${i})`);let c=Q();return c.start("Installing updated package version..."),await m("pnpm",["install"],{cwd:e}),c.stop("Package update complete!"),C("Please review and test the upgraded package version."),!0},mt=async(e,t,s,n,a)=>{let r=w(e,O),i=Q(),l=a?.sync?r:t;i.start("Preparing template snapshot..."),a?.sync&&(await rt(e,O),await F(r)),i.message("Scanning for files...");let c=await X(s,n,l),o=[];if(a?.sync){i.message("Comparing with local files...");let u=await X(s,n,e),f=new Set(c);o=u.filter(k=>!f.has(k))}if(i.stop(`Found ${c.length} files to update`),c.length===0&&o.length===0){p.warn("No files matched the patterns. Nothing to update."),a?.sync&&await I(r),C("Update cancelled.");return}p.info(`Patterns: ${s.length}`),p.info(`Files to update: ${c.length}`),a?.sync&&p.info(`Files to delete: ${o.length}`),i.start("Updating files...");let d=await lt(c,o,l,e,i);a?.sync&&(i.message("Cleaning up..."),await I(r)),i.stop("Update complete!"),pt(d),C("Please review and test the changes carefully.")},ee=async(e,t)=>{let s=process.cwd(),n=j(),a=e&&e.length>0?e:nt,r=e&&e.length>0?[]:at;try{if(tt("Let's update your Geistdocs project!"),await ft(s,e,t))return;p.info("Template source: bundled package snapshot"),e&&e.length>0&&p.info(`Updating specific files: ${e.join(", ")}`),t?.sync&&p.info("Sync mode enabled: will delete files removed from template"),await mt(s,n,a,r,t)}catch(i){let l=i instanceof Error?i.message:`${i}`;try{await I(w(s,O))}catch{}p.error(`Failed to update project: ${l}`),process.exit(1)}};T.name("geistdocs").description("CLI for Geistdocs projects").version("1.4.1","-v, --version","Output the current version");T.command("init").description("Initialize a new Geistdocs project").option("--name <name>","Name of the project").option("--disable-git","Disable git initialization").action(G);T.command("update [files...]").description("Update a Geistdocs project (optionally specify files/patterns to update)").option("--sync","Delete local files that no longer exist in the template").action(ee);T.command("translate [pattern]").description("Translate MDX file(s) to one or more locales (default: content/docs/**/*.mdx)").option("--config <path>","Path to config file to load locales from (defaults to geistdocs.tsx)").option("--url <url>","Custom translation API URL (defaults to GEISTDOCS_TRANSLATE_URL or https://geistdocs.com/translate)").option("--force","Force re-translation of all files, ignoring cache").action(q);T.parse(process.argv);
3
+ `,"utf8")},R=(e,t)=>{for(let s of A){let n=e[s];if(n&&t in n)return n[t]}},V=(e,t)=>!!R(e,t),b=(e,t,s)=>{let n=!1;for(let a of A){let r=e[a];r&&t in r&&(r[t]=s,n=!0)}return n},j=()=>oe(new URL("../../template",import.meta.url)),F=async e=>{await ne(j(),e,{recursive:!0});let t=$(e,".gitignore"),s=$(e,"_gitignore");try{await re(s,t)}catch{}};var ye=async e=>{await F(e)},Pe=async e=>{try{return await ce(e),!0}catch{return!1}},ve=async()=>{await Pe(".env.example")&&await le(".env.example",".env.local")},Te=async e=>{let t=await P(e),s=_();return b(t,g,s)?(await x(e,t),!0):!1},ke=async e=>{await m("pnpm",["install"],{cwd:e,env:process.env,stdio:"inherit"})},$e=async e=>{await m("git",["init"],{cwd:e,env:process.env,stdio:"inherit"}),await m("git",["add","."],{cwd:e,env:process.env,stdio:"inherit"}),await m("git",["commit","-m","\u2728 Initial commit"],{cwd:e,env:process.env,stdio:"inherit"})},xe=async()=>{let e=await we({message:"What is your project named?",placeholder:"my-app",validate(t){if(t.length===0)return"Please enter a project name."}});return ue(e)&&(de("Operation cancelled."),process.exit(0)),e.toString()},G=async e=>{try{ge("Let's start a Geistdocs project!");let t=process.cwd(),s=e.name||await xe(),n=he(),a=pe(t,s);n.start("Copying bundled template..."),await ye(s),n.message("Setting up environment variables..."),process.chdir(a),await ve(),n.message("Rewriting package dependency versions..."),await Te(a),n.message("Installing dependencies..."),await ke(a),e.disableGit||(n.message("Initializing Git repository..."),await $e(a)),n.stop("Project initialized successfully!"),me("Run `pnpm dev` to start the development server.")}catch(t){let s=t instanceof Error?t.message:`Failed to initialize project: ${t}`;fe.error(s),process.exit(1)}};import{readFileSync as be,writeFileSync as Fe}from"fs";import{mkdir as De,readFile as N,writeFile as Se}from"fs/promises";import{dirname as Ce,extname as Re,relative as M,resolve as S}from"path";import{intro as je,isCancel as Ee,log as h,multiselect as Ne,outro as D,spinner as Ue}from"@clack/prompts";import{glob as Oe}from"glob";import{Node as v,Project as Ie,SyntaxKind as Je}from"ts-morph";var Le="geistdocs.tsx",Ae="content/docs/**/*.mdx",U=".translation-cache.json",E=8,B=()=>({version:1,entries:{}}),_e=async e=>{let t=await N(e),{createHash:s}=await import("crypto");return s("sha256").update(t).digest("hex")},Ve=e=>{let t=S(process.cwd(),e);return be(t,"utf8")},z=e=>v.isObjectLiteralExpression(e)?e.getProperties().flatMap(t=>{if(v.isPropertyAssignment(t)){let s=t.getNameNode();if(v.isIdentifier(s)||v.isStringLiteral(s))return[s.getText().replaceAll(/['"]/g,"")]}return[]}).filter(Boolean):[],Ge=e=>{try{let t=new Ie({compilerOptions:{allowJs:!0,jsx:4,module:99,target:10},skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!0}),s=Ve(e),r=t.createSourceFile(e,s,{overwrite:!0}).getVariableDeclarations().find(l=>l.getName()==="translations")?.getInitializer();if(!r)return[];if(v.isObjectLiteralExpression(r))return z(r);let i=r.getFirstDescendantByKind(Je.ObjectLiteralExpression);return i?z(i):[]}catch(t){let s=t instanceof Error?t.message:`${t}`;return h.warn(`Failed to read locales from ${e}: ${s}`),[]}},Be=async()=>{let e=await Ne({message:"Which locales should be translated?",options:[{value:"cn",label:"Chinese (cn)"},{value:"jp",label:"Japanese (jp)"},{value:"es",label:"Spanish (es)"},{value:"fr",label:"French (fr)"},{value:"de",label:"German (de)"}],required:!0});return Ee(e)&&(D("Translation cancelled"),process.exit(0)),e},ze=async e=>(await Oe(e,{cwd:process.cwd(),absolute:!0,nodir:!0})).sort(),He=async()=>{let e=S(process.cwd(),U);try{let t=await N(e,"utf8"),s=JSON.parse(t);return s.version!==1||!s.entries?B():{version:1,entries:s.entries}}catch{return B()}},H=e=>{let t=S(process.cwd(),U),s=JSON.stringify(e,null,2);Fe(t,s,"utf8")},Me=async e=>{let t=await Promise.all(e.map(async s=>[s,await _e(s)]));return Object.fromEntries(t)},Ke=(e,t)=>{let s=Re(e);return`${e.slice(0,-s.length)}.${t}${s}`},K=(e,t)=>`${M(process.cwd(),e)}::${t}`,qe=(e,t,s,n,a=!1)=>{let r=[],i=0;for(let l of t){let c=s[l];for(let o of e){let d=Ke(l,o),u=K(l,o),f=n.entries[u];if(!a&&f?.hash===c){i+=1;continue}r.push({locale:o,sourceFile:l,sourceHash:c,targetFile:d})}}return{tasks:r,skippedCount:i}},Xe=async e=>{await De(Ce(e),{recursive:!0})},We=async(e,t,s)=>{let n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:t,locale:s})});if(!n.ok){let r=await n.text();throw new Error(`API request failed (${n.status}): ${r}`)}let a=await n.json();if(!a.translation)throw new Error("API response did not include a translation");return a.translation},Ye=async(e,t,s)=>{let n=await N(e.sourceFile,"utf8"),a=await We(t,n,e.locale);await Xe(e.targetFile),await Se(e.targetFile,a,"utf8"),s.entries[K(e.sourceFile,e.locale)]={hash:e.sourceHash,updatedAt:new Date().toISOString()}},q=async(e,t)=>{je("Translate MDX content");let s=e??Ae,n=t.url||process.env.GEISTDOCS_TRANSLATE_URL||"https://geistdocs.com/translate",a=Ge(t.config??Le),r=await ze(s);r.length===0&&(h.error(`No MDX files found matching pattern: ${s}`),D("Translation cancelled"),process.exit(1)),h.info(`Found ${r.length} MDX file(s) matching pattern`),a.length===0&&(a=await Be());let i=S(process.cwd(),U),l=await He();await H(l),h.info(`Using cache: ${i}`);let c=await Me(r),{tasks:o,skippedCount:d}=qe(a,r,c,l,t.force);if(o.length===0){h.success("All translations are up to date!"),D(`Skipped ${d} file(s) (unchanged)`);return}let u=[];for(let y=0;y<o.length;y+=E)u.push(o.slice(y,y+E));h.info(`Processing ${o.length} translation(s) in ${u.length} batch(es) of up to ${E}`),d>0&&h.info(`Skipped ${d} translation(s) (unchanged)`);let f=Ue();f.start("Translating content...");let k=0;for(let y of u)await Promise.all(y.map(async L=>{await Ye(L,n,l),k+=1,f.message(`Translated ${k}/${o.length}: ${M(process.cwd(),L.targetFile)}`)})),await H(l);f.stop("Translation complete!"),D(`Created/updated ${o.length} file(s)`)};import{access as Ze,copyFile as Qe,mkdir as Z,rm as J}from"fs/promises";import{dirname as et,join as w}from"path";import{intro as tt,log as p,outro as C,spinner as Q}from"@clack/prompts";import{glob as st}from"glob";var nt=["**/*"],at=["content/docs/**"],O=".geistdocs-tmp",rt=async(e,t)=>{let s=w(e,t);await J(s,{recursive:!0,force:!0}),await Z(s,{recursive:!0})},I=async e=>await J(e,{recursive:!0,force:!0}),X=async(e,t,s)=>(await st(e,{cwd:s,nodir:!0,dot:!0,ignore:[".git/**",...t]})).sort(),it=async e=>{try{return await Ze(e),!0}catch{return!1}},ot=async(e,t,s)=>{let n=w(t,e),a=w(s,e);return await it(n)?(await Qe(n,a),{success:!0}):{success:!1,error:`Source file not found: ${n}`}},ct=async(e,t)=>{let s=w(t,e);return await J(s,{force:!0}),{success:!0}},W=20,Y=async(e,t,s)=>{let n=[];for(let a=0;a<e.length;a+=s){let r=e.slice(a,a+s),i=await Promise.all(r.map(t));n.push(...i)}return n},lt=async(e,t,s,n,a)=>{let r={success:[],deleted:[],failed:[]},i=[...new Set(e.map(c=>et(w(n,c))))];a.message(`Creating ${i.length} directories...`),await Promise.all(i.map(c=>Z(c,{recursive:!0}))),a.message(`Updating ${e.length} files...`);let l=await Y(e,async c=>{let o=await ot(c,s,n);return{file:c,...o}},W);for(let{file:c,success:o,error:d}of l)o?r.success.push(c):r.failed.push({file:c,error:d??"Unknown error"});if(t.length>0){a.message(`Deleting ${t.length} files...`);let c=await Y(t,async o=>{try{return await ct(o,n),{file:o,success:!0}}catch(d){let u=d instanceof Error?d.message:`${d}`;return{file:o,success:!1,error:u}}},W);for(let o of c)o.success?r.deleted.push(o.file):r.failed.push({file:o.file,error:o.error})}return r},pt=e=>{if(e.success.length>0){p.success(`Successfully updated ${e.success.length} files:`);for(let t of e.success)p.info(` \u2713 ${t}`)}if(e.deleted.length>0){p.success(`Deleted ${e.deleted.length} files:`);for(let t of e.deleted)p.info(` \u{1F5D1} ${t}`)}if(e.failed.length>0){p.warn(`Failed to update ${e.failed.length} files:`);for(let{file:t,error:s}of e.failed)p.error(` \u2717 ${t}: ${s}`)}},dt=e=>e.includes("canary")?"canary":"latest",gt=async e=>{let t=await fetch(`https://registry.npmjs.org/${encodeURIComponent(g)}`);if(!t.ok)throw new Error(`Failed to resolve ${g}@${e}`);let n=(await t.json())["dist-tags"]?.[e];if(!n)throw new Error(`Could not find dist-tag ${e} for ${g}`);return n},ut=async e=>{let t=await P(e),s=R(t,g);if(!s)return{currentVersion:s,nextVersion:void 0,updated:!1};let n=dt(s),a=await gt(n);return s===a?{currentVersion:s,nextVersion:a,updateTag:n,updated:!1}:(b(t,g,a),await x(e,t),{currentVersion:s,nextVersion:a,updateTag:n,updated:!0})},ft=async(e,t,s)=>{let n=await P(e);if(!V(n,g))return!1;t&&t.length>0&&p.warn("Ignoring file patterns for a package-based site. This update will bump the package version instead."),s?.sync&&p.warn("Ignoring --sync for a package-based site. Runtime updates now come from the package version.");let{currentVersion:a,nextVersion:r,updateTag:i,updated:l}=await ut(e);if(!l)return p.success(a?`@vercel/geistdocs is already at ${r} (${i}).`:"No package version update was needed."),C("Package-based site is already up to date."),!0;p.info(`Bumping ${g} from ${a} to ${r} (${i})`);let c=Q();return c.start("Installing updated package version..."),await m("pnpm",["install"],{cwd:e}),c.stop("Package update complete!"),C("Please review and test the upgraded package version."),!0},mt=async(e,t,s,n,a)=>{let r=w(e,O),i=Q(),l=a?.sync?r:t;i.start("Preparing template snapshot..."),a?.sync&&(await rt(e,O),await F(r)),i.message("Scanning for files...");let c=await X(s,n,l),o=[];if(a?.sync){i.message("Comparing with local files...");let u=await X(s,n,e),f=new Set(c);o=u.filter(k=>!f.has(k))}if(i.stop(`Found ${c.length} files to update`),c.length===0&&o.length===0){p.warn("No files matched the patterns. Nothing to update."),a?.sync&&await I(r),C("Update cancelled.");return}p.info(`Patterns: ${s.length}`),p.info(`Files to update: ${c.length}`),a?.sync&&p.info(`Files to delete: ${o.length}`),i.start("Updating files...");let d=await lt(c,o,l,e,i);a?.sync&&(i.message("Cleaning up..."),await I(r)),i.stop("Update complete!"),pt(d),C("Please review and test the changes carefully.")},ee=async(e,t)=>{let s=process.cwd(),n=j(),a=e&&e.length>0?e:nt,r=e&&e.length>0?[]:at;try{if(tt("Let's update your Geistdocs project!"),await ft(s,e,t))return;p.info("Template source: bundled package snapshot"),e&&e.length>0&&p.info(`Updating specific files: ${e.join(", ")}`),t?.sync&&p.info("Sync mode enabled: will delete files removed from template"),await mt(s,n,a,r,t)}catch(i){let l=i instanceof Error?i.message:`${i}`;try{await I(w(s,O))}catch{}p.error(`Failed to update project: ${l}`),process.exit(1)}};T.name("geistdocs").description("CLI for Geistdocs projects").version("1.5.0","-v, --version","Output the current version");T.command("init").description("Initialize a new Geistdocs project").option("--name <name>","Name of the project").option("--disable-git","Disable git initialization").action(G);T.command("update [files...]").description("Update a Geistdocs project (optionally specify files/patterns to update)").option("--sync","Delete local files that no longer exist in the template").action(ee);T.command("translate [pattern]").description("Translate MDX file(s) to one or more locales (default: content/docs/**/*.mdx)").option("--config <path>","Path to config file to load locales from (defaults to geistdocs.tsx)").option("--url <url>","Custom translation API URL (defaults to GEISTDOCS_TRANSLATE_URL or https://geistdocs.com/translate)").option("--force","Force re-translation of all files, ignoring cache").action(q);T.parse(process.argv);
@@ -0,0 +1,11 @@
1
+ import { type VariantProps } from "class-variance-authority";
2
+ import type { ComponentProps } from "react";
3
+ declare const badgeVariants: (props?: ({
4
+ variant?: "default" | "destructive" | "outline" | "secondary" | null | undefined;
5
+ } & import("class-variance-authority/types").ClassProp) | undefined) => string;
6
+ type BadgeProps = ComponentProps<"span"> & VariantProps<typeof badgeVariants> & {
7
+ asChild?: boolean;
8
+ };
9
+ export declare function Badge({ className, variant, asChild, ...props }: BadgeProps): import("react/jsx-runtime").JSX.Element;
10
+ export { badgeVariants };
11
+ //# sourceMappingURL=badge.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"badge.d.ts","sourceRoot":"","sources":["../../src/components/badge.tsx"],"names":[],"mappings":"AAAA,OAAO,EAAO,KAAK,YAAY,EAAE,MAAM,0BAA0B,CAAC;AAElE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,OAAO,CAAC;AAG5C,QAAA,MAAM,aAAa;;8EAmBlB,CAAC;AAEF,KAAK,UAAU,GAAG,cAAc,CAAC,MAAM,CAAC,GACtC,YAAY,CAAC,OAAO,aAAa,CAAC,GAAG;IACnC,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB,CAAC;AAEJ,wBAAgB,KAAK,CAAC,EACpB,SAAS,EACT,OAAO,EACP,OAAe,EACf,GAAG,KAAK,EACT,EAAE,UAAU,2CAUZ;AAED,OAAO,EAAE,aAAa,EAAE,CAAC"}
@@ -0,0 +1,22 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { cva } from "class-variance-authority";
3
+ import { Slot as SlotPrimitive } from "radix-ui";
4
+ import { cn } from "../internal/cn";
5
+ const badgeVariants = cva("inline-flex w-fit shrink-0 items-center justify-center gap-1 overflow-hidden whitespace-nowrap rounded-full border px-2 py-0.5 font-medium text-xs transition-[color,box-shadow] focus-visible:border-gray-600 focus-visible:ring-[3px] focus-visible:ring-gray-600/50 aria-invalid:border-red-800 aria-invalid:ring-red-800/20 dark:aria-invalid:ring-red-800/40 [&>svg]:pointer-events-none [&>svg]:size-3", {
6
+ variants: {
7
+ variant: {
8
+ default: "border-transparent bg-gray-1000 text-background-100 [a&]:hover:bg-gray-1000/90",
9
+ secondary: "border-transparent bg-gray-alpha-400 text-gray-1000 [a&]:hover:bg-gray-alpha-400/90",
10
+ destructive: "border-transparent bg-red-800 text-white focus-visible:ring-red-800/20 dark:bg-red-800/60 dark:focus-visible:ring-red-800/40 [a&]:hover:bg-red-800/90",
11
+ outline: "text-gray-1000 [a&]:hover:bg-gray-100 [a&]:hover:text-gray-1000",
12
+ },
13
+ },
14
+ defaultVariants: {
15
+ variant: "default",
16
+ },
17
+ });
18
+ export function Badge({ className, variant, asChild = false, ...props }) {
19
+ const Comp = asChild ? SlotPrimitive.Slot : "span";
20
+ return (_jsx(Comp, { className: cn(badgeVariants({ variant }), className), "data-slot": "badge", ...props }));
21
+ }
22
+ export { badgeVariants };
@@ -31,7 +31,7 @@ export const CodeBlock = ({ children, className, icon, style, tabIndex, title, .
31
31
  }
32
32
  }, []);
33
33
  const Icon = isCopied ? CheckIcon : CopyIcon;
34
- const CodeBlockComponent = useCallback((props) => (_jsx("pre", { className: cn("not-prose flex-1 overflow-x-auto rounded-sm border bg-background-100 py-3 text-sm outline-none", "[&>code]:grid [&>code]:min-w-max", className, props.className), ref: ref, style: {
34
+ const CodeBlockComponent = useCallback((props) => (_jsx("pre", { className: cn("not-prose flex-1 overflow-x-auto rounded-md border bg-background-100 py-3 text-[13px]/5 outline-none", "[&>code]:grid [&>code]:min-w-max", className, props.className), ref: ref, style: {
35
35
  fontFeatureSettings: '"liga" 0, "calt" 0',
36
36
  fontVariantLigatures: "none",
37
37
  ...style,
@@ -39,7 +39,7 @@ export const CodeBlock = ({ children, className, icon, style, tabIndex, title, .
39
39
  if (!title) {
40
40
  return (_jsxs("div", { className: "relative mb-6", children: [_jsx(CodeBlockComponent, { className: cn(lineNumbers ? "line-numbers" : "", className) }), _jsx(Button, { className: "absolute top-[5px] right-[5px] bg-background-100/80 backdrop-blur-sm", onClick: copyToClipboard, size: "icon", variant: "ghost", children: _jsx(Icon, { size: 14 }) })] }));
41
41
  }
42
- return (_jsxs(Card, { className: "not-prose mb-6 gap-0 overflow-hidden rounded-sm p-0 shadow-none", children: [_jsxs(CardHeader, { className: "flex items-center gap-2 border-b bg-background-200 py-1.5! pr-1.5 pl-4 text-gray-800", children: [_jsx("div", { className: "flex size-3.5 shrink-0",
42
+ return (_jsxs(Card, { className: "not-prose mb-6 gap-0 overflow-hidden rounded-md p-0 shadow-none", children: [_jsxs(CardHeader, { className: "flex items-center gap-2 border-b bg-background-200 py-1.5! pr-1.5 pl-4 text-gray-800", children: [_jsx("div", { className: "flex size-3.5 shrink-0",
43
43
  // biome-ignore lint/security/noDangerouslySetInnerHtml: icon markup comes from code fence metadata.
44
44
  dangerouslySetInnerHTML: { __html: icon } }), _jsx(CardTitle, { className: "flex-1 font-mono font-normal text-sm tracking-tight", children: title }), _jsx(Button, { className: cn("shrink-0", className), onClick: copyToClipboard, size: "icon", variant: "ghost", children: _jsx(Icon, { size: 14 }) })] }), _jsx(CardContent, { className: "p-0", children: _jsx(CodeBlockComponent, { className: cn(className, "rounded-none border-none", lineNumbers ? "line-numbers" : "") }) })] }));
45
45
  };
@@ -0,0 +1,33 @@
1
+ import { type ComponentPropsWithoutRef, type JSX, type ReactNode } from "react";
2
+ type CommandPromptRootProps = Omit<ComponentPropsWithoutRef<"div">, "onChange"> & {
3
+ value?: string;
4
+ defaultValue?: string;
5
+ onValueChange?: (value: string) => void;
6
+ };
7
+ export declare function CommandPromptRoot({ value: valueProp, defaultValue, onValueChange, className, children, ...props }: CommandPromptRootProps): JSX.Element;
8
+ export declare function CommandPromptList({ className, ...props }: ComponentPropsWithoutRef<"div">): JSX.Element;
9
+ type CommandPromptTriggerProps = ComponentPropsWithoutRef<"button"> & {
10
+ value: string;
11
+ };
12
+ export declare function CommandPromptTrigger({ value, className, onClick, children, ...props }: CommandPromptTriggerProps): JSX.Element;
13
+ export declare function CommandPromptTriggerDivider({ className, ...props }: ComponentPropsWithoutRef<"div">): JSX.Element;
14
+ export declare function CommandPromptSurface({ className, onClick, children, }: {
15
+ className?: string;
16
+ children: ReactNode;
17
+ onClick?: ComponentPropsWithoutRef<"div">["onClick"];
18
+ }): JSX.Element;
19
+ export declare function CommandPromptPrefix({ className, ...props }: ComponentPropsWithoutRef<"span">): JSX.Element;
20
+ interface CommandPromptContentProps {
21
+ children: ReactNode;
22
+ className?: string;
23
+ copyValue?: string;
24
+ value: string;
25
+ }
26
+ export declare function CommandPromptViewport({ className, children, }: {
27
+ className?: string;
28
+ children: ReactNode;
29
+ }): JSX.Element;
30
+ export declare function CommandPromptContent(_props: CommandPromptContentProps): JSX.Element | null;
31
+ export declare function CommandPromptCopy({ className, onClick, ...props }: ComponentPropsWithoutRef<"button">): JSX.Element;
32
+ export {};
33
+ //# sourceMappingURL=command-prompt.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"command-prompt.d.ts","sourceRoot":"","sources":["../../src/components/command-prompt.tsx"],"names":[],"mappings":"AAKA,OAAO,EAEL,KAAK,wBAAwB,EAG7B,KAAK,GAAG,EACR,KAAK,SAAS,EAMf,MAAM,OAAO,CAAC;AAgCf,KAAK,sBAAsB,GAAG,IAAI,CAChC,wBAAwB,CAAC,KAAK,CAAC,EAC/B,UAAU,CACX,GAAG;IACF,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,aAAa,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;CACzC,CAAC;AAEF,wBAAgB,iBAAiB,CAAC,EAChC,KAAK,EAAE,SAAS,EAChB,YAAY,EACZ,aAAa,EACb,SAAS,EACT,QAAQ,EACR,GAAG,KAAK,EACT,EAAE,sBAAsB,GAAG,GAAG,CAAC,OAAO,CA0EtC;AAED,wBAAgB,iBAAiB,CAAC,EAChC,SAAS,EACT,GAAG,KAAK,EACT,EAAE,wBAAwB,CAAC,KAAK,CAAC,GAAG,GAAG,CAAC,OAAO,CAE/C;AAED,KAAK,yBAAyB,GAAG,wBAAwB,CAAC,QAAQ,CAAC,GAAG;IACpE,KAAK,EAAE,MAAM,CAAC;CACf,CAAC;AAEF,wBAAgB,oBAAoB,CAAC,EACnC,KAAK,EACL,SAAS,EACT,OAAO,EACP,QAAQ,EACR,GAAG,KAAK,EACT,EAAE,yBAAyB,GAAG,GAAG,CAAC,OAAO,CA6BzC;AAED,wBAAgB,2BAA2B,CAAC,EAC1C,SAAS,EACT,GAAG,KAAK,EACT,EAAE,wBAAwB,CAAC,KAAK,CAAC,GAAG,GAAG,CAAC,OAAO,CAQ/C;AAED,wBAAgB,oBAAoB,CAAC,EACnC,SAAS,EACT,OAAO,EACP,QAAQ,GACT,EAAE;IACD,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,SAAS,CAAC;IACpB,OAAO,CAAC,EAAE,wBAAwB,CAAC,KAAK,CAAC,CAAC,SAAS,CAAC,CAAC;CACtD,GAAG,GAAG,CAAC,OAAO,CA8Bd;AAED,wBAAgB,mBAAmB,CAAC,EAClC,SAAS,EACT,GAAG,KAAK,EACT,EAAE,wBAAwB,CAAC,MAAM,CAAC,GAAG,GAAG,CAAC,OAAO,CAOhD;AAED,UAAU,yBAAyB;IACjC,QAAQ,EAAE,SAAS,CAAC;IACpB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,KAAK,EAAE,MAAM,CAAC;CACf;AAED,wBAAgB,qBAAqB,CAAC,EACpC,SAAS,EACT,QAAQ,GACT,EAAE;IACD,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,SAAS,CAAC;CACrB,GAAG,GAAG,CAAC,OAAO,CAoJd;AAED,wBAAgB,oBAAoB,CAClC,MAAM,EAAE,yBAAyB,GAChC,GAAG,CAAC,OAAO,GAAG,IAAI,CAEpB;AAED,wBAAgB,iBAAiB,CAAC,EAChC,SAAS,EACT,OAAO,EACP,GAAG,KAAK,EACT,EAAE,wBAAwB,CAAC,QAAQ,CAAC,GAAG,GAAG,CAAC,OAAO,CAsFlD"}
@@ -0,0 +1,217 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { IconCheck } from "@vercel/geistdocs/assets/icons/icon-check";
4
+ import { IconCopy } from "@vercel/geistdocs/assets/icons/icon-copy";
5
+ import { AnimatePresence, motion, useReducedMotion } from "motion/react";
6
+ import { Children, createContext, isValidElement, useContext, useEffect, useLayoutEffect, useRef, useState, } from "react";
7
+ import { cn } from "../internal/cn";
8
+ const CommandPromptContext = createContext(null);
9
+ function useCommandPromptContext(component) {
10
+ const context = useContext(CommandPromptContext);
11
+ if (!context) {
12
+ throw new Error(`${component} must be used within CommandPrompt.Root`);
13
+ }
14
+ return context;
15
+ }
16
+ export function CommandPromptRoot({ value: valueProp, defaultValue, onValueChange, className, children, ...props }) {
17
+ const [uncontrolledValue, setUncontrolledValue] = useState(defaultValue ?? "");
18
+ const [copied, setCopied] = useState(false);
19
+ const [activeCopyValue, setActiveCopyValue] = useState("");
20
+ const [commandWidth, setCommandWidth] = useState();
21
+ const [isOverflowing, setIsOverflowing] = useState(false);
22
+ const [canShowGradient, setCanShowGradient] = useState(true);
23
+ const timeoutRef = useRef(null);
24
+ const value = valueProp ?? uncontrolledValue;
25
+ useEffect(() => {
26
+ return () => {
27
+ if (timeoutRef.current) {
28
+ clearTimeout(timeoutRef.current);
29
+ }
30
+ };
31
+ }, []);
32
+ function resetCopiedState() {
33
+ setCopied(false);
34
+ if (timeoutRef.current) {
35
+ clearTimeout(timeoutRef.current);
36
+ }
37
+ }
38
+ function setValue(nextValue) {
39
+ if (valueProp === undefined) {
40
+ setUncontrolledValue(nextValue);
41
+ }
42
+ resetCopiedState();
43
+ onValueChange?.(nextValue);
44
+ }
45
+ function copyActiveValue() {
46
+ if (!activeCopyValue) {
47
+ return;
48
+ }
49
+ navigator.clipboard.writeText(activeCopyValue);
50
+ setCopied(true);
51
+ if (timeoutRef.current) {
52
+ clearTimeout(timeoutRef.current);
53
+ }
54
+ timeoutRef.current = setTimeout(() => setCopied(false), 1000);
55
+ }
56
+ return (_jsx(CommandPromptContext.Provider, { value: {
57
+ value,
58
+ setValue,
59
+ copied,
60
+ copyActiveValue,
61
+ activeCopyValue,
62
+ setActiveCopyValue,
63
+ commandWidth,
64
+ setCommandWidth,
65
+ isOverflowing,
66
+ setIsOverflowing,
67
+ canShowGradient,
68
+ setCanShowGradient,
69
+ }, children: _jsx("div", { className: cn("flex w-full flex-col items-center gap-2", className), ...props, children: children }) }));
70
+ }
71
+ export function CommandPromptList({ className, ...props }) {
72
+ return _jsx("div", { className: cn("flex items-center", className), ...props });
73
+ }
74
+ export function CommandPromptTrigger({ value, className, onClick, children, ...props }) {
75
+ const context = useCommandPromptContext("CommandPrompt.Trigger");
76
+ const active = context.value === value;
77
+ return (_jsx("button", { "aria-pressed": active, className: cn("cursor-pointer px-3 py-2 text-gray-900 hover:text-gray-1000", "touch-manipulation rounded-sm border-none bg-transparent font-medium! text-label-13!", "outline outline-2 outline-transparent outline-offset-2 focus-visible:outline-[var(--ds-focus-color)]", "text-gray-900 data-[active]:font-medium data-[active]:text-gray-1000", "flex items-center gap-1.5 whitespace-nowrap", className), "data-active": active ? "" : undefined, onClick: (event) => {
78
+ onClick?.(event);
79
+ if (event.defaultPrevented) {
80
+ return;
81
+ }
82
+ context.setValue(value);
83
+ }, type: "button", ...props, children: children }));
84
+ }
85
+ export function CommandPromptTriggerDivider({ className, ...props }) {
86
+ return (_jsx("div", { "aria-hidden": true, className: cn("h-3 w-px bg-gray-400", className), ...props }));
87
+ }
88
+ export function CommandPromptSurface({ className, onClick, children, }) {
89
+ const context = useCommandPromptContext("CommandPrompt.Surface");
90
+ const shouldReduceMotion = useReducedMotion();
91
+ return (_jsx(motion.div, { className: cn("group material-small relative flex max-w-[calc(100vw-48px)] items-center gap-1 rounded-full py-2 pr-3 pl-5 transition-colors", className), layout: true, onClick: (event) => {
92
+ onClick?.(event);
93
+ if (event.defaultPrevented) {
94
+ return;
95
+ }
96
+ if (window.getSelection()?.toString()) {
97
+ return;
98
+ }
99
+ context.copyActiveValue();
100
+ }, transition: shouldReduceMotion
101
+ ? { duration: 0 }
102
+ : { type: "spring", bounce: 0, duration: 0.4 }, children: children }));
103
+ }
104
+ export function CommandPromptPrefix({ className, ...props }) {
105
+ return (_jsx("span", { className: cn("block pr-1 text-gray-500 text-label-16-mono!", className), ...props }));
106
+ }
107
+ export function CommandPromptViewport({ className, children, }) {
108
+ const context = useCommandPromptContext("CommandPrompt.Viewport");
109
+ const shouldReduceMotion = useReducedMotion();
110
+ const { commandWidth, canShowGradient, isOverflowing, setActiveCopyValue, setCanShowGradient, setCommandWidth, setIsOverflowing, } = context;
111
+ const measureRef = useRef(null);
112
+ const scrollObserverCleanup = useRef(null);
113
+ const items = Children.toArray(children)
114
+ .filter((child) => isValidElement(child))
115
+ .map((child) => child.props);
116
+ const activeItem = items.find((item) => item.value === context.value);
117
+ const command = activeItem?.children ?? null;
118
+ const fallbackCopyValue = typeof command === "string" || typeof command === "number"
119
+ ? String(command)
120
+ : Children.toArray(command)
121
+ .filter((child) => typeof child === "string" || typeof child === "number")
122
+ .join("");
123
+ const copyValue = activeItem?.copyValue ?? fallbackCopyValue;
124
+ // biome-ignore lint/correctness/useExhaustiveDependencies: copyValue must reset the overflow/gradient state when the active command changes.
125
+ useLayoutEffect(() => {
126
+ setIsOverflowing(false);
127
+ setCanShowGradient(Boolean(shouldReduceMotion));
128
+ }, [copyValue, setCanShowGradient, setIsOverflowing, shouldReduceMotion]);
129
+ useEffect(() => {
130
+ setActiveCopyValue(copyValue);
131
+ return () => {
132
+ setIsOverflowing(false);
133
+ scrollObserverCleanup.current?.();
134
+ scrollObserverCleanup.current = null;
135
+ };
136
+ }, [copyValue, setActiveCopyValue, setIsOverflowing]);
137
+ // biome-ignore lint/correctness/useExhaustiveDependencies: command/copyValue must re-measure the width to drive the resize animation when the active command changes.
138
+ useLayoutEffect(() => {
139
+ if (!measureRef.current) {
140
+ return;
141
+ }
142
+ setCommandWidth(measureRef.current.getBoundingClientRect().width);
143
+ }, [command, copyValue, setCommandWidth]);
144
+ return (_jsxs(motion.span, { animate: commandWidth === undefined
145
+ ? undefined
146
+ : { width: shouldReduceMotion ? "auto" : commandWidth }, className: cn("relative block min-w-0 overflow-hidden text-gray-1000 text-label-14-mono!", className), initial: false, onAnimationComplete: () => {
147
+ setCanShowGradient(true);
148
+ }, transition: shouldReduceMotion
149
+ ? { duration: 0 }
150
+ : { type: "spring", bounce: 0, duration: 0.4 }, children: [_jsx("span", { "aria-hidden": true, className: "pointer-events-none invisible absolute whitespace-nowrap", ref: measureRef, children: command }), _jsx(AnimatePresence, { initial: false, mode: "wait", children: Children.toArray(children).map((child) => {
151
+ if (!isValidElement(child)) {
152
+ return null;
153
+ }
154
+ if (child.props.value !== context.value) {
155
+ return null;
156
+ }
157
+ return (_jsx(motion.span, { animate: { opacity: 1, filter: "blur(0px)" }, className: cn("block min-w-0 whitespace-nowrap py-2", canShowGradient && isOverflowing
158
+ ? "overflow-x-auto"
159
+ : "overflow-x-hidden", child.props.className), exit: { opacity: 0, filter: "blur(1px)" }, initial: { opacity: 0, filter: "blur(1px)" }, ref: (element) => {
160
+ scrollObserverCleanup.current?.();
161
+ scrollObserverCleanup.current = null;
162
+ if (!element) {
163
+ return;
164
+ }
165
+ const checkOverflow = () => {
166
+ setIsOverflowing(element.scrollWidth > element.clientWidth);
167
+ };
168
+ checkOverflow();
169
+ const observer = new ResizeObserver(checkOverflow);
170
+ observer.observe(element);
171
+ scrollObserverCleanup.current = () => observer.disconnect();
172
+ }, transition: shouldReduceMotion ? { duration: 0 } : { duration: 0.15 }, children: child.props.children }, copyValue));
173
+ }) }), _jsx(AnimatePresence, { children: canShowGradient && isOverflowing && (_jsx(motion.span, { animate: { opacity: 1 }, "aria-hidden": true, className: "pointer-events-none absolute top-0 right-0 bottom-0 z-10 block w-4 bg-gradient-to-r from-transparent to-background-100", exit: { opacity: 0 }, initial: { opacity: 0 }, transition: shouldReduceMotion ? { duration: 0 } : { duration: 0.2 } })) })] }));
174
+ }
175
+ export function CommandPromptContent(_props) {
176
+ return null;
177
+ }
178
+ export function CommandPromptCopy({ className, onClick, ...props }) {
179
+ const context = useCommandPromptContext("CommandPrompt.Copy");
180
+ const shouldReduceMotion = useReducedMotion();
181
+ return (_jsxs("button", { "aria-label": context.copied ? "Copied" : "Copy command", className: cn("relative flex size-8 shrink-0 translate-x-0.5 cursor-pointer items-center justify-center rounded-full border-none bg-transparent text-gray-1000", "hover:!bg-gray-alpha-200 touch-manipulation transition-colors group-hover:bg-gray-alpha-100", "outline-2 outline-transparent outline-offset-2 focus-visible:outline-[var(--ds-focus-color)]", className), onClick: (event) => {
182
+ onClick?.(event);
183
+ if (event.defaultPrevented) {
184
+ return;
185
+ }
186
+ event.stopPropagation();
187
+ context.copyActiveValue();
188
+ }, type: "button", ...props, children: [_jsx(AnimatePresence, { initial: false, children: !context.copied && (_jsx(motion.span, { animate: {
189
+ opacity: 1,
190
+ transform: "scale(1)",
191
+ filter: "blur(0px)",
192
+ }, className: "absolute inset-0 flex items-center justify-center", exit: {
193
+ opacity: 0,
194
+ transform: "scale(0.5)",
195
+ filter: "blur(1px)",
196
+ }, initial: {
197
+ opacity: 0,
198
+ transform: "scale(0.5)",
199
+ filter: "blur(1px)",
200
+ }, transition: shouldReduceMotion
201
+ ? { duration: 0 }
202
+ : { duration: 0.2, ease: [0.23, 1, 0.32, 1] }, children: _jsx(IconCopy, { className: "block", size: 16 }) }, "copy")) }), _jsx(AnimatePresence, { initial: false, children: context.copied && (_jsx(motion.span, { animate: {
203
+ opacity: 1,
204
+ transform: "scale(1)",
205
+ filter: "blur(0px)",
206
+ }, className: "absolute inset-0 flex items-center justify-center", exit: {
207
+ opacity: 0,
208
+ transform: "scale(0.5)",
209
+ filter: "blur(1px)",
210
+ }, initial: {
211
+ opacity: 0,
212
+ transform: "scale(0.5)",
213
+ filter: "blur(1px)",
214
+ }, transition: shouldReduceMotion
215
+ ? { duration: 0 }
216
+ : { duration: 0.2, ease: [0.23, 1, 0.32, 1] }, children: _jsx(IconCheck, { className: "block", size: 16 }) }, "check")) })] }));
217
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"controls.d.ts","sourceRoot":"","sources":["../src/controls.tsx"],"names":[],"mappings":"AAYA,OAAO,EAAE,KAAK,cAAc,EAAuB,MAAM,OAAO,CAAC;AAGjE,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAS9C,UAAU,iBAAiB;IACzB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;CACtB;AAED,eAAO,MAAM,YAAY,GAAI,wBAAwB,iBAAiB,4CAqBrE,CAAC;AAEF,eAAO,MAAM,WAAW,+CA4BvB,CAAC;AAEF,eAAO,MAAM,gBAAgB,sDA+B5B,CAAC;AAEF,KAAK,gBAAgB,GAAG,IAAI,CAAC,cAAc,CAAC,OAAO,MAAM,CAAC,EAAE,SAAS,CAAC,GAAG;IACvE,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,CAAC;AAEF,eAAO,MAAM,WAAW,GAAI,0DAOzB,gBAAgB,mDAgClB,CAAC"}
1
+ {"version":3,"file":"controls.d.ts","sourceRoot":"","sources":["../src/controls.tsx"],"names":[],"mappings":"AAMA,OAAO,EAAE,KAAK,cAAc,EAAuB,MAAM,OAAO,CAAC;AAGjE,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAS9C,UAAU,iBAAiB;IACzB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;CACtB;AAED,eAAO,MAAM,YAAY,GAAI,wBAAwB,iBAAiB,4CAqBrE,CAAC;AAEF,eAAO,MAAM,WAAW,+CA4BvB,CAAC;AAEF,eAAO,MAAM,gBAAgB,sDA+B5B,CAAC;AAEF,KAAK,gBAAgB,GAAG,IAAI,CAAC,cAAc,CAAC,OAAO,MAAM,CAAC,EAAE,SAAS,CAAC,GAAG;IACvE,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,CAAC;AAEF,eAAO,MAAM,WAAW,GAAI,0DAOzB,gBAAgB,mDA2BlB,CAAC"}
package/dist/controls.js CHANGED
@@ -1,8 +1,8 @@
1
1
  "use client";
2
- import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
3
  import { useI18n } from "fumadocs-ui/contexts/i18n";
4
4
  import { useSearchContext } from "fumadocs-ui/contexts/search";
5
- import { CheckIcon, LanguagesIcon, MessagesSquareIcon, MoonIcon, SunIcon, } from "lucide-react";
5
+ import { CheckIcon, LanguagesIcon, MoonIcon, SunIcon } from "lucide-react";
6
6
  import { useTheme } from "next-themes";
7
7
  import { useEffect, useState } from "react";
8
8
  import { useGeistdocsChat } from "./internal/chat/context";
@@ -48,5 +48,5 @@ export const AskAIButton = ({ children, className, prompt, size = "sm", variant
48
48
  return;
49
49
  }
50
50
  setIsOpen(!isOpen);
51
- }, size: size, type: "button", variant: variant, ...props, children: children ?? (_jsxs(_Fragment, { children: [_jsx(MessagesSquareIcon, { className: "size-3.5 text-gray-800" }), _jsx("span", { children: "Ask AI" })] })) }));
51
+ }, size: size, type: "button", variant: variant, ...props, children: children ?? _jsx("span", { children: "Ask AI" }) }));
52
52
  };
package/docs/agents.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Geistdocs Package Docs
2
2
 
3
- These docs are bundled with `@vercel/geistdocs` 1.4.1 so agents can understand the installed package without web access.
3
+ These docs are bundled with `@vercel/geistdocs` 1.5.0 so agents can understand the installed package without web access.
4
4
  They are generated from `apps/template/content/docs` during the package build.
5
5
 
6
6
  ## How to use these files
package/docs/llms.txt CHANGED
@@ -1,6 +1,6 @@
1
1
  # Geistdocs Package Documentation
2
2
 
3
- These docs are bundled with `@vercel/geistdocs` 1.4.1.
3
+ These docs are bundled with `@vercel/geistdocs` 1.5.0.
4
4
  They describe how to build package-backed Geistdocs sites and how to use the package APIs from generated project adapters.
5
5
 
6
6
  ## Documentation Index
@@ -190,5 +190,5 @@
190
190
  }
191
191
  ],
192
192
  "source": "apps/template/content/docs",
193
- "version": "1.4.1"
193
+ "version": "1.5.0"
194
194
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@vercel/geistdocs",
3
3
  "description": "Runtime and CLI for Geistdocs projects.",
4
- "version": "1.4.1",
4
+ "version": "1.5.0",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "https://github.com/vercel/geistdocs",
@@ -111,6 +111,10 @@
111
111
  "types": "./dist/shiki-theme.d.ts",
112
112
  "default": "./dist/shiki-theme.js"
113
113
  },
114
+ "./components/badge": {
115
+ "types": "./dist/components/badge.d.ts",
116
+ "default": "./dist/components/badge.js"
117
+ },
114
118
  "./components/button": {
115
119
  "types": "./dist/components/button.d.ts",
116
120
  "default": "./dist/components/button.js"
@@ -139,6 +143,10 @@
139
143
  "types": "./dist/components/collapsible.d.ts",
140
144
  "default": "./dist/components/collapsible.js"
141
145
  },
146
+ "./components/command-prompt": {
147
+ "types": "./dist/components/command-prompt.d.ts",
148
+ "default": "./dist/components/command-prompt.js"
149
+ },
142
150
  "./components/copy-prompt": {
143
151
  "types": "./dist/components/copy-prompt.d.ts",
144
152
  "default": "./dist/components/copy-prompt.js"
@@ -1,5 +1,5 @@
1
+ import { Badge } from "@vercel/geistdocs/components/badge";
1
2
  import type { ReactNode } from "react";
2
- import { Badge } from "@/components/ui/badge";
3
3
 
4
4
  interface HeroProps {
5
5
  badge: string;
@@ -1,4 +1,3 @@
1
- import type { Metadata } from "next";
2
1
  import {
3
2
  CommandPromptContent,
4
3
  CommandPromptCopy,
@@ -9,7 +8,8 @@ import {
9
8
  CommandPromptTrigger,
10
9
  CommandPromptTriggerDivider,
11
10
  CommandPromptViewport,
12
- } from "@/components/ui/command-prompt";
11
+ } from "@vercel/geistdocs/components/command-prompt";
12
+ import type { Metadata } from "next";
13
13
  import { CenteredSection } from "./components/centered-section";
14
14
  import { CTA } from "./components/cta";
15
15
  import { Hero } from "./components/hero";
@@ -18,7 +18,7 @@
18
18
  "@streamdown/code": "^1.0.1",
19
19
  "@vercel/agent-readability": "^0.2.1",
20
20
  "@vercel/analytics": "^1.6.1",
21
- "@vercel/geistdocs": "1.4.1",
21
+ "@vercel/geistdocs": "1.5.0",
22
22
  "@vercel/speed-insights": "^1.3.1",
23
23
  "ai": "^6.0.132",
24
24
  "class-variance-authority": "^0.7.1",
@@ -1,46 +0,0 @@
1
- import * as React from "react"
2
- import { Slot as SlotPrimitive } from "radix-ui"
3
- import { cva, type VariantProps } from "class-variance-authority"
4
-
5
- import { cn } from "@/lib/utils"
6
-
7
- const badgeVariants = cva(
8
- "inline-flex items-center justify-center rounded-full border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-gray-600 focus-visible:ring-gray-600/50 focus-visible:ring-[3px] aria-invalid:ring-red-800/20 dark:aria-invalid:ring-red-800/40 aria-invalid:border-red-800 transition-[color,box-shadow] overflow-hidden",
9
- {
10
- variants: {
11
- variant: {
12
- default:
13
- "border-transparent bg-gray-1000 text-background-100 [a&]:hover:bg-gray-1000/90",
14
- secondary:
15
- "border-transparent bg-gray-alpha-400 text-gray-1000 [a&]:hover:bg-gray-alpha-400/90",
16
- destructive:
17
- "border-transparent bg-red-800 text-white [a&]:hover:bg-red-800/90 focus-visible:ring-red-800/20 dark:focus-visible:ring-red-800/40 dark:bg-red-800/60",
18
- outline:
19
- "text-gray-1000 [a&]:hover:bg-gray-100 [a&]:hover:text-gray-1000",
20
- },
21
- },
22
- defaultVariants: {
23
- variant: "default",
24
- },
25
- }
26
- )
27
-
28
- function Badge({
29
- className,
30
- variant,
31
- asChild = false,
32
- ...props
33
- }: React.ComponentProps<"span"> &
34
- VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
35
- const Comp = asChild ? SlotPrimitive.Slot : "span"
36
-
37
- return (
38
- <Comp
39
- data-slot="badge"
40
- className={cn(badgeVariants({ variant }), className)}
41
- {...props}
42
- />
43
- )
44
- }
45
-
46
- export { Badge, badgeVariants }
@@ -1,488 +0,0 @@
1
- "use client";
2
-
3
- import { AnimatePresence, motion, useReducedMotion } from "motion/react";
4
- import {
5
- Children,
6
- type ComponentPropsWithoutRef,
7
- createContext,
8
- isValidElement,
9
- type JSX,
10
- type ReactNode,
11
- useContext,
12
- useEffect,
13
- useLayoutEffect,
14
- useRef,
15
- useState,
16
- } from "react";
17
- import { IconCheck } from "@vercel/geistdocs/assets/icons/icon-check";
18
- import { IconCopy } from "@vercel/geistdocs/assets/icons/icon-copy";
19
- import { cn } from "@/lib/utils";
20
-
21
- type CommandPromptContextValue = {
22
- value: string;
23
- setValue: (value: string) => void;
24
- copied: boolean;
25
- copyActiveValue: () => void;
26
- activeCopyValue: string;
27
- setActiveCopyValue: (value: string) => void;
28
- commandWidth?: number;
29
- setCommandWidth: (value: number | undefined) => void;
30
- isOverflowing: boolean;
31
- setIsOverflowing: (value: boolean) => void;
32
- canShowGradient: boolean;
33
- setCanShowGradient: (value: boolean) => void;
34
- };
35
-
36
- const CommandPromptContext = createContext<CommandPromptContextValue | null>(
37
- null
38
- );
39
-
40
- function useCommandPromptContext(component: string) {
41
- const context = useContext(CommandPromptContext);
42
-
43
- if (!context) {
44
- throw new Error(`${component} must be used within CommandPrompt.Root`);
45
- }
46
-
47
- return context;
48
- }
49
-
50
- type CommandPromptRootProps = Omit<
51
- ComponentPropsWithoutRef<"div">,
52
- "onChange"
53
- > & {
54
- value?: string;
55
- defaultValue?: string;
56
- onValueChange?: (value: string) => void;
57
- };
58
-
59
- export function CommandPromptRoot({
60
- value: valueProp,
61
- defaultValue,
62
- onValueChange,
63
- className,
64
- children,
65
- ...props
66
- }: CommandPromptRootProps): JSX.Element {
67
- const [uncontrolledValue, setUncontrolledValue] = useState(
68
- defaultValue ?? ""
69
- );
70
- const [copied, setCopied] = useState(false);
71
- const [activeCopyValue, setActiveCopyValue] = useState("");
72
- const [commandWidth, setCommandWidth] = useState<number>();
73
- const [isOverflowing, setIsOverflowing] = useState(false);
74
- const [canShowGradient, setCanShowGradient] = useState(true);
75
- const timeoutRef = useRef<ReturnType<typeof setTimeout>>(null);
76
- const value = valueProp ?? uncontrolledValue;
77
-
78
- useEffect(() => {
79
- return () => {
80
- if (timeoutRef.current) clearTimeout(timeoutRef.current);
81
- };
82
- }, []);
83
-
84
- function resetCopiedState() {
85
- setCopied(false);
86
- if (timeoutRef.current) clearTimeout(timeoutRef.current);
87
- }
88
-
89
- function setValue(nextValue: string) {
90
- if (valueProp === undefined) {
91
- setUncontrolledValue(nextValue);
92
- }
93
-
94
- resetCopiedState();
95
- onValueChange?.(nextValue);
96
- }
97
-
98
- function copyActiveValue() {
99
- if (!activeCopyValue) return;
100
-
101
- void navigator.clipboard.writeText(activeCopyValue);
102
- setCopied(true);
103
- if (timeoutRef.current) clearTimeout(timeoutRef.current);
104
- timeoutRef.current = setTimeout(() => setCopied(false), 1000);
105
- }
106
-
107
- return (
108
- <CommandPromptContext.Provider
109
- value={{
110
- value,
111
- setValue,
112
- copied,
113
- copyActiveValue,
114
- activeCopyValue,
115
- setActiveCopyValue,
116
- commandWidth,
117
- setCommandWidth,
118
- isOverflowing,
119
- setIsOverflowing,
120
- canShowGradient,
121
- setCanShowGradient,
122
- }}
123
- >
124
- <div
125
- className={cn("w-full flex items-center flex-col gap-2", className)}
126
- {...props}
127
- >
128
- {children}
129
- </div>
130
- </CommandPromptContext.Provider>
131
- );
132
- }
133
-
134
- export function CommandPromptList({
135
- className,
136
- ...props
137
- }: ComponentPropsWithoutRef<"div">): JSX.Element {
138
- return <div className={cn("flex items-center", className)} {...props} />;
139
- }
140
-
141
- type CommandPromptTriggerProps = ComponentPropsWithoutRef<"button"> & {
142
- value: string;
143
- };
144
-
145
- export function CommandPromptTrigger({
146
- value,
147
- className,
148
- onClick,
149
- children,
150
- ...props
151
- }: CommandPromptTriggerProps): JSX.Element {
152
- const context = useCommandPromptContext("CommandPrompt.Trigger");
153
- const active = context.value === value;
154
-
155
- return (
156
- <button
157
- aria-pressed={active}
158
- className={cn(
159
- "cursor-pointer text-gray-900 hover:text-gray-1000 px-3 py-2",
160
- "text-label-13! font-medium! touch-manipulation border-none bg-transparent rounded-sm",
161
- "outline outline-2 outline-offset-2 outline-transparent focus-visible:outline-[var(--ds-focus-color)]",
162
- "text-gray-900 data-[active]:text-gray-1000 data-[active]:font-medium",
163
- "flex gap-1.5 items-center whitespace-nowrap",
164
- className
165
- )}
166
- data-active={active ? "" : undefined}
167
- onClick={(event) => {
168
- onClick?.(event);
169
- if (event.defaultPrevented) return;
170
- context.setValue(value);
171
- }}
172
- type="button"
173
- {...props}
174
- >
175
- {children}
176
- </button>
177
- );
178
- }
179
-
180
- export function CommandPromptTriggerDivider({
181
- className,
182
- ...props
183
- }: ComponentPropsWithoutRef<"div">): JSX.Element {
184
- return (
185
- <div
186
- aria-hidden
187
- className={cn("w-px h-3 bg-gray-400", className)}
188
- {...props}
189
- />
190
- );
191
- }
192
-
193
- export function CommandPromptSurface({
194
- className,
195
- onClick,
196
- children,
197
- }: {
198
- className?: string;
199
- children: ReactNode;
200
- onClick?: ComponentPropsWithoutRef<"div">["onClick"];
201
- }): JSX.Element {
202
- const context = useCommandPromptContext("CommandPrompt.Surface");
203
- const shouldReduceMotion = useReducedMotion();
204
-
205
- return (
206
- <motion.div
207
- className={cn(
208
- "relative flex items-center group gap-1 material-small transition-colors pl-5 py-2 pr-3 max-w-[calc(100vw-48px)] rounded-full",
209
- className
210
- )}
211
- layout
212
- onClick={(event) => {
213
- onClick?.(event);
214
- if (event.defaultPrevented) return;
215
- if (window.getSelection()?.toString()) return;
216
- context.copyActiveValue();
217
- }}
218
- transition={
219
- shouldReduceMotion
220
- ? { duration: 0 }
221
- : { type: "spring", bounce: 0, duration: 0.4 }
222
- }
223
- >
224
- {children}
225
- </motion.div>
226
- );
227
- }
228
-
229
- export function CommandPromptPrefix({
230
- className,
231
- ...props
232
- }: ComponentPropsWithoutRef<"span">): JSX.Element {
233
- return (
234
- <span
235
- className={cn("block text-label-16-mono! text-gray-500 pr-1", className)}
236
- {...props}
237
- />
238
- );
239
- }
240
-
241
- type CommandPromptContentProps = {
242
- value: string;
243
- copyValue?: string;
244
- className?: string;
245
- children: ReactNode;
246
- };
247
-
248
- export function CommandPromptViewport({
249
- className,
250
- children,
251
- }: {
252
- className?: string;
253
- children: ReactNode;
254
- }): JSX.Element {
255
- const context = useCommandPromptContext("CommandPrompt.Viewport");
256
- const shouldReduceMotion = useReducedMotion();
257
- const {
258
- commandWidth,
259
- canShowGradient,
260
- isOverflowing,
261
- setActiveCopyValue,
262
- setCanShowGradient,
263
- setCommandWidth,
264
- setIsOverflowing,
265
- } = context;
266
- const measureRef = useRef<HTMLSpanElement>(null);
267
- const scrollObserverCleanup = useRef<(() => void) | null>(null);
268
- const items = Children.toArray(children)
269
- .filter((child): child is React.ReactElement<CommandPromptContentProps> =>
270
- isValidElement<CommandPromptContentProps>(child)
271
- )
272
- .map((child) => child.props);
273
- const activeItem = items.find((item) => item.value === context.value);
274
- const command = activeItem?.children ?? null;
275
- const fallbackCopyValue =
276
- typeof command === "string" || typeof command === "number"
277
- ? String(command)
278
- : Children.toArray(command)
279
- .filter(
280
- (child): child is string | number =>
281
- typeof child === "string" || typeof child === "number"
282
- )
283
- .join("");
284
- const copyValue = activeItem?.copyValue ?? fallbackCopyValue;
285
-
286
- useLayoutEffect(() => {
287
- setIsOverflowing(false);
288
- setCanShowGradient(Boolean(shouldReduceMotion));
289
- }, [copyValue, setCanShowGradient, setIsOverflowing, shouldReduceMotion]);
290
-
291
- useEffect(() => {
292
- setActiveCopyValue(copyValue);
293
-
294
- return () => {
295
- setIsOverflowing(false);
296
- scrollObserverCleanup.current?.();
297
- scrollObserverCleanup.current = null;
298
- };
299
- }, [copyValue, setActiveCopyValue, setIsOverflowing]);
300
-
301
- useLayoutEffect(() => {
302
- if (!measureRef.current) return;
303
-
304
- setCommandWidth(measureRef.current.getBoundingClientRect().width);
305
- }, [command, copyValue, setCommandWidth]);
306
-
307
- return (
308
- <motion.span
309
- animate={
310
- commandWidth === undefined
311
- ? undefined
312
- : { width: shouldReduceMotion ? "auto" : commandWidth }
313
- }
314
- className={cn(
315
- "relative block min-w-0 overflow-hidden text-label-14-mono! text-gray-1000",
316
- className
317
- )}
318
- initial={false}
319
- onAnimationComplete={() => {
320
- setCanShowGradient(true);
321
- }}
322
- transition={
323
- shouldReduceMotion
324
- ? { duration: 0 }
325
- : { type: "spring", bounce: 0, duration: 0.4 }
326
- }
327
- >
328
- <span
329
- aria-hidden
330
- className="pointer-events-none invisible absolute whitespace-nowrap"
331
- ref={measureRef}
332
- >
333
- {command}
334
- </span>
335
- <AnimatePresence initial={false} mode="wait">
336
- {Children.toArray(children).map((child) => {
337
- if (!isValidElement<CommandPromptContentProps>(child)) return null;
338
- if (child.props.value !== context.value) return null;
339
-
340
- return (
341
- <motion.span
342
- animate={{ opacity: 1, filter: "blur(0px)" }}
343
- className={cn(
344
- "block whitespace-nowrap min-w-0 py-2",
345
- canShowGradient && isOverflowing
346
- ? "overflow-x-auto"
347
- : "overflow-x-hidden",
348
- child.props.className
349
- )}
350
- exit={{ opacity: 0, filter: "blur(1px)" }}
351
- initial={{ opacity: 0, filter: "blur(1px)" }}
352
- key={copyValue}
353
- ref={(element) => {
354
- scrollObserverCleanup.current?.();
355
- scrollObserverCleanup.current = null;
356
- if (!element) return;
357
-
358
- const checkOverflow = () => {
359
- setIsOverflowing(element.scrollWidth > element.clientWidth);
360
- };
361
-
362
- checkOverflow();
363
- const observer = new ResizeObserver(checkOverflow);
364
- observer.observe(element);
365
- scrollObserverCleanup.current = () => observer.disconnect();
366
- }}
367
- transition={
368
- shouldReduceMotion ? { duration: 0 } : { duration: 0.15 }
369
- }
370
- >
371
- {child.props.children}
372
- </motion.span>
373
- );
374
- })}
375
- </AnimatePresence>
376
- <AnimatePresence>
377
- {canShowGradient && isOverflowing && (
378
- <motion.span
379
- animate={{ opacity: 1 }}
380
- aria-hidden
381
- className="pointer-events-none block z-10 absolute right-0 bg-gradient-to-r from-transparent to-background-100 top-0 bottom-0 w-4"
382
- exit={{ opacity: 0 }}
383
- initial={{ opacity: 0 }}
384
- transition={
385
- shouldReduceMotion ? { duration: 0 } : { duration: 0.2 }
386
- }
387
- />
388
- )}
389
- </AnimatePresence>
390
- </motion.span>
391
- );
392
- }
393
-
394
- export function CommandPromptContent(
395
- _props: CommandPromptContentProps
396
- ): JSX.Element | null {
397
- return null;
398
- }
399
-
400
- export function CommandPromptCopy({
401
- className,
402
- onClick,
403
- ...props
404
- }: ComponentPropsWithoutRef<"button">): JSX.Element {
405
- const context = useCommandPromptContext("CommandPrompt.Copy");
406
- const shouldReduceMotion = useReducedMotion();
407
-
408
- return (
409
- <button
410
- aria-label={context.copied ? "Copied" : "Copy command"}
411
- className={cn(
412
- "text-gray-1000 rounded-full border-none bg-transparent shrink-0 cursor-pointer relative size-8 flex items-center justify-center translate-x-0.5",
413
- "group-hover:bg-gray-alpha-100 hover:!bg-gray-alpha-200 transition-colors touch-manipulation",
414
- "outline-2 outline-offset-2 outline-transparent focus-visible:outline-[var(--ds-focus-color)]",
415
- className
416
- )}
417
- onClick={(event) => {
418
- onClick?.(event);
419
- if (event.defaultPrevented) return;
420
- event.stopPropagation();
421
- context.copyActiveValue();
422
- }}
423
- type="button"
424
- {...props}
425
- >
426
- <AnimatePresence initial={false}>
427
- {!context.copied && (
428
- <motion.span
429
- animate={{
430
- opacity: 1,
431
- transform: "scale(1)",
432
- filter: "blur(0px)",
433
- }}
434
- className="absolute inset-0 flex items-center justify-center"
435
- exit={{
436
- opacity: 0,
437
- transform: "scale(0.5)",
438
- filter: "blur(1px)",
439
- }}
440
- initial={{
441
- opacity: 0,
442
- transform: "scale(0.5)",
443
- filter: "blur(1px)",
444
- }}
445
- key="copy"
446
- transition={
447
- shouldReduceMotion
448
- ? { duration: 0 }
449
- : { duration: 0.2, ease: [0.23, 1, 0.32, 1] }
450
- }
451
- >
452
- <IconCopy className="block" size={16} />
453
- </motion.span>
454
- )}
455
- </AnimatePresence>
456
- <AnimatePresence initial={false}>
457
- {context.copied && (
458
- <motion.span
459
- animate={{
460
- opacity: 1,
461
- transform: "scale(1)",
462
- filter: "blur(0px)",
463
- }}
464
- className="absolute inset-0 flex items-center justify-center"
465
- exit={{
466
- opacity: 0,
467
- transform: "scale(0.5)",
468
- filter: "blur(1px)",
469
- }}
470
- initial={{
471
- opacity: 0,
472
- transform: "scale(0.5)",
473
- filter: "blur(1px)",
474
- }}
475
- key="check"
476
- transition={
477
- shouldReduceMotion
478
- ? { duration: 0 }
479
- : { duration: 0.2, ease: [0.23, 1, 0.32, 1] }
480
- }
481
- >
482
- <IconCheck className="block" size={16} />
483
- </motion.span>
484
- )}
485
- </AnimatePresence>
486
- </button>
487
- );
488
- }