create-arona-app 0.0.1-dev.ff9c398 → 0.0.2

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 (70) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +11 -44
  3. package/bin/create-arona-app.js +115 -112
  4. package/package.json +23 -21
  5. package/templates/alchemy/README.md +17 -0
  6. package/templates/alchemy/alchemy.run.ts +16 -0
  7. package/templates/alchemy/package.json +28 -0
  8. package/templates/alchemy/src/counter.ts +38 -0
  9. package/templates/alchemy/src/register.ts +26 -0
  10. package/templates/alchemy/src/resources.ts +8 -0
  11. package/templates/alchemy/src/worker.ts +29 -0
  12. package/templates/alchemy/tsconfig.json +22 -0
  13. package/templates/counter/.env.example +3 -0
  14. package/templates/counter/README.md +17 -0
  15. package/templates/counter/package.json +21 -0
  16. package/templates/counter/src/index.ts +72 -0
  17. package/templates/counter/tsconfig.json +22 -0
  18. package/templates/counter/vite.config.ts +6 -0
  19. package/templates/default/.env.example +3 -0
  20. package/templates/default/package.json +14 -12
  21. package/templates/default/src/counter.ts +65 -0
  22. package/templates/default/src/index.ts +36 -14
  23. package/templates/default/tsconfig.json +20 -26
  24. package/templates/default/vite.config.ts +7 -0
  25. package/templates/rick-and-morty/.env.example +4 -0
  26. package/templates/rick-and-morty/package.json +15 -12
  27. package/templates/rick-and-morty/src/commands/search.ts +15 -0
  28. package/templates/rick-and-morty/src/components/search/character.ts +57 -0
  29. package/templates/rick-and-morty/src/components/search/index.ts +99 -0
  30. package/templates/rick-and-morty/src/components/search/pagination.ts +49 -0
  31. package/templates/rick-and-morty/src/components/search/search-form.ts +60 -0
  32. package/templates/rick-and-morty/src/components/search/status.ts +22 -0
  33. package/templates/rick-and-morty/src/index.ts +40 -14
  34. package/templates/rick-and-morty/src/queries/characters.ts +89 -0
  35. package/templates/rick-and-morty/tsconfig.json +20 -26
  36. package/templates/rick-and-morty/vite.config.ts +7 -0
  37. package/templates/serverless/README.md +17 -0
  38. package/templates/serverless/package.json +22 -0
  39. package/templates/serverless/src/counter.ts +39 -0
  40. package/templates/serverless/src/handler.ts +38 -0
  41. package/templates/serverless/src/index.ts +78 -0
  42. package/templates/serverless/src/register.ts +21 -0
  43. package/templates/serverless/tsconfig.json +22 -0
  44. package/templates/simple/.env.example +3 -0
  45. package/templates/simple/package.json +13 -12
  46. package/templates/simple/src/app.ts +147 -0
  47. package/templates/simple/src/index.ts +57 -0
  48. package/templates/simple/tsconfig.json +20 -26
  49. package/templates/simple/vite.config.ts +6 -0
  50. package/templates/slack/.env.example +3 -0
  51. package/templates/slack/README.md +17 -0
  52. package/templates/slack/package.json +22 -0
  53. package/templates/slack/src/app.ts +45 -0
  54. package/templates/slack/src/index.ts +43 -0
  55. package/templates/slack/tsconfig.json +22 -0
  56. package/templates/slack/vite.config.ts +6 -0
  57. package/templates/default/src/commands/counter/counter.tsx +0 -53
  58. package/templates/default/src/commands/counter/index.ts +0 -7
  59. package/templates/rick-and-morty/src/commands/rick-and-morty/app.tsx +0 -28
  60. package/templates/rick-and-morty/src/commands/rick-and-morty/components/character-display.tsx +0 -40
  61. package/templates/rick-and-morty/src/commands/rick-and-morty/components/character-search-modal.tsx +0 -34
  62. package/templates/rick-and-morty/src/commands/rick-and-morty/components/character-search.tsx +0 -29
  63. package/templates/rick-and-morty/src/commands/rick-and-morty/components/character-select.tsx +0 -36
  64. package/templates/rick-and-morty/src/commands/rick-and-morty/components/navigation.tsx +0 -58
  65. package/templates/rick-and-morty/src/commands/rick-and-morty/hooks/character-search-provider.tsx +0 -90
  66. package/templates/rick-and-morty/src/commands/rick-and-morty/hooks/useCharacters.ts +0 -38
  67. package/templates/rick-and-morty/src/commands/rick-and-morty/index.ts +0 -21
  68. package/templates/rick-and-morty/src/commands/rick-and-morty/types.ts +0 -24
  69. package/templates/simple/src/app.tsx +0 -38
  70. package/templates/simple/src/index.tsx +0 -33
