Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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
52 changes: 52 additions & 0 deletions src/components/AyahView.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import React from 'react'
import type { Meta, StoryObj } from '@storybook/react'
import AyahView from './AyahView'
import '../fonts/index.css'
import { getAyah } from '../utils/ayah'
import type { CSSProperties } from 'react'

type AyahViewStoryProps = {
surah: number
ayah: number
style?: CSSProperties
className?: string
}

function AyahViewStory({ surah, ayah, style, className }: AyahViewStoryProps) {
const result = getAyah(surah, ayah)
if (!result) {
return <p style={{ color: '#121212' }}>Ayah not found ({surah}:{ayah})</p>
}
return <AyahView verse={result.verse} style={style} className={className} />
}

const meta: Meta<typeof AyahViewStory> = {
component: AyahViewStory,
parameters: {
layout: 'centered',
},
}

export default meta
type Story = StoryObj<typeof meta>

export const Default: Story = {
name: 'AyahView',
args: {
surah: 1,
ayah: 1,
style: {
maxWidth: '360px',
padding: '1rem',
backgroundColor: '#F3F4F5',
color: '#121212',
borderRadius: 4,
},
},
argTypes: {
surah: { type: 'number' },
ayah: { type: 'number' },
style: { control: 'object' },
className: { type: 'string' },
},
}
73 changes: 73 additions & 0 deletions src/components/AyahView.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { memo, useMemo } from 'react'
import clipboardCopy from 'clipboard-copy'
import styled from 'styled-components'

import QuranText from './QuranText'
import { AyahViewProps } from '../types'
import { getProcessedWordsFromVerse } from '../utils/page'
import { isArabicDigits } from '../utils/string'
import { isDeepEqual } from '../utils/array'

const AyahContainer = styled.div`
word-break: keep-all !important;
line-height: 1.6;
font-size: 1.1em;
direction: rtl;
text-align: right;
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.15em;
font-family: 'quran-font_react-quran', serif;
`

/**
* Handles copy text event – copies selected Quran words as space-separated text.
*/
const onQuranTextCopy = (event: React.ClipboardEvent<HTMLDivElement>) => {
const selection = document.getSelection()
const quranWordsToCopy = Array.from(document.querySelectorAll(`[data-word]`))
.filter(node => selection?.containsNode(node, true))
.map(wordElement => wordElement.innerHTML.trim())
.join(' ')

if (typeof quranWordsToCopy === 'string' && quranWordsToCopy.length > 0) {
event.preventDefault()
clipboardCopy(quranWordsToCopy)
}
}

/**
* Renders a single ayah (verse) using the same font and word styling as ReadingView.
*/
const AyahView = memo(function AyahView({ verse, style = {}, className = '' }: AyahViewProps) {

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of receiving a Verse object, it would be better to receive two props:

surah: number
ayah: number

After that, it handles getting the Verse object and all the required data.
This ensures simpler code base and better developer experience.

const words = useMemo(() => getProcessedWordsFromVerse(verse), [verse])

return (
<AyahContainer
className={className}
style={style}
onCopy={onQuranTextCopy}
dir="rtl"
>
{words.map((word, wordIndex) => {
const isAyahMarker = isArabicDigits(word.text_uthmani)
const charClass = isAyahMarker ? `react-quran_ayah-marker` : 'react-quran_ayah-word'

return (
<QuranText
className={charClass}
key={`ayah-word-${wordIndex}`}
text={word.text_uthmani}
data={{
chapter: word.chapter_id,
verse: word.verse_number,
}}
/>
)
})}
</AyahContainer>
)
}, isDeepEqual)

export default AyahView
1 change: 1 addition & 0 deletions src/components/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export { default as ReadingView } from './ReadingView'
export { default as Basmalah } from '../components/Basmalah'
export { default as AyahView } from './AyahView'
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
export * from './components'
export { getAyah, searchAyahByText } from './utils/ayah'
export type { AyahResult, SearchAyahOptions } from './types'
29 changes: 29 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,3 +72,32 @@ export type LineContainerStyleProps = {
$length: number
$center: boolean
}

export type AyahViewProps = {
/** A single verse (ayah) with `d` (e.g. "104_1") and `w` (words) */
verse: Verse
/** Optional container styles */
style?: CSSProperties
/** Optional className for the root element */
className?: string
}

export type AyahResult = {
/** Full ayah text (words joined, end marker excluded) */
text: string
/** Surah number (1–114) */
surah: number
/** Arabic surah name from surah.json */
surahName: string
/** Ayah number within the surah */
ayah: number
/** Raw verse for AyahView or further use */
verse: Verse
}

export type SearchAyahOptions = {
/** Max number of results to return */
limit?: number
/** Number of matching ayahs to skip (for pagination) */
offset?: number
}
53 changes: 53 additions & 0 deletions src/utils/ayah.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import React from 'react'
import type { Meta, StoryObj } from '@storybook/react'
import AyahView from '../components/AyahView'
import '../fonts/index.css'
import { getAyah, searchAyahByText } from './ayah'

