@chakra-ui/react#toast TypeScript Examples

The following examples show how to use @chakra-ui/react#toast. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UI.tsx    From dope-monorepo with GNU General Public License v3.0 6 votes vote down vote up
private _handleNetworkEvents() {
    if (NetworkHandler.getInstance().connected)
      this.toast({
        ...chakraToastStyle,
        title: 'Connection established',
        status: 'success',
      });

    NetworkHandler.getInstance().on(NetworkEvents.CONNECTED, () =>
      this.toast({
        ...chakraToastStyle,
        title: 'Connection established',
        status: 'success',
      }),
    );

    NetworkHandler.getInstance().on(NetworkEvents.DISCONNECTED, () => {
      this.toast({
        ...chakraToastStyle,
        title: 'Connection lost',
        status: 'error',
      });

      // display connection lost window
      // this.add.reactDom(ConnectionLostWindow);
    });

    NetworkHandler.getInstance().on(NetworkEvents.ERROR, (data: DataTypes[NetworkEvents.ERROR]) => {
      this.toast({
        ...chakraToastStyle,
        title: 'Error ' + data.code,
        description: data.message,
        status: 'error',
      })
    });
  }
Example #2
Source File: UI.tsx    From dope-monorepo with GNU General Public License v3.0 6 votes vote down vote up
private _handleItemInteractions() {
    // handle player add itme into inventory
    EventHandler.emitter().on(Events.PLAYER_INVENTORY_ADD_ITEM, (item: Item, pickup?: boolean) => {
      this.toast({
        ...chakraToastStyle,
        title: pickup
          ? `You picked up ${item.name}`
          : `${item.name} has been added to your inventory`,
        status: 'info',
      });
    });
    // handle player remove item from inventory
    EventHandler.emitter().on(Events.PLAYER_INVENTORY_REMOVE_ITEM, (item: Item, drop?: boolean) => {
      this.toast({
        ...chakraToastStyle,
        title: drop ? `You dropped ${item.name}` : `${item.name} was removed from your inventory`,
        status: 'info',
      });
    });
  }
Example #3
Source File: UI.tsx    From dope-monorepo with GNU General Public License v3.0 6 votes vote down vote up
private _handleQuests() {
    const icon: string = '?';
    // handle quest events
    EventHandler.emitter().on(Events.PLAYER_QUEST_NEW, (quest: Quest) => {
      // TODO: Add line break and quest description when escape sequences are supported
      this.toast({
        ...chakraToastStyle,
        title: `New quest: ${quest.name}`,
      });
    });
    EventHandler.emitter().on(Events.PLAYER_QUEST_COMPLETE, (quest: Quest) => {
      this.toast({
        ...chakraToastStyle,
        title: `Completed quest: ${quest.name}`,
      });
    });
  }
Example #4
Source File: UI.tsx    From dope-monorepo with GNU General Public License v3.0 5 votes vote down vote up
update(time: number, delta: number): void {
    // TODO: do this elsewhere? in game scene?
    // if the player moves too far away from the "owner" of the current interaction
    // cancel it.
    if (this.currentInteraction?.textBox instanceof DialogueTextBox) {
      const playerPos = new Phaser.Math.Vector2(this.player.x, this.player.y);
      const citizen = this.currentInteraction.citizen;
      const citizenPos = new Phaser.Math.Vector2(
        this.currentInteraction.citizen.x,
        this.currentInteraction.citizen.y,
      );

      citizen.lookAt(playerPos.x, playerPos.y);
      this.player.scene.cameras.main.centerOn((this.player.x + citizenPos.x) / 2, (this.player.y + citizenPos.y) / 2);

      if (playerPos.distance(citizenPos) > this.currentInteraction.maxDistance) {
        // onInteractionFinish!!! not complete.
        this.currentInteraction.citizen.onInteractionFinish();
        this.currentInteraction.textBox.destroy();
        this.currentInteraction = undefined;

        EventHandler.emitter().emit(Events.PLAYER_CITIZEN_INTERACT_FINISH, citizen, true);
      }
    }

    const offsetSpacing = 2;
    const playerCamera = this.player.scene.cameras.main;
    this.chatMessageBoxes.forEach((chatToasts, hustler) => {
      if (!hustler.active) {
        chatToasts.forEach((toast) => toast.destroy());
        this.chatMessageBoxes.delete(hustler);
        return;
      }

      let offsetHeight = 0;
      for (let i = chatToasts.length - 1; i >= 0; i--) {
        const chatToast = chatToasts[i];
        offsetHeight += (chatToast.displayHeight) + offsetSpacing;

        let x = (hustler.x - playerCamera.worldView.x) * playerCamera.zoom;
        let y = (hustler.y - playerCamera.worldView.y) * playerCamera.zoom;

        y -= this.player.displayHeight * (playerCamera.zoom / 2);
        y -= offsetHeight;

        if (hustler.hoverText)
          y -= hustler.hoverText.displayHeight * 2;

        chatToast.setPosition(x, y);
        if (chatToast.scale !== playerCamera.zoom / 3)
          chatToast.setScale(playerCamera.zoom / 3);
      }
    });
  }
