Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions apps/web/src/lib/rtl.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { describe, expect, it } from "vite-plus/test";
import { containsRtl, dirFor, dirForMarkdown, isRtlText } from "./rtl";

describe("isRtlText", () => {
const cases: Array<[string, boolean]> = [
["שלום עולם", true],
["مرحبا بالعالم", true],
["سلام دنیا", true],
["שלום hello עולם", true],
["Note: بقية الجملة عربية طويلة جدا", true],
["Hello world", false],
["Hello world שלום", false],
["", false],
["12345 !@#$%", false],
["ﭐﭑﭒ ﬠﬡ", true],
];

for (const [input, expected] of cases) {
it(`${JSON.stringify(input)} -> ${expected}`, () => {
expect(isRtlText(input)).toBe(expected);
});
}
});

describe("containsRtl", () => {
it("detects RTL without classifying unrelated scripts as RTL", () => {
expect(containsRtl("hello שלום")).toBe(true);
expect(containsRtl("hello world")).toBe(false);
expect(containsRtl("")).toBe(false);
expect(containsRtl("中文")).toBe(false);
expect(containsRtl("あいう")).toBe(false);
});
});

describe("dirFor", () => {
it("returns rtl for RTL-majority text", () => {
expect(dirFor("שלום")).toBe("rtl");
});

it("returns ltr for LTR text", () => {
expect(dirFor("hi")).toBe("ltr");
});
});

describe("dirForMarkdown", () => {
it("ignores markdown code when deciding direction", () => {
expect(dirForMarkdown("- **`apps/web`**: אפליקציית React שמציגה צ'אט")).toBe("rtl");
});
});
40 changes: 40 additions & 0 deletions apps/web/src/lib/rtl.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
function isRtlChar(c: number): boolean {
return (
(c >= 0x0590 && c <= 0x05ff) ||
(c >= 0x0600 && c <= 0x06ff) ||
(c >= 0x0750 && c <= 0x077f) ||
(c >= 0x08a0 && c <= 0x08ff) ||
(c >= 0xfb1d && c <= 0xfdff) ||
(c >= 0xfe70 && c <= 0xfeff)
);
}

function isLtrChar(c: number): boolean {
return (c >= 0x41 && c <= 0x5a) || (c >= 0x61 && c <= 0x7a) || (c >= 0xc0 && c <= 0x024f);
}

export function isRtlText(text: string): boolean {
let rtl = 0;
let ltr = 0;
for (let i = 0; i < text.length; i++) {
const c = text.charCodeAt(i);
if (isRtlChar(c)) rtl++;
else if (isLtrChar(c)) ltr++;
}
if (rtl === 0 && ltr === 0) return false;
return rtl > ltr;
}

export function containsRtl(text: string): boolean {
return Array.from(text).some((char) => isRtlChar(char.charCodeAt(0)));
}

export function dirFor(text: string): "rtl" | "ltr" {
return isRtlText(text) ? "rtl" : "ltr";
}

const MARKDOWN_DIRECTION_NEUTRAL_RE = /```[\s\S]*?(?:```|$)|`[^`\n]*`|https?:\/\/\S+/g;

export function dirForMarkdown(text: string): "rtl" | "ltr" {
return dirFor(text.replace(MARKDOWN_DIRECTION_NEUTRAL_RE, ""));
}
Loading