function AyahUtilsDemo() {
const ayah = getAyah(1, 1)
const searchResults = searchAyahByText('بسم', { limit: 5 })

return (
<div style={{ direction: 'rtl', maxWidth: 480, padding: '1rem', color: '#121212' }}>
<h3 style={{ marginTop: 0 }}>getAyah(1, 1)</h3>
{ayah ? (
<>
<p style={{ margin: '0.5rem 0' }}>
{ayah.surahName} — آية {ayah.ayah}
</p>
<AyahView verse={ayah.verse} />
<p style={{ fontSize: '0.85em', opacity: 0.8 }}>{ayah.text}</p>
</>
) : (
<p>Not found</p>
)}

<h3>searchAyahByText(&apos;بسم&apos;, limit: 5)</h3>
<ul style={{ paddingRight: '1.25rem', margin: 0 }}>
{searchResults.map(result => (
<li key={`${result.surah}_${result.ayah}`} style={{ marginBottom: '0.75rem' }}>
<strong>
{result.surahName} {result.surah}:{result.ayah}
</strong>
<div style={{ fontSize: '0.9em' }}>{result.text}</div>
</li>
))}
</ul>
</div>
)
}

const meta: Meta<typeof AyahUtilsDemo> = {
component: AyahUtilsDemo,
parameters: {
layout: 'centered',
},
}

export default meta
type Story = StoryObj<typeof meta>

export const Default: Story = {
name: 'Ayah utilities',
}
97 changes: 97 additions & 0 deletions src/utils/ayah.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import pagesData from '../data/pages-v2.json'
import { AyahResult, PageDataType, SearchAyahOptions, Verse } from '../types'
import { getChapterName } from './chapter'
import { isArabicDigits, stringToNumber, stripHarakaat } from './string'

let verseIndex: Map<string, Verse> | null = null

function buildVerseIndex(): Map<string, Verse> {
if (verseIndex) return verseIndex

const index = new Map<string, Verse>()
for (const page of pagesData as PageDataType) {
for (const verse of page) {
index.set(verse.d, verse)
}
}
verseIndex = index
return index
}

function verseToText(verse: Verse): string {
return verse.w
.filter(
({ uthmani, type }) =>
type !== 'end' && !isArabicDigits(uthmani),
)
.map(({ uthmani }) => uthmani)
.join(' ')
}

function parseVerseKey(d: string): [number, number] {
const [surah, ayah] = d.split('_').map(stringToNumber)
return [surah, ayah]
}

function toAyahResult(verse: Verse): AyahResult {
const [surah, ayah] = parseVerseKey(verse.d)
return {
text: verseToText(verse),
surah,
surahName: getChapterName(surah),
ayah,
verse,
}
}

/**
* Returns a single ayah by surah and ayah number.
*/
export function getAyah(surahNumber: number, ayahNumber: number): AyahResult | null {
const verse = buildVerseIndex().get(`${surahNumber}_${ayahNumber}`)
return verse ? toAyahResult(verse) : null
}

/**
* Returns ayahs whose text includes the given query (substring match).
* Matching ignores harakaat (e.g. "بسم" matches "بِسۡمِ").
*
* Use `limit` and `offset` to paginate (e.g. page 2 with 10 per page: `{ limit: 10, offset: 10 }`).
*/
export function searchAyahByText(
query: string,
options?: SearchAyahOptions,
): AyahResult[] {
const trimmed = query.trim()
if (!trimmed) return []

const normalizedQuery = stripHarakaat(trimmed)
if (!normalizedQuery) return []

const offset = Math.max(0, options?.offset ?? 0)
const limit = options?.limit
if (limit !== undefined && limit <= 0) return []

const results: AyahResult[] = []
let skipped = 0
let done = false

buildVerseIndex().forEach(verse => {
if (done) return

const text = verseToText(verse)
if (!stripHarakaat(text).includes(normalizedQuery)) return

if (skipped < offset) {
skipped++
return
}

results.push(toAyahResult(verse))
if (limit !== undefined && results.length >= limit) {
done = true
}
})

return results
}
17 changes: 17 additions & 0 deletions src/utils/page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,23 @@ import { ProcessedWord, Verse } from '../types'
import { groupBy } from './array'
import { stringToNumber } from './string'

/**
* Convert a single verse to an array of ProcessedWord.
*/
export function getProcessedWordsFromVerse(verse: Verse): ProcessedWord[] {
const { w: words, d: verse_data } = verse
const [chapter_id, verse_number] = verse_data.split('_').map(stringToNumber)

return words.map(({ uthmani: text_uthmani, line, type }, index) => ({
chapter_id,
verse_number,
is_start: verse_number === 1 && index === 0,
text_uthmani,
line,
type: type || 'word',
}))
}

/**
* Convert a page number into a string and ensure it's a valid page number.
*/
Expand Down
21 changes: 21 additions & 0 deletions src/utils/string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,27 @@ export function stringToNumber(string: string | number): number {
return Number(String(string))
}

function isHarakaatOrMark(codePoint: number): boolean {
if (codePoint >= 0x064b && codePoint <= 0x065f) return true
if (codePoint === 0x0640 || codePoint === 0x0670) return true
if (codePoint >= 0x06d6 && codePoint <= 0x06ed) return true
return false
}

/**
* Removes harakaat and related marks for harakaat-insensitive search.
*/
export function stripHarakaat(text: string): string {
let result = ''
for (const char of text) {
const codePoint = char.codePointAt(0)
if (codePoint !== undefined && !isHarakaatOrMark(codePoint)) {
result += char
}
}
return result
}

const arabicDigitsRegex = /^[\u0660-\u0669]+$/

/**
Expand Down