Example #5
Source File: UI.tsx    From dope-monorepo with GNU General Public License v3.0 5 votes vote down vote up
private _handleMisc() {
    EventHandler.emitter().on(Events.SHOW_NOTIFICAION, (toast: UseToastOptions) => {
      this.toast(toast);
    });

    EventHandler.emitter().on(Events.CHAT_MESSAGE, (hustler: Hustler, text: string, timestamp?: number, addToChat?: boolean) => {      
      if (addToChat) {
        const messageData: DataTypes[NetworkEvents.SERVER_PLAYER_CHAT_MESSAGE] = {
          author: hustler.name,
          message: text,
          timestamp: timestamp ?? Date.now(),
        };
        // add to store
        this.messagesStore.push(messageData);
        // if chattype component is open, dispatch event to update it
        if (this.sendMessageInput) this.sendMessageInput.events.emit('chat_message', messageData);
      }

      // display message IG
      // TODO: dont display if hustler not in camera viewport?
      const messageDuration = {
        in: 500,
        hold: 3500 + text.length * 50,
        out: 500,
      };

      let chatToasts = this.chatMessageBoxes.get(hustler) ?? this.chatMessageBoxes.set(hustler, new Array()).get(hustler)!;

      chatToasts.push(
        this.rexUI.add.toast({
          background: this.rexUI.add.roundRectangle(0, 0, 2, 2, 10, 0xffffff, 0.4),
          text: getBBcodeText(this, 200, 0, 0, 10, '18px').setText(text),
          space: {
            left: 5,
            right: 5,
            top: 5,
            bottom: 5,
          },
          duration: messageDuration,
        }),
      );
      const chatMessage = chatToasts[chatToasts.length - 1];
      // show message
      chatMessage.showMessage(text);

      // destroy game object after duration & remove from array
      // timeout for duration of message
      setTimeout(
        () => {
          chatMessage.destroy();
          // remove chat message toast from array
          chatToasts.splice(chatToasts.indexOf(chatMessage), 1);
        },
        Object.values(messageDuration).reduce((a, b) => a + b, 0),
      );
    });
  }
