merlyn/frontend/src/hooks/useChatMessageAlignment.js
高先生 2ea94b5064
feature: support configurable left and right message layout (#3244)
* feat: support user select message  direction

* feat: optimizing the code

* feat: lint code

* fix: prevent localstorage read on every message component render
ui: refactor alignment UI selector for dark and light mode with simple styling

* docs: update jsdoc comment for hook
fix: apply chat alignment to homepage chat

* fix mobile styles of message chat alignment preference

---------

Co-authored-by: Timothy Carambat <rambat1010@gmail.com>
Co-authored-by: shatfield4 <seanhatfield5@gmail.com>
2025-02-25 12:54:16 -08:00

31 lines
1.0 KiB
JavaScript

import { useState, useEffect, useCallback } from "react";
const ALIGNMENT_STORAGE_KEY = "anythingllm-chat-message-alignment";
/**
* Store the message alignment in localStorage as well as provide a function to get the alignment of a message via role.
* @returns {{msgDirection: 'left'|'left_right', setMsgDirection: (direction: string) => void, getMessageAlignment: (role: string) => string}} - The message direction and the class name for the direction.
*/
export function useChatMessageAlignment() {
const [msgDirection, setMsgDirection] = useState(
() => localStorage.getItem(ALIGNMENT_STORAGE_KEY) ?? "left"
);
useEffect(() => {
if (msgDirection) localStorage.setItem(ALIGNMENT_STORAGE_KEY, msgDirection);
}, [msgDirection]);
const getMessageAlignment = useCallback(
(role) => {
const isLeftToRight = role === "user" && msgDirection === "left_right";
return isLeftToRight ? "flex-row-reverse" : "";
},
[msgDirection]
);
return {
msgDirection,
setMsgDirection,
getMessageAlignment,
};
}