@@ -0,0 +1,57 @@
1
+ import { Telemetry } from "@arona/core";
2
+ import {
3
+ DiscordGatewayClient,
4
+ DiscordGatewayEvent,
5
+ Intent,
6
+ renderMessage,
7
+ } from "@arona/platform-discord";
8
+ import { NodeRuntime } from "@effect/platform-node";
9
+ import { Config, Effect, Stream } from "effect";
10
+ import { App } from "./app";
11
+
12
+ const program = Effect.gen(function* () {
13
+ const config = yield* Config.all({
14
+ token: Config.Redacted("DISCORD_APP_TOKEN"),
15
+ clientId: Config.String("DISCORD_APP_ID"),
16
+ devGuildId: Config.option(Config.String("DISCORD_DEV_GUILD_ID")),
17
+ });
18
+
19
+ return yield* Effect.gen(function* () {
20
+ const client = yield* DiscordGatewayClient;
21
+
22
+ yield* Effect.forkChild(
23
+ Stream.runForEach(
24
+ client.events,
25
+ DiscordGatewayEvent.$match({
26
+ MessageCreate: ({ message }) =>
27
+ message.author.bot
28
+ ? Effect.void
29
+ : renderMessage(message, App, { message }).pipe(Effect.asVoid),
30
+ Ready: () => Effect.void,
31
+ InteractionCreate: () => Effect.void,
32
+ Dispatch: () => Effect.void,
33
+ }),
34
+ ),
35
+ );
36
+
37
+ const user = yield* client.login;
38
+ yield* Effect.log(`🚀 Logged in as ${user.username}`);
39
+ return yield* Effect.never;
40
+ }).pipe(
41
+ Effect.provide(
42
+ DiscordGatewayClient.layerEphemeral({
43
+ token: config.token,
44
+ clientId: config.clientId,
45
+ devGuildId: config.devGuildId,
46
+ intents: [Intent.Guilds, Intent.GuildMessages, Intent.MessageContent],
47
+ }),
48
+ ),
49
+ );
50
+ });
51
+
52
+ const telemetry =
53
+ process.env.NODE_ENV === "production"
54
+ ? Telemetry.layerFromEnv
55
+ : Telemetry.layer({ console: true });
56
+
57
+ NodeRuntime.runMain(program.pipe(Effect.provide(telemetry)));
@@ -1,28 +1,22 @@
1
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
- }
2
+ "compilerOptions": {
3
+ "lib": [
4
+ "ESNext"
5
+ ],
6
+ "target": "ESNext",
7
+ "module": "ESNext",
8
+ "moduleDetection": "force",
9
+ "moduleResolution": "bundler",
10
+ "allowImportingTsExtensions": true,
11
+ "verbatimModuleSyntax": true,
12
+ "noEmit": true,
13
+ "strict": true,
14
+ "exactOptionalPropertyTypes": true,
15
+ "skipLibCheck": true,
16
+ "noFallthroughCasesInSwitch": true,
17
+ "noUncheckedIndexedAccess": true
18
+ },
19
+ "include": [
20
+ "src/**/*"
21
+ ]
28
22
  }
