habits.andr33v.ru/app/composables/useVillageHelpers.ts

61 lines
1.3 KiB
TypeScript

export const useVillageHelpers = () => {
/**
* Converts data-coordinates (x, y) into a chess-like UI format (e.g. A7).
*
* DATA CONTRACT:
* - x: 0..4 (left → right)
* - y: 0..6 (bottom → top)
*
* UI CONTRACT:
* - rows are shown top → bottom
* - row number = 7 - y
*/
const formatCoordinates = (x: number, y: number): string => {
if (
typeof x !== 'number' ||
typeof y !== 'number' ||
x < 0 ||
y < 0
) {
return '';
}
const col = String.fromCharCode('A'.charCodeAt(0) + x);
const row = 7 - y;
return `${col}${row}`;
};
/**
* Formats backend event messages that already contain
* raw data-coordinates in the form "(x, y)".
*
* IMPORTANT:
* - This function is PRESENTATION-ONLY
* - It assumes (x, y) are DATA coordinates
* - It does NOT change semantics, only visual output
*/
const formatMessageCoordinates = (message: string): string => {
if (!message) return '';
return message.replace(
/\((\d+),\s*(\d+)\)/g,
(_match, xStr, yStr) => {
const x = Number(xStr);
const y = Number(yStr);
if (Number.isNaN(x) || Number.isNaN(y)) {
return _match;
}
return formatCoordinates(x, y);
}
);
};
return {
formatCoordinates,
formatMessageCoordinates,
};
};