create-arona-app 0.0.1-dev.1748629324347.5a2f8d0

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.
Files changed (23) hide show
  1. package/README.md +58 -0
  2. package/bin/create-arona-app.js +139 -0
  3. package/package.json +39 -0
  4. package/templates/default/README.md +17 -0
  5. package/templates/default/package.json +21 -0
  6. package/templates/default/src/commands/counter/counter.tsx +53 -0
  7. package/templates/default/src/commands/counter/index.ts +7 -0
  8. package/templates/default/src/index.ts +17 -0
  9. package/templates/default/tsconfig.json +28 -0
  10. package/templates/rick-and-morty/README.md +17 -0
  11. package/templates/rick-and-morty/package.json +21 -0
  12. package/templates/rick-and-morty/src/commands/rick-and-morty/app.tsx +28 -0
  13. package/templates/rick-and-morty/src/commands/rick-and-morty/components/character-display.tsx +40 -0
  14. package/templates/rick-and-morty/src/commands/rick-and-morty/components/character-search-modal.tsx +34 -0
  15. package/templates/rick-and-morty/src/commands/rick-and-morty/components/character-search.tsx +29 -0
  16. package/templates/rick-and-morty/src/commands/rick-and-morty/components/character-select.tsx +36 -0
  17. package/templates/rick-and-morty/src/commands/rick-and-morty/components/navigation.tsx +58 -0
  18. package/templates/rick-and-morty/src/commands/rick-and-morty/hooks/character-search-provider.tsx +90 -0
  19. package/templates/rick-and-morty/src/commands/rick-and-morty/hooks/useCharacters.ts +38 -0
  20. package/templates/rick-and-morty/src/commands/rick-and-morty/index.ts +21 -0
  21. package/templates/rick-and-morty/src/commands/rick-and-morty/types.ts +24 -0
  22. package/templates/rick-and-morty/src/index.ts +17 -0
  23. package/templates/rick-and-morty/tsconfig.json +28 -0