@@ -0,0 +1,6 @@
1
+ import Arona from "@arona/core/vite";
2
+ import { defineConfig } from "vite-plus";
3
+
4
+ export default defineConfig({
5
+ plugins: [Arona.plugin({ entry: "./src/index.ts" })],
6
+ });
@@ -0,0 +1,3 @@
1
+ SLACK_BOT_TOKEN=xoxb-your-bot-token
2
+ SLACK_APP_TOKEN=xapp-your-app-token
3
+ SLACK_PORT=3000
@@ -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,22 @@
1
+ {
2
+ "name": "@arona-ex/slack",
3
+ "private": true,
4
+ "description": "A Slack bot with interactive Block Kit messages",
5
+ "type": "module",
6
+ "module": "index.ts",
7
+ "scripts": {
8
+ "dev": "vp build --watch --mode development",
9
+ "build": "vp build",
10
+ "check:types": "effect-tsgo tsrs --noEmit"
11
+ },
12
+ "dependencies": {
13
+ "@arona/core": "0.0.2",
14
+ "@arona/platform-slack": "0.0.2",
15
+ "effect": "4.2.0"
16
+ },
17
+ "devDependencies": {
18
+ "@types/node": "^26.6.10",
19
+ "typescript": "^5.8.3",
20
+ "vite-plus": "1.8.0"
21
+ }
22
+ }
@@ -0,0 +1,45 @@
1
+ import { Actions, Blocks, Button, Divider, Section, Text, component } from "@arona/platform-slack";
2
+ import { UiSchema } from "effect/ui";
3
+ import { Schema } from "effect";
4
+
5
+ const AppMessage = UiSchema.TaggedEnum({
6
+ ClickedIncrement: {},
7
+ ClickedReset: {},
8
+ });
9
+
10
+ /** An interactive Block Kit message with a shared counter. */
11
+ export const App = component({
12
+ name: "SlackCounter",
13
+ model: Schema.Struct({ count: Schema.Finite }),
14
+ message: AppMessage,
15
+ }).make({
16
+ init: () => ({ count: 0 }),
17
+ update: {
18
+ ClickedIncrement: ($) => $.evolve({ count: (count) => count + 1 }),
19
+ ClickedReset: ($) => $.set({ count: 0 }),
20
+ },
21
+ view: (h, model) =>
22
+ Blocks(h, {
23
+ children: [
24
+ Section(h, {
25
+ children: [Text(h, `:wave: Count: *${model.count}*`)],
26
+ }),
27
+ Divider(h),
28
+ Actions(h, {
29
+ children: [
30
+ Button(h, {
31
+ style: "primary",
32
+ onClick: AppMessage.ClickedIncrement(),
33
+ children: ["+1"],
34
+ }),
35
+ Button(h, {
36
+ style: "danger",
37
+ onClick: AppMessage.ClickedReset(),
38
+ disabled: model.count === 0,
39
+ children: ["Reset"],
40
+ }),
41
+ ],
42
+ }),
43
+ ],
44
+ }),
45
+ });
@@ -0,0 +1,43 @@
1
+ import { Telemetry } from "@arona/core";
2
+ import { AronaSlackClient, renderMessage } from "@arona/platform-slack";
3
+ import { NodeRuntime } from "@effect/platform-node";
4
+ import { Config, Effect, Stream } from "effect";
5
+ import { App } from "./app";
6
+
7
+ const program = Effect.gen(function* () {
8
+ const config = yield* Config.all({
9
+ token: Config.Redacted("SLACK_BOT_TOKEN"),
10
+ appToken: Config.Redacted("SLACK_APP_TOKEN"),
11
+ port: Config.Number("SLACK_PORT").pipe(Config.withDefault(3000)),
12
+ });
13
+
14
+ return yield* Effect.gen(function* () {
15
+ const client = yield* AronaSlackClient;
16
+
17
+ yield* Effect.forkChild(
18
+ client.messages.pipe(
19
+ Stream.filter((message) => "text" in message && /hi/i.test(message.text ?? "")),
20
+ Stream.runForEach((message) => renderMessage(message, App, {}).pipe(Effect.asVoid)),
21
+ ),
22
+ );
23
+
24
+ yield* client.start;
25
+ return yield* Effect.never;
26
+ }).pipe(
27
+ Effect.provide(
28
+ AronaSlackClient.layer({
29
+ token: config.token,
30
+ appToken: config.appToken,
31
+ socketMode: true,
32
+ port: config.port,
33
+ }),
34
+ ),
35
+ );
36
+ });
37
+
38
+ const telemetry =
39
+ process.env.NODE_ENV === "production"
40
+ ? Telemetry.layerFromEnv
41
+ : Telemetry.layer({ console: true });
42
+
43
+ NodeRuntime.runMain(program.pipe(Effect.provide(telemetry)));
@@ -0,0 +1,22 @@
1
+ {
2
+ "compilerOptions": {
3
+ "lib": [
4
+ "ESNext"
5
+ ],
6
+ "target": "ESNext",
7
+ "module": "ESNext",
8
+ "moduleDetection": "force",
9
+ "moduleResolution": "bundler",
10
+ "allowImportingTsExtensions": true,
11
+ "verbatimModuleSyntax": true,
12
+ "noEmit": true,
13
+ "strict": true,
14
+ "exactOptionalPropertyTypes": true,
15
+ "skipLibCheck": true,
16
+ "noFallthroughCasesInSwitch": true,
17
+ "noUncheckedIndexedAccess": true
18
+ },
19
+ "include": [
20
+ "src/**/*"
21
+ ]
22
+ }
@@ -0,0 +1,6 @@
1
+ import Arona from "@arona/core/vite";
2
+ import { defineConfig } from "vite-plus";
3
+
4
+ export default defineConfig({
5
+ plugins: [Arona.plugin({ entry: "./src/index.ts" })],
6
+ });
@@ -1,53 +0,0 @@
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
- }
@@ -1,7 +0,0 @@
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
- })
@@ -1,28 +0,0 @@
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
- }
@@ -1,40 +0,0 @@
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
- }
@@ -1,34 +0,0 @@
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
- }
@@ -1,29 +0,0 @@
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
- }
@@ -1,36 +0,0 @@
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
- }
@@ -1,58 +0,0 @@
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
- }
@@ -1,90 +0,0 @@
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
- }