Example #6
Source File: UI.tsx    From dope-monorepo with GNU General Public License v3.0 5 votes vote down vote up
public toast = createStandaloneToast(theme);
Example #7
Source File: useGame.ts    From dope-monorepo with GNU General Public License v3.0 5 votes vote down vote up
export function useGame(
  config: Types.Core.GameConfig,
  containerRef: React.RefObject<HTMLDivElement>,
): Game | undefined {
  const [game, setGame] = useState<Game>();
  // reload on account/chain change
  useEffect(() => {
    if (!window.ethereum) return;

    const { ethereum } = window as any;
    const toast = createStandaloneToast();

    const destroyGame = () => {
      game?.destroy(true);
      setTimeout(() => setGame(undefined));
      // setGame(undefined)
    };

    const onAccountsChanged = (accounts: string[]) => {
      toast({
        title: 'Detected account change. Reloading game...',
        description: `${accounts[0]}`,
        status: 'warning',
      });
      destroyGame();
    };

    const onChainChanged = (chainId: string | number) => {
      toast({
        title: 'Detected chain change. Reloading game...',
        description: `Chain changed to ${chainId}`,
        status: 'warning',
      });
      destroyGame();
    };

    ethereum.on('accountsChanged', onAccountsChanged);
    ethereum.on('chainChanged', onChainChanged);

    return () => {
      if (ethereum.removeListener) {
        ethereum.removeListener('accountsChanged', onAccountsChanged);
        ethereum.removeListener('chainChanged', onChainChanged);
      }
    };
  }, [game]);

  useEffect(() => {
    if (!game && containerRef.current) {
      //setTimeout(() => {
      const newGame = new Game({ ...config, parent: containerRef.current! });
      setGame(newGame);
      //})
    }
    return () => {
      game?.destroy(true);
    };
  }, [config, containerRef, game]);

  return game;
}
Example #8
Source File: UI.tsx    From dope-monorepo with GNU General Public License v3.0 4 votes vote down vote up
private _handleNpcInteractions() {
    EventHandler.emitter().on(
      Events.PLAYER_CITIZEN_INTERACT_FINISH,
      (citizen: Citizen, cancelled: boolean) => {
        if (!cancelled) return;

        this.toast({
          ...chakraToastStyle,
          title: 'You ran away from the conversation!',
          status: 'info',
        });
      },
    );

    EventHandler.emitter().on(Events.PLAYER_CITIZEN_INTERACT, (citizen: Citizen) => {
      if (citizen.conversations.length === 0) return;

      // get upcoming conversation
      const conv: Conversation = citizen.conversations[0];

      // const icon = this.rexUI.add.label({
      //   orientation: 'y',
      //   icon: this.add.image(0, 0, citizen.texture.key, citizen.texture.key + '_icon').setScale(3),
      //   text: getBBcodeText(this, 0, 0, 0, 0, '10px')
      //   .setText(citizen.name)
      //   .setXOffset(-10)
      //   // .setOrigin(-0.5, 0.5)
      //   .setColor(Palette.COLOR_DARK)
      // });
      let icon;
      if (citizen.hustlerId !== '') {
        icon = this.add.image(0, 0, citizen.texture.key, citizen.texture.key + '_icon').setScale(3);
        icon.setOrigin(0, -0.5);
      }
      // icon.layout();
      const textBox = new DialogueTextBox(this, 500, 500, 65, icon);
      let text = conv.texts[0];
      if (!text) return;

      textBox.start(text.text, text.typingSpeed ?? 50, text.choices)
        .on('complete', (selectedChoice: number) => {
          if (text.onEnd)
            text.onEnd!(citizen, conv, text, selectedChoice);

          conv.texts.shift();
          if (conv.texts.length === 0) {
            textBox.destroy();
            this.currentInteraction = undefined;

            // TODO: Move somewhere else, maybe in the Citizen class?
            citizen.onInteractionFinish();
            EventHandler.emitter().emit(Events.PLAYER_CITIZEN_INTERACT_FINISH, citizen, false);

            citizen.conversations.shift();
            // TODO: move else where
            // NetworkHandler.getInstance().send(UniversalEventNames.PLAYER_UPDATE_CITIZEN_STATE, {
            //   id: citizen.getData('id'),
            //   incConversations: true 
            // });

            if (conv.onFinish) conv.onFinish(citizen, conv);

            return;
          }

          // TODO: Fire up end text event and move somewhere else, maybe in network handler?
          // NetworkHandler.getInstance().send(UniversalEventNames.PLAYER_UPDATE_CITIZEN_STATE, {
          //   citizen: citizen.getData('id'),
          //   conversation: conv.id,
          // } as DataTypes[NetworkEvents.CLIENT_PLAYER_UPDATE_CITIZEN_STATE]);

          text = conv.texts[0];
          textBox.start(text!.text, text!.typingSpeed ?? 50, text.choices);
        })

      this.currentInteraction = { citizen, textBox, maxDistance: 100 };

      // Chat bubbles
      // let pos = new Phaser.Math.Vector2(npc.x, npc.y - (npc.height / 1.2));
      // pos = this.cameras.main.worl
      // npc.x
      // new SpeechBubbleTextBox(this, pos.x, pos.y)
      //     .setScale(1)
      //     .start(conv.text, 50)
      //     .on('destroy', () => {
      //         // re-enable inputs
      //         (this.player.scene as GameScene).canUseMouse = true;
      //         this.player.scene.input.keyboard.enabled = true;
      //         // TODO: Move somewhere else, maybe in the Citizen class?
      //         EventHandler.emitter().emit(Events.PLAYER_INTERACT_NPC_COMPLETE, npc);
      //         // call conversation oncomplete
      //         if (conv.onComplete)
      //             conv.onComplete();
      //     });
    });
  }