package/README.md ADDED
@@ -0,0 +1,58 @@
1
+ # create-arona-app
2
+
3
+ Create a new Arona app with a single command.
4
+
5
+ ## Usage
6
+
7
+ ```bash
8
+ # Using bun
9
+ bun create arona-app my-app
10
+
11
+ # Using npm
12
+ npm create arona-app my-app
13
+
14
+ # Using yarn
15
+ yarn create arona-app my-app
16
+
17
+ # Using pnpm
18
+ pnpm create arona-app my-app
19
+ ```
20
+
21
+ ## Templates
22
+
23
+ The following templates are available:
24
+
25
+ - `default` - A basic Arona app setup with essential features
26
+ - `rick-and-morty` - An example app that demonstrates API integration with the Rick and Morty API
27
+
28
+ ## Features
29
+
30
+ - Interactive CLI with project name validation
31
+ - Template selection
32
+ - Package manager selection (npm, yarn, pnpm, bun)
33
+ - Automatic package.json configuration
34
+ - Clear next steps instructions
35
+
36
+ ## Development
37
+
38
+ To work on this package locally:
39
+
40
+ 1. Clone the repository
41
+ 2. Install dependencies:
42
+ ```bash
43
+ bun install
44
+ # or
45
+ npm install
46
+ # or
47
+ yarn install
48
+ # or
49
+ pnpm install
50
+ ```
51
+ 3. Link the package:
52
+ ```bash
53
+ npm link
54
+ ```
55
+ 4. Test the package:
56
+ ```bash
57
+ create-arona-app my-test-app
58
+ ```
@@ -0,0 +1,139 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { program } from 'commander';
4
+ import inquirer from 'inquirer';
5
+ import chalk from 'chalk';
6
+ import ora from 'ora';
7
+ import fs from 'fs-extra';
8
+ import path from 'path';
9
+ import { fileURLToPath } from 'url';
10
+
11
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
12
+
13
+ const TEMPLATES = {
14
+ default: 'Default template with basic setup',
15
+ 'rick-and-morty': 'Rick and Morty example with API integration'
16
+ };
17
+
18
+ const PACKAGE_MANAGERS = {
19
+ npm: {
20
+ install: 'npm install',
21
+ dev: 'npm run dev'
22
+ },
23
+ yarn: {
24
+ install: 'yarn',
25
+ dev: 'yarn dev'
26
+ },
27
+ pnpm: {
28
+ install: 'pnpm install',
29
+ dev: 'pnpm dev'
30
+ },
31
+ bun: {
32
+ install: 'bun install',
33
+ dev: 'bun dev'
34
+ }
35
+ };
36
+
37
+ function detectPackageManager() {
38
+ const userAgent = process.env.npm_config_user_agent || '';
39
+ if (userAgent.includes('yarn')) return 'yarn';
40
+ if (userAgent.includes('pnpm')) return 'pnpm';
41
+ if (userAgent.includes('bun')) return 'bun';
42
+ return 'npm';
43
+ }
44
+
45
+ async function processReadme(content, projectName, packageManager) {
46
+ const pm = PACKAGE_MANAGERS[packageManager];
47
+ return content
48
+ .replace(/{{projectName}}/g, projectName)
49
+ .replace(/{{installCommand}}/g, pm.install)
50
+ .replace(/{{devCommand}}/g, pm.dev);
51
+ }
52
+
53
+ async function createApp() {
54
+ console.log(chalk.blue('✨ Welcome to create-arona-app! ✨\n'));
55
+
56
+ const { projectName } = await inquirer.prompt([
57
+ {
58
+ type: 'input',
59
+ name: 'projectName',
60
+ message: 'What is your project named?',
61
+ default: 'my-arona-app',
62
+ validate: (input) => {
63
+ if (!input) return 'Project name is required';
64
+ if (fs.existsSync(input)) return 'Directory already exists';
65
+ return true;
66
+ }
67
+ }
68
+ ]);
69
+
70
+ const { template } = await inquirer.prompt([
71
+ {
72
+ type: 'list',
73
+ name: 'template',
74
+ message: 'Which template would you like to use?',
75
+ choices: Object.entries(TEMPLATES).map(([key, description]) => ({
76
+ name: `${key} - ${description}`,
77
+ value: key
78
+ }))
79
+ }
80
+ ]);
81
+
82
+ const detectedPM = detectPackageManager();
83
+ const { packageManager } = await inquirer.prompt([
84
+ {
85
+ type: 'list',
86
+ name: 'packageManager',
87
+ message: 'Which package manager would you like to use?',
88
+ default: detectedPM,
89
+ choices: Object.keys(PACKAGE_MANAGERS).map(pm => ({
90
+ name: pm,
91
+ value: pm
92
+ }))
93
+ }
94
+ ]);
95
+
96
+ const spinner = ora('Creating your Arona app...').start();
97
+
98
+ try {
99
+ // Create project directory
100
+ await fs.mkdir(projectName);
101
+
102
+ // Copy template files from the local templates directory
103
+ const templatePath = path.join(__dirname, '..', 'templates', template);
104
+ await fs.copy(templatePath, projectName);
105
+
106
+ // Update package.json with project name
107
+ const packageJsonPath = path.join(projectName, 'package.json');
108
+ const packageJson = await fs.readJson(packageJsonPath);
109
+ packageJson.name = projectName;
110
+ await fs.writeJson(packageJsonPath, packageJson, { spaces: 2 });
111
+
112
+ // Process README
113
+ const readmePath = path.join(projectName, 'README.md');
114
+ const readmeContent = await fs.readFile(readmePath, 'utf-8');
115
+ const processedReadme = await processReadme(readmeContent, projectName, packageManager);
116
+ await fs.writeFile(readmePath, processedReadme);
117
+
118
+ spinner.succeed(chalk.green('Project created successfully!'));
119
+
120
+ const pm = PACKAGE_MANAGERS[packageManager];
121
+ console.log('\nNext steps:');
122
+ console.log(chalk.cyan(` cd ${projectName}`));
123
+ console.log(chalk.cyan(` ${pm.install}`));
124
+ console.log(chalk.cyan(` ${pm.dev}`));
125
+ console.log('\nHappy coding! 🚀');
126
+
127
+ } catch (error) {
128
+ spinner.fail(chalk.red('Failed to create project'));
129
+ console.error(error);
130
+ process.exit(1);
131
+ }
132
+ }
133
+
134
+ program
135
+ .name('create-arona-app')
136
+ .description('Create a new Arona app with a single command')
137
+ .action(createApp);
138
+
139
+ program.parse();
package/package.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "create-arona-app",
3
+ "version": "0.0.1-dev.1748629324347.5a2f8d0",
4
+ "repository": {
5
+ "type": "git",
6
+ "url": "git+https://github.com/djobbo/arona.git"
7
+ },
8
+ "license": "MIT",
9
+ "description": "Create a new Arona app with a single command",
10
+ "type": "module",
11
+ "bin": {
12
+ "create-arona-app": "./bin/create-arona-app.js"
13
+ },
14
+ "files": [
15
+ "bin",
16
+ "templates"
17
+ ],
18
+ "scripts": {
19
+ "build": "bun run scripts/copy-templates.ts",
20
+ "prepublishOnly": "bun run build"
21
+ },
22
+ "keywords": [
23
+ "arona",
24
+ "create-arona-app",
25
+ "scaffold",
26
+ "template"
27
+ ],
28
+ "author": "",
29
+ "dependencies": {
30
+ "chalk": "^5.3.0",
31
+ "commander": "^11.1.0",
32
+ "fs-extra": "^11.2.0",
33
+ "inquirer": "^9.2.12",
34
+ "ora": "^7.0.1"
35
+ },
36
+ "devDependencies": {
37
+ "bun-types": "latest"
38
+ }
39
+ }
@@ -0,0 +1,17 @@
1
+ # {{projectName}}
2
+
3
+ This project was created using [create-arona-app](https://github.com/djobbo/arona).
4
+
5
+ ## Getting Started
6
+
7
+ First, install the dependencies:
8
+
9
+ ```bash
10
+ {{installCommand}}
11
+ ```
12
+
13
+ Then, run the development server:
14
+
15
+ ```bash
16
+ {{devCommand}}
17
+ ```
@@ -0,0 +1,21 @@
1
+ {
2
+ "name": "@arona-ex/default",
3
+ "description": "A basic Arona app setup with essential features",
4
+ "module": "index.ts",
5
+ "type": "module",
6
+ "private": true,
7
+ "scripts": {
8
+ "dev": "arona dev ./src/index.ts",
9
+ "build": "arona build ./src/index.ts"
10
+ },
11
+ "devDependencies": {
12
+ "@types/bun": "latest"
13
+ },
14
+ "peerDependencies": {
15
+ "typescript": "^5.8.3"
16
+ },
17
+ "dependencies": {
18
+ "@arona/discord": "workspace:*",
19
+ "@fontsource/slackey": "^5.2.5"
20
+ }
21
+ }
@@ -0,0 +1,53 @@
1
+ import { Button, Canvas, Container, Text } from "@arona/discord"
2
+ import { useState } from "react"
3
+ import { createRequire } from 'module'
4
+ import { readFileSync } from 'fs'
5
+
6
+ const require = createRequire(import.meta.url)
7
+ const resolve = require.resolve
8
+ const slackey = readFileSync(resolve("@fontsource/slackey/files/slackey-latin-400-normal.woff"))
9
+
10
+ export const Counter = () => {
11
+ const [count, setCount] = useState(0)
12
+
13
+ return (
14
+ <>
15
+ <Container>
16
+ <Text># Step: `{count}`</Text>
17
+ <Button
18
+ onClick={() => {
19
+ setCount((prev) => prev + 1)
20
+ }}
21
+ >
22
+ +
23
+ </Button>
24
+ <Canvas width={256} height={96} name="counter.png" fonts={[{
25
+ name: "Slackey",
26
+ data: slackey,
27
+ style: "normal",
28
+ weight: 400,
29
+ }]}>
30
+ <div style={{
31
+ fontFamily: "Slackey",
32
+ fontSize: 32,
33
+ color: "white",
34
+ backgroundColor: "black",
35
+ position: "absolute",
36
+ top: 0,
37
+ left: 0,
38
+ width: "100%",
39
+ height: "100%",
40
+ display: "flex",
41
+ justifyContent: "center",
42
+ alignItems: "center",
43
+ }}>Hello</div>
44
+ </Canvas>
45
+ </Container>
46
+ {/* <Text>
47
+ ```ansi<br/>
48
+ Welcome to Rebane's Discord Colored Text Generator!
49
+ ```
50
+ </Text> */}
51
+ </>
52
+ )
53
+ }
@@ -0,0 +1,7 @@
1
+ import { Counter } from "./counter"
2
+ import { createSlashCommand } from "@arona/discord"
3
+
4
+ export const counter = createSlashCommand("counter", {
5
+ command: (command) => command.setDescription("Counting example command"),
6
+ component: Counter,
7
+ })
@@ -0,0 +1,17 @@
1
+ import { AronaDiscordClient } from "@arona/discord"
2
+ import { Events, GatewayIntentBits } from "discord.js"
3
+ import { counter } from "./commands/counter"
4
+
5
+ const client = new AronaDiscordClient({
6
+ token: process.env.DISCORD_APP_TOKEN!,
7
+ clientId: process.env.DISCORD_APP_ID!,
8
+ devGuildId: process.env.DISCORD_DEV_GUILD_ID,
9
+ intents: [GatewayIntentBits.Guilds],
10
+ })
11
+
12
+ client.once(Events.ClientReady, () => {
13
+ console.log(`🚀 Logged in as ${client.user?.tag}`)
14
+ })
15
+
16
+ client.addCommands([counter])
17
+ await client.login()
@@ -0,0 +1,28 @@
1
+ {
2
+ "compilerOptions": {
3
+ // Environment setup & latest features
4
+ "lib": ["ESNext"],
5
+ "target": "ESNext",
6
+ "module": "ESNext",
7
+ "moduleDetection": "force",
8
+ "jsx": "react-jsx",
9
+ "allowJs": true,
10
+
11
+ // Bundler mode
12
+ "moduleResolution": "bundler",
13
+ "allowImportingTsExtensions": true,
14
+ "verbatimModuleSyntax": true,
15
+ "noEmit": true,
16
+
17
+ // Best practices
18
+ "strict": true,
19
+ "skipLibCheck": true,
20
+ "noFallthroughCasesInSwitch": true,
21
+ "noUncheckedIndexedAccess": true,
22
+
23
+ // Some stricter flags (disabled by default)
24
+ "noUnusedLocals": false,
25
+ "noUnusedParameters": false,
26
+ "noPropertyAccessFromIndexSignature": false
27
+ }
28
+ }
@@ -0,0 +1,17 @@
1
+ # {{projectName}}
2
+
3
+ This project was created using [create-arona-app](https://github.com/djobbo/arona).
4
+
5
+ ## Getting Started
6
+
7
+ First, install the dependencies:
8
+
9
+ ```bash
10
+ {{installCommand}}
11
+ ```
12
+
13
+ Then, run the development server:
14
+
15
+ ```bash
16
+ {{devCommand}}
17
+ ```
@@ -0,0 +1,21 @@
1
+ {
2
+ "name": "@arona-ex/rick-and-morty",
3
+ "description": "An example app that demonstrates API integration with the Rick and Morty API",
4
+ "module": "index.ts",
5
+ "type": "module",
6
+ "private": true,
7
+ "scripts": {
8
+ "dev": "arona dev ./src/index.ts"
9
+ },
10
+ "devDependencies": {
11
+ "@types/bun": "latest"
12
+ },
13
+ "peerDependencies": {
14
+ "typescript": "^5.8.3"
15
+ },
16
+ "dependencies": {
17
+ "@arona/discord": "workspace:*",
18
+ "@tanstack/react-query": "^5.76.1",
19
+ "discord.js": "^14.19.3"
20
+ }
21
+ }
@@ -0,0 +1,28 @@
1
+ import { CharacterDisplay } from "./components/character-display"
2
+ import { CharacterSearch } from "./components/character-search"
3
+ import { CharacterSearchProvider } from "./hooks/character-search-provider"
4
+ import { CharacterSelect } from "./components/character-select"
5
+ import { Container, Section, Text } from "@arona/discord"
6
+ import { Navigation } from "./components/navigation"
7
+ import { QueryClientProvider } from "@tanstack/react-query"
8
+ import { rickAndMortySearch } from "."
9
+
10
+ export const App = () => {
11
+ const {
12
+ loaderData: { queryClient },
13
+ interaction: {
14
+ params: { query },
15
+ },
16
+ } = rickAndMortySearch.useCommandContext()
17
+
18
+ return (
19
+ <QueryClientProvider client={queryClient}>
20
+ <CharacterSearchProvider defaultSearch={query}>
21
+ <CharacterSearch />
22
+ <CharacterDisplay />
23
+ <CharacterSelect />
24
+ <Navigation />
25
+ </CharacterSearchProvider>
26
+ </QueryClientProvider>
27
+ )
28
+ }
@@ -0,0 +1,40 @@
1
+ import { Button, Container, Section, Text, Thumbnail } from "@arona/discord"
2
+ import { useCharacterSearch } from "../hooks/character-search-provider"
3
+ import type { CharacterStatus } from "../types"
4
+ import type { ColorResolvable } from "discord.js"
5
+
6
+ const getCharacterStatusColor = (status: CharacterStatus): ColorResolvable => {
7
+ switch (status) {
8
+ case "Alive":
9
+ return "Green"
10
+ case "Dead":
11
+ return "Red"
12
+ default:
13
+ return "Default"
14
+ }
15
+ }
16
+
17
+ export const CharacterDisplay = () => {
18
+ const { character } = useCharacterSearch()
19
+
20
+ if (!character) {
21
+ return (
22
+ <Container>
23
+ <Text>No character selected</Text>
24
+ </Container>
25
+ )
26
+ }
27
+
28
+ return (
29
+ <Container
30
+ accentColor={getCharacterStatusColor(character.status ?? "unknown")}
31
+ >
32
+ <Section accessory={<Thumbnail media={{ url: character.image }} />}>
33
+ <Text>
34
+ {character.name} `{character.species}`
35
+ </Text>
36
+ </Section>
37
+ <Text>{character.status}</Text>
38
+ </Container>
39
+ )
40
+ }
@@ -0,0 +1,34 @@
1
+ import { Modal, TextInput } from "@arona/discord"
2
+ import { TextInputStyle } from "discord.js"
3
+ import { useCharacterSearch } from "../hooks/character-search-provider"
4
+
5
+ interface CharacterSearchModalProps {
6
+ search?: string
7
+ setSearch: (search: string) => void
8
+ }
9
+
10
+ export const CharacterSearchModal = ({
11
+ search,
12
+ setSearch,
13
+ }: CharacterSearchModalProps) => {
14
+ // This is not yet possible
15
+ // Context is not shared between main app and modals
16
+ // const { search, setSearch } = useCharacterSearch()
17
+
18
+ return (
19
+ <Modal title="Search Character">
20
+ <TextInput
21
+ style={TextInputStyle.Short}
22
+ label="Search for a character by name"
23
+ minLength={1}
24
+ maxLength={50}
25
+ placeholder="e.g. Rick Sanchez, Morty Smith, etc."
26
+ value={search}
27
+ onChange={(value) => {
28
+ console.log("Search value changed:", value)
29
+ setSearch(value ?? "")
30
+ }}
31
+ />
32
+ </Modal>
33
+ )
34
+ }
@@ -0,0 +1,29 @@
1
+ import { Button, Section, Text, useModal } from "@arona/discord"
2
+ import { CharacterSearchModal } from "./character-search-modal"
3
+ import { useCharacterSearch } from "../hooks/character-search-provider"
4
+
5
+ export const CharacterSearch = () => {
6
+ const { search, setSearch } = useCharacterSearch()
7
+ const { openModal } = useModal()
8
+
9
+ return (
10
+ <Section
11
+ accessory={
12
+ <Button
13
+ onClick={openModal(() => (
14
+ <CharacterSearchModal search={search} setSearch={setSearch} />
15
+ ))}
16
+ >
17
+ Search
18
+ </Button>
19
+ }
20
+ >
21
+ <Text>### Search Character</Text>
22
+ {search ? (
23
+ <Text>Current search: {search}</Text>
24
+ ) : (
25
+ <Text>No search term set.</Text>
26
+ )}
27
+ </Section>
28
+ )
29
+ }
@@ -0,0 +1,36 @@
1
+ import { Option, Select } from "@arona/discord"
2
+ import { useCharacterSearch } from "../hooks/character-search-provider"
3
+ import type { Character, CharacterStatus } from "../types"
4
+
5
+ type CharacterSelectProps = {
6
+ characters: Character[]
7
+ character: Character | undefined
8
+ onSelectCharacter: (val: string) => void
9
+ isLoading?: boolean
10
+ }
11
+
12
+ const statusEmojis: Record<CharacterStatus, string> = {
13
+ Alive: "🙂",
14
+ Dead: "💀",
15
+ unknown: "❓",
16
+ }
17
+
18
+ export const CharacterSelect = () => {
19
+ const { character, characters, selectCharacter, isLoading } =
20
+ useCharacterSearch()
21
+ return (
22
+ <Select onChange={([val]) => selectCharacter(val)} disabled={isLoading}>
23
+ {characters.map((char, i) => (
24
+ <Option
25
+ key={char.id}
26
+ value={char.id.toString()}
27
+ description={`${char.species} - ${char.status}`}
28
+ selected={character ? char.id === character.id : i === 0}
29
+ emoji={statusEmojis[char.status] ?? "❔"}
30
+ >
31
+ {char.name}
32
+ </Option>
33
+ ))}
34
+ </Select>
35
+ )
36
+ }
@@ -0,0 +1,58 @@
1
+ import { ActionRow, Button } from "@arona/discord"
2
+ import { ButtonStyle } from "discord.js"
3
+ import { useCharacterSearch } from "../hooks/character-search-provider"
4
+
5
+ export const Navigation = () => {
6
+ const { page, setPage, pageMetadata, isLoading } = useCharacterSearch()
7
+ const setCurrentPage = (newPage: number) => {
8
+ if (!pageMetadata) return setPage(1)
9
+
10
+ if (newPage > pageMetadata.pages) return setPage(pageMetadata.pages)
11
+ if (newPage < 1) return setPage(1)
12
+
13
+ return setPage(newPage)
14
+ }
15
+
16
+ const canInteract = !isLoading && !!pageMetadata && pageMetadata.pages > 0
17
+
18
+ return (
19
+ <ActionRow>
20
+ <Button
21
+ style={ButtonStyle.Secondary}
22
+ onClick={() => setCurrentPage(1)}
23
+ disabled={!canInteract || page <= 1}
24
+ >
25
+ {"<<"}
26
+ </Button>
27
+ <Button
28
+ style={ButtonStyle.Primary}
29
+ onClick={() => setCurrentPage(page - 1)}
30
+ disabled={!canInteract || page <= 1}
31
+ >
32
+ {"<"}
33
+ </Button>
34
+ <Button style={ButtonStyle.Secondary} disabled>
35
+ Page {page}
36
+ {pageMetadata && ` / ${pageMetadata.pages}`}
37
+ </Button>
38
+ <Button
39
+ style={ButtonStyle.Primary}
40
+ onClick={() => setCurrentPage(page + 1)}
41
+ disabled={
42
+ !canInteract || (!!pageMetadata && pageMetadata.pages <= page)
43
+ }
44
+ >
45
+ {">"}
46
+ </Button>
47
+ <Button
48
+ style={ButtonStyle.Secondary}
49
+ onClick={() => setCurrentPage(pageMetadata?.pages ?? 1)}
50
+ disabled={
51
+ !canInteract || (!!pageMetadata && pageMetadata.pages <= page)
52
+ }
53
+ >
54
+ {">>"}
55
+ </Button>
56
+ </ActionRow>
57
+ )
58
+ }
@@ -0,0 +1,90 @@
1
+ import {
2
+ type ReactNode,
3
+ createContext,
4
+ useContext,
5
+ useEffect,
6
+ useState,
7
+ } from "react"
8
+ import { useCharacters } from "./useCharacters"
9
+ import type { Character, PageMetadata } from "../types"
10
+
11
+ interface ICharacterSearchContext {
12
+ search: string
13
+ setSearch: (search: string) => void
14
+ page: number
15
+ setPage: (page: number) => void
16
+ pageMetadata: PageMetadata | null
17
+ characters: Character[]
18
+ isLoading: boolean
19
+ character: Character | null
20
+ selectCharacter: (id: string) => void
21
+ }
22
+
23
+ const characterSearchContext = createContext<ICharacterSearchContext>({
24
+ search: "",
25
+ setSearch: () => {},
26
+ page: 1,
27
+ setPage: () => {},
28
+ characters: [],
29
+ pageMetadata: null,
30
+ isLoading: false,
31
+ character: null,
32
+ selectCharacter: () => {},
33
+ })
34
+
35
+ export const useCharacterSearch = () => {
36
+ const context = useContext(characterSearchContext)
37
+ if (!context) {
38
+ throw new Error(
39
+ "useCharacterSearch must be used within a CharacterSearchProvider",
40
+ )
41
+ }
42
+
43
+ return context
44
+ }
45
+
46
+ type CharacterSearchProviderProps = {
47
+ children: ReactNode
48
+ defaultSearch?: string
49
+ }
50
+
51
+ export const CharacterSearchProvider = ({
52
+ children,
53
+ defaultSearch,
54
+ }: CharacterSearchProviderProps) => {
55
+ const [search, setSearch] = useState(defaultSearch ?? "")
56
+ const [page, setPage] = useState(1)
57
+ const [character, setCharacter] = useState<Character | null>(null)
58
+ console.log("CharacterSearchProvider", { search, page })
59
+ const { characters, pageMetadata, isLoading } = useCharacters(search, page)
60
+
61
+ const selectCharacter = (id: string) => {
62
+ setCharacter(characters?.find((char) => char.id.toString() === id) ?? null)
63
+ }
64
+
65
+ useEffect(() => {
66
+ setCharacter(characters?.[0] ?? null)
67
+ }, [characters])
68
+
69
+ useEffect(() => {
70
+ setPage(1)
71
+ }, [search])
72
+
73
+ return (
74
+ <characterSearchContext.Provider
75
+ value={{
76
+ search,
77
+ setSearch,
78
+ page,
79
+ setPage,
80
+ pageMetadata,
81
+ characters,
82
+ isLoading,
83
+ character,
84
+ selectCharacter,
85
+ }}
86
+ >
87
+ {children}
88
+ </characterSearchContext.Provider>
89
+ )
90
+ }
@@ -0,0 +1,38 @@
1
+ import { useQuery } from "@tanstack/react-query"
2
+ import type { Character, PageMetadata } from "../types"
3
+
4
+ type APIResponse = {
5
+ info: PageMetadata
6
+ results: Character[]
7
+ }
8
+
9
+ export const useCharacters = (search: string, page: number) => {
10
+ const { data, ...query } = useQuery({
11
+ queryKey: ["character", search, page],
12
+ queryFn: async () => {
13
+ const response = await fetch(
14
+ `https://rickandmortyapi.com/api/character/?name=${search}&page=${page}`,
15
+ )
16
+ const data = (await response.json()) as APIResponse
17
+
18
+ return {
19
+ characters: data.results,
20
+ pageMetadata: data.info,
21
+ }
22
+ },
23
+ })
24
+
25
+ if (!data) {
26
+ return {
27
+ characters: [] as Character[],
28
+ pageMetadata: null,
29
+ isLoading: query.isLoading,
30
+ }
31
+ }
32
+
33
+ return {
34
+ characters: data.characters ?? [],
35
+ pageMetadata: data.pageMetadata,
36
+ isLoading: query.isLoading,
37
+ }
38
+ }
@@ -0,0 +1,21 @@
1
+ import { App } from "./app"
2
+ import { QueryClient } from "@tanstack/react-query"
3
+ import { createSlashCommand } from "@arona/discord"
4
+
5
+ export const rickAndMortySearch = createSlashCommand("search", {
6
+ command: (command) =>
7
+ command
8
+ .setDescription("Search Rick and Morty API")
9
+ .addTypedStringOption((option) =>
10
+ option
11
+ .setName("query")
12
+ .setDescription("Search query")
13
+ .setRequired(false),
14
+ ),
15
+ loader: () => {
16
+ return {
17
+ queryClient: new QueryClient(),
18
+ }
19
+ },
20
+ component: App,
21
+ })
@@ -0,0 +1,24 @@
1
+ export type PageMetadata = {
2
+ count: number
3
+ pages: number
4
+ next: string | null
5
+ prev: string | null
6
+ }
7
+
8
+ export type CharacterStatus = "Alive" | "Dead" | "unknown"
9
+
10
+ export type Character = {
11
+ id: number
12
+ name: string
13
+ status: CharacterStatus
14
+ species: string
15
+ type: string
16
+ gender: string
17
+ origin: {
18
+ name: string
19
+ }
20
+ location: {
21
+ name: string
22
+ }
23
+ image: string
24
+ }
@@ -0,0 +1,17 @@
1
+ import { AronaDiscordClient } from "@arona/discord"
2
+ import { Events, GatewayIntentBits } from "discord.js"
3
+ import { rickAndMortySearch } from "./commands/rick-and-morty"
4
+
5
+ const client = new AronaDiscordClient({
6
+ token: process.env.DISCORD_APP_TOKEN!,
7
+ clientId: process.env.DISCORD_APP_ID!,
8
+ devGuildId: process.env.DISCORD_DEV_GUILD_ID,
9
+ intents: [GatewayIntentBits.Guilds],
10
+ })
11
+
12
+ client.once(Events.ClientReady, () => {
13
+ console.log(`🚀 Logged in as ${client.user?.tag}`)
14
+ })
15
+
16
+ client.addCommands([rickAndMortySearch])
17
+ await client.login()
@@ -0,0 +1,28 @@
1
+ {
2
+ "compilerOptions": {
3
+ // Environment setup & latest features
4
+ "lib": ["ESNext"],
5
+ "target": "ESNext",
6
+ "module": "ESNext",
7
+ "moduleDetection": "force",
8
+ "jsx": "react-jsx",
9
+ "allowJs": true,
10
+
11
+ // Bundler mode
12
+ "moduleResolution": "bundler",
13
+ "allowImportingTsExtensions": true,
14
+ "verbatimModuleSyntax": true,
15
+ "noEmit": true,
16
+
17
+ // Best practices
18
+ "strict": true,
19
+ "skipLibCheck": true,
20
+ "noFallthroughCasesInSwitch": true,
21
+ "noUncheckedIndexedAccess": true,
22
+
23
+ // Some stricter flags (disabled by default)
24
+ "noUnusedLocals": false,
25
+ "noUnusedParameters": false,
26
+ "noPropertyAccessFromIndexSignature": false
27
+ }
28
+ }