@siraj-works/naskh 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +21 -0
- package/LICENSE +21 -0
- package/LIMITATIONS.md +45 -0
- package/README.md +113 -2
- package/SECURITY.md +9 -0
- package/assets/Amiri-Regular.ttf +0 -0
- package/assets/OFL.txt +94 -0
- package/index.d.ts +33 -0
- package/package.json +66 -4
- package/pdfkit.d.ts +17 -0
- package/src/bidi.js +171 -0
- package/src/index.js +51 -0
- package/src/integrations/pdfkit.js +43 -0
- package/src/shaping.js +131 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.1 (2026-11-29)
|
|
4
|
+
- TypeScript declarations now match the published package name and both entry
|
|
5
|
+
points. Previously `index.d.ts` declared `module 'naskh'`, so TypeScript users
|
|
6
|
+
of `@siraj-works/naskh` got no types at all. Added `pdfkit.d.ts` and `types`
|
|
7
|
+
conditions to the `exports` map (works with `node`, `node16`/`nodenext` and
|
|
8
|
+
`bundler` resolution); verified with `tsc --strict` under all three.
|
|
9
|
+
- README: corrected the license note (the Amiri font does ship in `assets/`),
|
|
10
|
+
documented TypeScript support.
|
|
11
|
+
|
|
12
|
+
## 0.1.0 (2026-11-28)
|
|
13
|
+
- Initial release: UAX#9 bidi reordering (via bidi-js), contextual Arabic
|
|
14
|
+
shaping (U+0621–U+064A, tatweel, lam-alef), visual piece decomposition for
|
|
15
|
+
script-itemizing engines (pdfkit/fontkit, node-canvas/Pango), pdfkit
|
|
16
|
+
drawText/drawParagraphs integration, generic presentation-form path,
|
|
17
|
+
idempotency guard, multiline paragraphs, automated tests incl. conformance
|
|
18
|
+
cross-check against bidi-js and rendered before/after artifacts. Pre-release review fixes: surrogate-pair-safe
|
|
19
|
+
bidi run indexing (emoji no longer corrupt engine output), unshape() now folds
|
|
20
|
+
only presentation forms instead of a global NFKC, robustness suite covering
|
|
21
|
+
emoji/ZWJ/composed Unicode/currencies/dates/Hebrew.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Siraj Works contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/LIMITATIONS.md
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
# Known limitations (v0.1.0)
|
|
2
|
+
|
|
3
|
+
Honest list, verified against real renders. If it is not here or in the README
|
|
4
|
+
matrix, it is not claimed.
|
|
5
|
+
|
|
6
|
+
1. **Single-line layout.** `naskh/pdfkit` `drawText` and the canvas recipe place
|
|
7
|
+
one visual line. Automatic line wrapping for long paragraphs is not in v0.1.
|
|
8
|
+
`drawParagraphs` handles `\n`-separated lines only.
|
|
9
|
+
2. **No right-to-left justification / kashida.** Pieces are placed by measured
|
|
10
|
+
widths; inter-word kashida stretching is not applied.
|
|
11
|
+
3. **Shaping coverage: Arabic block U+0621–U+064A + tatweel + lam-alef.**
|
|
12
|
+
Persian/Urdu-only letters (e.g. پ چ ڤ گ) and Arabic Supplement/Extended blocks
|
|
13
|
+
pass through unshaped in the generic path. Bidi ordering still applies.
|
|
14
|
+
In the pdfkit/canvas paths the engine's own GSUB shaping covers them.
|
|
15
|
+
4. **jsPDF is not supported for preprocessing.** jsPDF has an internal Arabic
|
|
16
|
+
pipeline; feeding it naskh output (shaped or reordered) breaks rendering —
|
|
17
|
+
verified empirically. Pure-Arabic jsPDF+Amiri works natively; mixed-direction
|
|
18
|
+
jsPDF is broken upstream with no input-side fix we could verify.
|
|
19
|
+
5. **pdfmake: no verified mixed-bidi hook.** pdfmake's layout engine takes the
|
|
20
|
+
raw string; there is no place to inject piece placement in v0.1. Pure-Arabic
|
|
21
|
+
works via its bundled pdfkit/fontkit engine.
|
|
22
|
+
6. **Copy/paste, search, and PDF text extraction.** The `generic` path emits
|
|
23
|
+
Arabic Presentation Forms-B codepoints; extracted/copied text will contain
|
|
24
|
+
those codepoints, not the original letters (mitigation: `naskh.unshape()`,
|
|
25
|
+
an NFKC fold). The pdfkit/canvas paths keep original codepoints but the
|
|
26
|
+
drawn order is visual, so extraction order may not match reading order.
|
|
27
|
+
**Keep your logical-order source string** for storage, search, and a11y.
|
|
28
|
+
7. **prepare() twice on the pdfkit path is not recoverable.** The generic path
|
|
29
|
+
is idempotent (presentation forms detected). The engine path reorders base
|
|
30
|
+
letters; feeding its output back in will compute bidi on visual-order text.
|
|
31
|
+
Do not chain prepare() calls.
|
|
32
|
+
8. **Dates and numbers follow UAX#9 strictly.** `2026-11-28` inside an RTL
|
|
33
|
+
paragraph renders as `28-11-2026` (hyphen is a European separator; this is
|
|
34
|
+
conformant behavior, identical to browsers/Pango). To pin a date in place,
|
|
35
|
+
wrap it in LRI…PDI (U+2066…U+2069) or use direction marks.
|
|
36
|
+
9. **Fonts.** The generic path needs a font with Presentation Forms-B coverage
|
|
37
|
+
in cmap (verified: Amiri). GSUB-only fonts render .notdef or isolated forms
|
|
38
|
+
there. The pdfkit/canvas paths work with any properly hinted Arabic font
|
|
39
|
+
supported by fontkit/Pango.
|
|
40
|
+
10. **No vertical text, no ruby/annotation text, no SVG textPath.**
|
|
41
|
+
11. **Emoji pass through safely but render only if the chosen font has emoji
|
|
42
|
+
glyphs** (Amiri does not - a fallback emoji font is needed, same as any
|
|
43
|
+
text engine).
|
|
44
|
+
12. **Performance.** Linear in input size, fine for documents; not designed for
|
|
45
|
+
per-frame game loops (benchmark in test suite: ~100KB < 1.5s on a small VM).
|
package/README.md
CHANGED
|
@@ -1,3 +1,114 @@
|
|
|
1
|
-
#
|
|
1
|
+
# naskh
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Arabic & RTL text preparation for PDF and canvas renderers.
|
|
4
|
+
|
|
5
|
+
Logical-order text in, renderer-ready output out. naskh handles the two things most
|
|
6
|
+
PDF/canvas libraries get wrong with Arabic: **bidirectional ordering** (mixed
|
|
7
|
+
Arabic / Latin / numbers / punctuation, per the Unicode Bidirectional Algorithm,
|
|
8
|
+
UAX#9) and **contextual Arabic letter shaping** (isolated / initial / medial / final
|
|
9
|
+
forms, lam-alef ligatures) for renderers that have no shaping engine.
|
|
10
|
+
|
|
11
|
+
Built on [bidi-js](https://github.com/lojjic/bidi-js), a conformance-tested UAX#9
|
|
12
|
+
implementation (MIT license). naskh does not re-implement the bidi algorithm.
|
|
13
|
+
|
|
14
|
+
```
|
|
15
|
+
npm install @siraj-works/naskh
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Which renderer are you using?
|
|
19
|
+
|
|
20
|
+
| Renderer | Native Arabic? | What naskh does for you | Status |
|
|
21
|
+
|---|---|---|---|
|
|
22
|
+
| **pdfkit** | Shapes letters, but breaks mixed-direction lines and mirrored punctuation | `naskh/pdfkit` `drawText()` places UAX#9 visual pieces | ✅ tested (pixel + glyph level) |
|
|
23
|
+
| **pdfmake** | Same engine as pdfkit (bundles pdfkit/fontkit) | Pure-Arabic works natively; mixed bidi needs manual piece layout (no hook in v0.1) | ⚠️ partial |
|
|
24
|
+
| **jsPDF** | Has its own Arabic pipeline (works for pure Arabic with Amiri) | None — preprocessing conflicts with its pipeline. Mixed bidi is broken in jsPDF itself | ❌ use pdfkit for mixed text |
|
|
25
|
+
| **Browser canvas** | Browsers shape + bidi natively | Not needed | ✅ native |
|
|
26
|
+
| **node-canvas (Pango)** | Shapes, but breaks mixed-direction run order | `visualPieces()` + `fillText` per piece (see example) | ✅ tested (pixel) |
|
|
27
|
+
| **Anything with no shaping** (raw canvas-like, SVG, game engines) | None | `prepare(text, { renderer: 'generic' })` → presentation-form visual string | ✅ tested |
|
|
28
|
+
|
|
29
|
+
Every ✅ claim above is backed by an automated test or a rendered artifact in this
|
|
30
|
+
repository (see `test/` and `examples/`). We do not claim support we have not run.
|
|
31
|
+
|
|
32
|
+
## Quick start: pdfkit
|
|
33
|
+
|
|
34
|
+
```js
|
|
35
|
+
const PDFDocument = require('pdfkit');
|
|
36
|
+
const { drawText } = require('@siraj-works/naskh/pdfkit');
|
|
37
|
+
|
|
38
|
+
const doc = new PDFDocument();
|
|
39
|
+
doc.registerFont('amiri', 'Amiri-Regular.ttf');
|
|
40
|
+
doc.font('amiri').fontSize(18);
|
|
41
|
+
|
|
42
|
+
// right-aligned at x=540, correct mixed bidi:
|
|
43
|
+
drawText(doc, 'فاتورة Invoice رقم 123 بتاريخ 2026-11-28', 540, 100, { align: 'right' });
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
`drawText` returns the painted width. Set font and size **before** calling.
|
|
47
|
+
Single-line only in v0.1 (no automatic wrapping) — see LIMITATIONS.md.
|
|
48
|
+
|
|
49
|
+
## Quick start: node-canvas
|
|
50
|
+
|
|
51
|
+
```js
|
|
52
|
+
const naskh = require('@siraj-works/naskh');
|
|
53
|
+
const pieces = naskh.visualPieces(text, { engine: 'pango' });
|
|
54
|
+
let x = rightEdge - pieces.reduce((w, p) => w + ctx.measureText(p.text).width, 0);
|
|
55
|
+
for (const p of pieces) { ctx.fillText(p.text, x, y); x += ctx.measureText(p.text).width; }
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
See `examples/canvas.js`.
|
|
59
|
+
|
|
60
|
+
## Quick start: generic (no shaping engine)
|
|
61
|
+
|
|
62
|
+
```js
|
|
63
|
+
const naskh = require('@siraj-works/naskh');
|
|
64
|
+
const visual = naskh.prepare('مرحبا بالعالم', { renderer: 'generic' });
|
|
65
|
+
// visual-order string of Arabic Presentation Forms-B codepoints;
|
|
66
|
+
// paint it left-to-right with a font that covers presentation forms (e.g. Amiri).
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## API
|
|
70
|
+
|
|
71
|
+
- `prepare(text, { renderer, direction, assumeShaped })` — one-call preparation.
|
|
72
|
+
Calling `prepare()` on its own output is safe (never double-shapes).
|
|
73
|
+
- `visualPieces(text, { direction, mirror, engine })` — placeable pieces in exact
|
|
74
|
+
visual order. Strong pieces stay logical (your engine shapes/reverses them);
|
|
75
|
+
neutral pieces are final (mirrored, pre-reversed). `engine: 'fontkit' | 'pango'`.
|
|
76
|
+
- `visualRuns(text, { direction, mirror })` — UAX#9 runs in visual order.
|
|
77
|
+
- `toVisual(text)` — full visual-order string (unshaped).
|
|
78
|
+
- `shape(text)` / `unshape(text)` / `isShaped(text)` — contextual shaping utilities.
|
|
79
|
+
|
|
80
|
+
`direction` is `'auto' | 'rtl' | 'ltr'` (base paragraph direction; default auto,
|
|
81
|
+
first strong character). Multiline input: `\n` splits paragraphs, each handled
|
|
82
|
+
independently.
|
|
83
|
+
|
|
84
|
+
TypeScript types ship with the package for both entry points
|
|
85
|
+
(`@siraj-works/naskh` and `@siraj-works/naskh/pdfkit`); they resolve under
|
|
86
|
+
`node`, `node16`/`nodenext` and `bundler` module resolution.
|
|
87
|
+
|
|
88
|
+
## Fonts
|
|
89
|
+
|
|
90
|
+
Shaped output and presentation forms need a font that covers Arabic Presentation
|
|
91
|
+
Forms-B. [Amiri](https://github.com/aliftype/amiri) (OFL) is verified. Fonts that
|
|
92
|
+
only implement shaping via OpenType GSUB (many modern fonts) work for the pdfkit /
|
|
93
|
+
canvas paths but **not** for the `generic` presentation-form path — check cmap
|
|
94
|
+
coverage first.
|
|
95
|
+
|
|
96
|
+
## Correctness and honesty
|
|
97
|
+
|
|
98
|
+
- Bidi ordering is delegated to bidi-js, which passes the official UAX#9
|
|
99
|
+
conformance tests (section UAX-C1). naskh's piece decomposition is verified
|
|
100
|
+
against bidi-js output in `test/bidi.test.js`.
|
|
101
|
+
- We distinguish **visual rendering correctness** from **internal text
|
|
102
|
+
structure**: prepared output is for painting only. Keep your original
|
|
103
|
+
logical-order string for storage, search, copy/paste and accessibility.
|
|
104
|
+
Text extracted from a PDF made with the generic path will contain presentation
|
|
105
|
+
forms — see LIMITATIONS.md.
|
|
106
|
+
- We do **not** claim full Unicode shaping-spec conformance: the shaping table
|
|
107
|
+
covers the Arabic block U+0621–U+064A + tatweel + lam-alef. Persian/Urdu-only
|
|
108
|
+
letters pass through unshaped (they still get correct bidi order). See
|
|
109
|
+
LIMITATIONS.md.
|
|
110
|
+
|
|
111
|
+
## License
|
|
112
|
+
|
|
113
|
+
MIT. Dependencies: bidi-js (MIT). The Amiri font in `assets/` is OFL-1.1 and
|
|
114
|
+
ships with the package; other fonts are your choice.
|
package/SECURITY.md
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
# Security & reporting policy
|
|
2
|
+
|
|
3
|
+
- naskh processes text locally. It collects no data, makes no network calls,
|
|
4
|
+
and contains no telemetry or tracking.
|
|
5
|
+
- Dependency surface is one package: bidi-js (MIT, zero dependencies).
|
|
6
|
+
- Report bugs and security issues via GitHub Issues on the project repository.
|
|
7
|
+
For security-sensitive reports, mark the issue clearly and avoid attaching
|
|
8
|
+
private data; we will move to a private channel if needed.
|
|
9
|
+
- naskh never asks for credentials, API keys, or secrets of any kind.
|
|
Binary file
|
package/assets/OFL.txt
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
Copyright 2010-2022 The Amiri Project Authors (https://github.com/aliftype/amiri).
|
|
2
|
+
|
|
3
|
+
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
|
4
|
+
This license is copied below, and is also available with a FAQ at:
|
|
5
|
+
https://openfontlicense.org/
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
-----------------------------------------------------------
|
|
9
|
+
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
|
10
|
+
-----------------------------------------------------------
|
|
11
|
+
|
|
12
|
+
PREAMBLE
|
|
13
|
+
The goals of the Open Font License (OFL) are to stimulate worldwide
|
|
14
|
+
development of collaborative font projects, to support the font creation
|
|
15
|
+
efforts of academic and linguistic communities, and to provide a free and
|
|
16
|
+
open framework in which fonts may be shared and improved in partnership
|
|
17
|
+
with others.
|
|
18
|
+
|
|
19
|
+
The OFL allows the licensed fonts to be used, studied, modified and
|
|
20
|
+
redistributed freely as long as they are not sold by themselves. The
|
|
21
|
+
fonts, including any derivative works, can be bundled, embedded,
|
|
22
|
+
redistributed and/or sold with any software provided that any reserved
|
|
23
|
+
names are not used by derivative works. The fonts and derivatives,
|
|
24
|
+
however, cannot be released under any other type of license. The
|
|
25
|
+
requirement for fonts to remain under this license does not apply
|
|
26
|
+
to any document created using the fonts or their derivatives.
|
|
27
|
+
|
|
28
|
+
DEFINITIONS
|
|
29
|
+
"Font Software" refers to the set of files released by the Copyright
|
|
30
|
+
Holder(s) under this license and clearly marked as such. This may
|
|
31
|
+
include source files, build scripts and documentation.
|
|
32
|
+
|
|
33
|
+
"Reserved Font Name" refers to any names specified as such after the
|
|
34
|
+
copyright statement(s).
|
|
35
|
+
|
|
36
|
+
"Original Version" refers to the collection of Font Software components as
|
|
37
|
+
distributed by the Copyright Holder(s).
|
|
38
|
+
|
|
39
|
+
"Modified Version" refers to any derivative made by adding to, deleting,
|
|
40
|
+
or substituting -- in part or in whole -- any of the components of the
|
|
41
|
+
Original Version, by changing formats or by porting the Font Software to a
|
|
42
|
+
new environment.
|
|
43
|
+
|
|
44
|
+
"Author" refers to any designer, engineer, programmer, technical
|
|
45
|
+
writer or other person who contributed to the Font Software.
|
|
46
|
+
|
|
47
|
+
PERMISSION & CONDITIONS
|
|
48
|
+
Permission is hereby granted, free of charge, to any person obtaining
|
|
49
|
+
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
|
50
|
+
redistribute, and sell modified and unmodified copies of the Font
|
|
51
|
+
Software, subject to the following conditions:
|
|
52
|
+
|
|
53
|
+
1) Neither the Font Software nor any of its individual components,
|
|
54
|
+
in Original or Modified Versions, may be sold by itself.
|
|
55
|
+
|
|
56
|
+
2) Original or Modified Versions of the Font Software may be bundled,
|
|
57
|
+
redistributed and/or sold with any software, provided that each copy
|
|
58
|
+
contains the above copyright notice and this license. These can be
|
|
59
|
+
included either as stand-alone text files, human-readable headers or
|
|
60
|
+
in the appropriate machine-readable metadata fields within text or
|
|
61
|
+
binary files as long as those fields can be easily viewed by the user.
|
|
62
|
+
|
|
63
|
+
3) No Modified Version of the Font Software may use the Reserved Font
|
|
64
|
+
Name(s) unless explicit written permission is granted by the corresponding
|
|
65
|
+
Copyright Holder. This restriction only applies to the primary font name as
|
|
66
|
+
presented to the users.
|
|
67
|
+
|
|
68
|
+
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
|
69
|
+
Software shall not be used to promote, endorse or advertise any
|
|
70
|
+
Modified Version, except to acknowledge the contribution(s) of the
|
|
71
|
+
Copyright Holder(s) and the Author(s) or with their explicit written
|
|
72
|
+
permission.
|
|
73
|
+
|
|
74
|
+
5) The Font Software, modified or unmodified, in part or in whole,
|
|
75
|
+
must be distributed entirely under this license, and must not be
|
|
76
|
+
distributed under any other license. The requirement for fonts to
|
|
77
|
+
remain under this license does not apply to any document created
|
|
78
|
+
using the Font Software.
|
|
79
|
+
|
|
80
|
+
TERMINATION
|
|
81
|
+
This license becomes null and void if any of the above conditions are
|
|
82
|
+
not met.
|
|
83
|
+
|
|
84
|
+
DISCLAIMER
|
|
85
|
+
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
86
|
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
|
87
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
|
88
|
+
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
|
89
|
+
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
|
90
|
+
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
|
91
|
+
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
92
|
+
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
|
93
|
+
OTHER DEALINGS IN THE FONT SOFTWARE.
|
|
94
|
+
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
export interface PrepareOptions {
|
|
2
|
+
renderer?: 'pdfkit' | 'pdfmake' | 'generic';
|
|
3
|
+
direction?: 'auto' | 'rtl' | 'ltr';
|
|
4
|
+
assumeShaped?: boolean;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export interface Piece {
|
|
8
|
+
text: string;
|
|
9
|
+
rtl: boolean;
|
|
10
|
+
neutral: boolean;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface Run {
|
|
14
|
+
text: string;
|
|
15
|
+
rtl: boolean;
|
|
16
|
+
level: number;
|
|
17
|
+
break?: boolean;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export type Direction = 'auto' | 'rtl' | 'ltr';
|
|
21
|
+
|
|
22
|
+
export function prepare(text: string, opts?: PrepareOptions): string;
|
|
23
|
+
export function shape(text: string): string;
|
|
24
|
+
export function unshape(text: string): string;
|
|
25
|
+
export function isShaped(text: string): boolean;
|
|
26
|
+
export function toVisual(text: string, opts?: { direction?: Direction }): string;
|
|
27
|
+
export function visualRuns(text: string, opts?: { direction?: Direction; mirror?: boolean }): Run[];
|
|
28
|
+
export function visualPieces(
|
|
29
|
+
text: string,
|
|
30
|
+
opts?: { direction?: Direction; mirror?: boolean; engine?: 'fontkit' | 'pango' }
|
|
31
|
+
): Piece[];
|
|
32
|
+
export function reorderForEngine(text: string, opts?: { direction?: Direction }): string;
|
|
33
|
+
export const version: string;
|
package/package.json
CHANGED
|
@@ -1,6 +1,68 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@siraj-works/naskh",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Arabic & RTL text preparation for PDF and canvas renderers: UAX#9 bidi reordering + contextual Arabic shaping. Logical in, renderer-ready out.",
|
|
5
|
+
"main": "src/index.js",
|
|
6
|
+
"types": "index.d.ts",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": {
|
|
9
|
+
"types": "./index.d.ts",
|
|
10
|
+
"default": "./src/index.js"
|
|
11
|
+
},
|
|
12
|
+
"./pdfkit": {
|
|
13
|
+
"types": "./pdfkit.d.ts",
|
|
14
|
+
"default": "./src/integrations/pdfkit.js"
|
|
15
|
+
},
|
|
16
|
+
"./assets/*": "./assets/*",
|
|
17
|
+
"./package.json": "./package.json"
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"src",
|
|
21
|
+
"assets/Amiri-Regular.ttf",
|
|
22
|
+
"assets/OFL.txt",
|
|
23
|
+
"index.d.ts",
|
|
24
|
+
"README.md",
|
|
25
|
+
"LIMITATIONS.md",
|
|
26
|
+
"CHANGELOG.md",
|
|
27
|
+
"SECURITY.md",
|
|
28
|
+
"LICENSE",
|
|
29
|
+
"pdfkit.d.ts"
|
|
30
|
+
],
|
|
31
|
+
"scripts": {
|
|
32
|
+
"test": "node --test && node test-robust.js && node test-verify.js",
|
|
33
|
+
"prepublishOnly": "node scripts-preflight.js"
|
|
34
|
+
},
|
|
35
|
+
"keywords": [
|
|
36
|
+
"arabic",
|
|
37
|
+
"rtl",
|
|
38
|
+
"bidi",
|
|
39
|
+
"bidirectional",
|
|
40
|
+
"shaping",
|
|
41
|
+
"arabic-shaping",
|
|
42
|
+
"pdf",
|
|
43
|
+
"pdfkit",
|
|
44
|
+
"canvas",
|
|
45
|
+
"text",
|
|
46
|
+
"uax9",
|
|
47
|
+
"presentation-forms",
|
|
48
|
+
"visual-order"
|
|
49
|
+
],
|
|
50
|
+
"license": "MIT",
|
|
51
|
+
"dependencies": {
|
|
52
|
+
"bidi-js": "^1.0.3"
|
|
53
|
+
},
|
|
54
|
+
"engines": {
|
|
55
|
+
"node": ">=14"
|
|
56
|
+
},
|
|
57
|
+
"repository": {
|
|
58
|
+
"type": "git",
|
|
59
|
+
"url": "https://github.com/siraj-works/naskh.git"
|
|
60
|
+
},
|
|
61
|
+
"homepage": "https://github.com/siraj-works/naskh#readme",
|
|
62
|
+
"bugs": "https://github.com/siraj-works/naskh/issues",
|
|
63
|
+
"author": "Siraj Works contributors",
|
|
64
|
+
"devDependencies": {
|
|
65
|
+
"pdfkit": "^0.15.0",
|
|
66
|
+
"canvas": "^2.11.2"
|
|
67
|
+
}
|
|
68
|
+
}
|
package/pdfkit.d.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export interface PdfKitOptions {
|
|
2
|
+
direction?: 'auto' | 'rtl' | 'ltr';
|
|
3
|
+
align?: 'left' | 'right';
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
export interface PdfKitParagraphOptions extends PdfKitOptions {
|
|
7
|
+
lineGap?: number;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export function drawText(doc: any, text: string, x: number, y: number, opts?: PdfKitOptions): number;
|
|
11
|
+
export function drawParagraphs(
|
|
12
|
+
doc: any,
|
|
13
|
+
text: string,
|
|
14
|
+
x: number,
|
|
15
|
+
y: number,
|
|
16
|
+
opts?: PdfKitParagraphOptions
|
|
17
|
+
): number;
|
package/src/bidi.js
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
// naskh - bidirectional reordering built on bidi-js (UAX#9, conformance-tested).
|
|
2
|
+
// Two output shapes:
|
|
3
|
+
// toVisual() -> full visual-order string for renderers with NO shaping/bidi engine
|
|
4
|
+
// (use together with shaping.js presentation forms).
|
|
5
|
+
// visualRuns() -> runs in visual order, each kept in LOGICAL character order, for
|
|
6
|
+
// engines that shape and reverse RTL runs themselves (pdfkit/fontkit).
|
|
7
|
+
'use strict';
|
|
8
|
+
|
|
9
|
+
const bidiFactory = require('bidi-js');
|
|
10
|
+
const { isCombiningMark } = require('./shaping');
|
|
11
|
+
|
|
12
|
+
let bidi = null;
|
|
13
|
+
const engine = () => (bidi || (bidi = bidiFactory()));
|
|
14
|
+
|
|
15
|
+
const PARA_SPLIT = /\r\n|[\n\r\u2028\u2029]/;
|
|
16
|
+
|
|
17
|
+
function paragraphs(text) {
|
|
18
|
+
// split into UAX#9 paragraphs, remembering the separators
|
|
19
|
+
const parts = [];
|
|
20
|
+
let start = 0;
|
|
21
|
+
for (let i = 0; i < text.length; i++) {
|
|
22
|
+
if (PARA_SPLIT.test(text[i])) {
|
|
23
|
+
parts.push({ text: text.slice(start, i), sep: text[i] });
|
|
24
|
+
start = i + 1;
|
|
25
|
+
PARA_SPLIT.lastIndex = 0;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
PARA_SPLIT.lastIndex = 0;
|
|
29
|
+
parts.push({ text: text.slice(start), sep: '' });
|
|
30
|
+
return parts;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function levelsFor(paraText, direction) {
|
|
34
|
+
const paraLevel = direction === 'rtl' ? 1 : direction === 'ltr' ? 0 : 'auto';
|
|
35
|
+
return engine().getEmbeddingLevels(paraText, paraLevel);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// Visual-order run list for one paragraph.
|
|
39
|
+
// Returns [{ text, rtl, level }] in visual order; each run's text in LOGICAL order,
|
|
40
|
+
// with bracket mirroring applied where UAX#9 requires it (odd levels).
|
|
41
|
+
function visualRunsOf(paraText, direction, mirrorEnabled) {
|
|
42
|
+
if (!paraText) return [];
|
|
43
|
+
const b = engine();
|
|
44
|
+
const levelsResult = levelsFor(paraText, direction);
|
|
45
|
+
const indices = b.getReorderedIndices(paraText, levelsResult);
|
|
46
|
+
const levels = levelsResult.levels;
|
|
47
|
+
const chars = paraText.split(''); // code units: bidi-js indices are UTF-16 (surrogate-pair safe)
|
|
48
|
+
const mirror = mirrorEnabled ? b.getMirroredCharactersMap(paraText, levels) : new Map();
|
|
49
|
+
|
|
50
|
+
const runs = [];
|
|
51
|
+
let cur = null; // { rtl, level, idxs: [original indices in logical order] }
|
|
52
|
+
for (let v = 0; v < indices.length; v++) {
|
|
53
|
+
const orig = indices[v];
|
|
54
|
+
const rtl = (levels[orig] & 1) === 1;
|
|
55
|
+
if (cur && cur.rtl === rtl && (rtl ? orig === cur.last - 1 : orig === cur.last + 1)) {
|
|
56
|
+
cur.idxs.push(orig); cur.last = orig;
|
|
57
|
+
} else {
|
|
58
|
+
if (cur) runs.push(cur);
|
|
59
|
+
cur = { rtl, level: levels[orig], idxs: [orig], last: orig };
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
if (cur) runs.push(cur);
|
|
63
|
+
|
|
64
|
+
return runs.map((r) => {
|
|
65
|
+
r.idxs.sort((a, b2) => a - b2);
|
|
66
|
+
let text = '';
|
|
67
|
+
for (const i of r.idxs) text += (mirror.get(i) || chars[i]);
|
|
68
|
+
return { text, rtl: r.rtl, level: r.level };
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Full visual-order string for one paragraph, combining-mark safe:
|
|
73
|
+
// a combining mark always stays AFTER its base character in memory,
|
|
74
|
+
// which is what LTR glyph-painting renderers (PDF writers, canvas) expect.
|
|
75
|
+
function toVisualOf(paraText, direction) {
|
|
76
|
+
if (!paraText) return '';
|
|
77
|
+
const b = engine();
|
|
78
|
+
const levelsResult = levelsFor(paraText, direction);
|
|
79
|
+
const visual = [...b.getReorderedString(paraText, levelsResult)]; // mirroring applied by bidi-js
|
|
80
|
+
// fix mark clusters: [mark..., base] -> [base, mark...] (marks reversed with their base)
|
|
81
|
+
for (let i = 0; i < visual.length - 1; i++) {
|
|
82
|
+
if (isCombiningMark(visual[i].codePointAt(0))) {
|
|
83
|
+
let j = i;
|
|
84
|
+
while (j < visual.length - 1 && isCombiningMark(visual[j].codePointAt(0))) j++;
|
|
85
|
+
if (!isCombiningMark(visual[j].codePointAt(0)) && j > i) {
|
|
86
|
+
// rotate: base char at j moves to position i
|
|
87
|
+
const base = visual[j];
|
|
88
|
+
for (let k = j; k > i; k--) visual[k] = visual[k - 1];
|
|
89
|
+
visual[i] = base;
|
|
90
|
+
i = j; // continue after this cluster
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return visual.join('');
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function mapParagraphs(text, fn, direction) {
|
|
98
|
+
return paragraphs(text).map((p) => fn(p.text, direction) + p.sep).join('');
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// Public: full visual-order string (for no-engine renderers; pair with shape()).
|
|
102
|
+
const toVisual = (text, { direction = 'auto' } = {}) =>
|
|
103
|
+
mapParagraphs(text, toVisualOf, direction);
|
|
104
|
+
|
|
105
|
+
// Public: visual runs in logical order.
|
|
106
|
+
// mirror: substitute bracket glyphs for odd levels (default true). Set false when
|
|
107
|
+
// the target engine performs its own bidi mirroring (e.g. Pango / node-canvas).
|
|
108
|
+
const visualRuns = (text, { direction = 'auto', mirror = true } = {}) =>
|
|
109
|
+
paragraphs(text).flatMap((p) => {
|
|
110
|
+
const runs = visualRunsOf(p.text, direction, mirror);
|
|
111
|
+
if (p.sep) runs.push({ text: p.sep, rtl: false, level: 0, break: true });
|
|
112
|
+
return runs;
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
// Public: run-level reordered string for shaping engines (pdfkit/pdfmake path).
|
|
116
|
+
// Runs concatenated in visual order; each run stays logical so the engine's own
|
|
117
|
+
// RTL reversal + GSUB shaping produces correct output.
|
|
118
|
+
const reorderForEngine = (text, { direction = 'auto' } = {}) =>
|
|
119
|
+
visualRuns(text, { direction }).map((r) => r.text).join('');
|
|
120
|
+
|
|
121
|
+
// Split one run into placeable pieces: strong text (letters/digits/marks, with
|
|
122
|
+
// whitespace attached) vs neutral islands (brackets, punctuation - bidi class
|
|
123
|
+
// ON/CS/ES/ET/BN). Renderers that reverse by script itemization (fontkit, Pango)
|
|
124
|
+
// scramble neutral islands inside RTL runs, so pieces are placed individually in
|
|
125
|
+
// exact visual order. Within an RTL run the piece order is reversed; each strong
|
|
126
|
+
// piece stays in LOGICAL order (the engine shapes and reverses it internally).
|
|
127
|
+
const NEUTRAL_TYPES = new Set(['ON', 'CS', 'ES', 'ET', 'BN', 'B', 'S']);
|
|
128
|
+
const isArabicIndicDigit = (ch) => /[\u0660-\u0669\u06F0-\u06F9]/.test(ch);
|
|
129
|
+
// Piece model: an RTL run's conformant visual form is its full char-level reversal
|
|
130
|
+
// (UAX#9 L1). Engines reverse strong (same-script letter) text internally, so:
|
|
131
|
+
// - strong letter pieces stay in LOGICAL order (engine reverses + shapes them)
|
|
132
|
+
// - neutral/whitespace pieces are FINAL: chars reversed here, engine must not
|
|
133
|
+
// touch them (common-script items are not reversed by fontkit/Pango)
|
|
134
|
+
// - Arabic-Indic digit pieces are FINAL too: their script is Arabic so engines
|
|
135
|
+
// would reverse them - we pre-reverse so the engine's reversal restores order.
|
|
136
|
+
function splitPieces(runText, rtl, engineName) {
|
|
137
|
+
const b = engine();
|
|
138
|
+
const pieces = [];
|
|
139
|
+
let cur = null;
|
|
140
|
+
const push = (text, kind) => { if (text) pieces.push({ text, kind }); };
|
|
141
|
+
for (const ch of runText) {
|
|
142
|
+
const type = b.getBidiCharTypeName(ch);
|
|
143
|
+
const kind = NEUTRAL_TYPES.has(type) || type === 'WS' ? 'neutral'
|
|
144
|
+
: isArabicIndicDigit(ch) ? 'digits' : 'strong';
|
|
145
|
+
if (cur && cur.kind === kind) cur.text += ch;
|
|
146
|
+
else { if (cur) pieces.push(cur); cur = { text: ch, kind }; }
|
|
147
|
+
}
|
|
148
|
+
if (cur) pieces.push(cur);
|
|
149
|
+
const ordered = rtl ? [...pieces].reverse() : pieces;
|
|
150
|
+
return ordered.map((p) => {
|
|
151
|
+
if (p.kind === 'strong') return { text: p.text, rtl, neutral: false };
|
|
152
|
+
// final pieces: exact visual chars. Both fontkit and Pango reverse
|
|
153
|
+
// Arabic-script items (incl. Arabic-Indic digits) at draw time (verified
|
|
154
|
+
// empirically on both), so digit pieces are always pre-reversed.
|
|
155
|
+
const chars = [...p.text];
|
|
156
|
+
const visual = rtl || p.kind === 'digits' ? chars.reverse().join('') : p.text;
|
|
157
|
+
return { text: visual, rtl, neutral: true };
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// Public: fully decomposed, visual-ordered, placeable pieces for engine renderers.
|
|
162
|
+
// Each piece: { text, rtl, neutral }. Strong pieces are logical order; neutral
|
|
163
|
+
// pieces are final (pre-mirrored when mirror:true). Place left-to-right with
|
|
164
|
+
// measured widths; do not let the engine reorder across pieces.
|
|
165
|
+
const visualPieces = (text, { direction = 'auto', mirror = true, engine: engineName = 'fontkit' } = {}) =>
|
|
166
|
+
visualRuns(text, { direction, mirror }).flatMap((r) => {
|
|
167
|
+
if (r.break) return [r];
|
|
168
|
+
return splitPieces(r.text, r.rtl, engineName).map((p) => ({ text: p.text, rtl: r.rtl, neutral: p.neutral }));
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
module.exports = { toVisual, visualRuns, visualPieces, reorderForEngine };
|
package/src/index.js
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// naskh - Arabic & RTL text preparation for PDF and canvas renderers.
|
|
2
|
+
// Logical order in, renderer-ready output out. See README.md for the integration matrix.
|
|
3
|
+
'use strict';
|
|
4
|
+
|
|
5
|
+
const { shape, unshape, isShaped } = require('./shaping');
|
|
6
|
+
const { toVisual, visualRuns, visualPieces, reorderForEngine } = require('./bidi');
|
|
7
|
+
|
|
8
|
+
// Renderers with their own GSUB shaping + RTL run reversal (verified empirically):
|
|
9
|
+
// give them run-level reordered, mirrored, UNSHAPED text.
|
|
10
|
+
const ENGINE_RENDERERS = new Set(['pdfkit', 'pdfmake']);
|
|
11
|
+
// Renderers with no shaping at all: full shaping + visual order.
|
|
12
|
+
const GENERIC_RENDERERS = new Set(['generic', 'svg', 'raw']);
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Prepare logical-order text for a renderer.
|
|
16
|
+
* @param {string} text logical-order input (never mutated)
|
|
17
|
+
* @param {object} opts
|
|
18
|
+
* renderer: 'pdfkit' | 'pdfmake' | 'generic' (see README for jsPDF/canvas notes)
|
|
19
|
+
* direction: 'auto' | 'rtl' | 'ltr' paragraph base direction
|
|
20
|
+
* assumeShaped: if true, do not normalize pre-shaped input (default false:
|
|
21
|
+
* pre-shaped input is folded back to base letters first, so calling
|
|
22
|
+
* prepare() twice never double-shapes)
|
|
23
|
+
*/
|
|
24
|
+
function prepare(text, { renderer = 'pdfkit', direction = 'auto', assumeShaped = false } = {}) {
|
|
25
|
+
if (typeof text !== 'string') throw new TypeError('naskh: text must be a string');
|
|
26
|
+
let t = text;
|
|
27
|
+
if (!assumeShaped && isShaped(t)) {
|
|
28
|
+
// Double-application guard: text already carries presentation forms.
|
|
29
|
+
// For generic renderers it is already fully prepared: return it unchanged
|
|
30
|
+
// (makes prepare() idempotent on its own output). For engine renderers we
|
|
31
|
+
// can only fold back to base letters; note that bidi order of pre-shaped
|
|
32
|
+
// visual text cannot be recovered reliably - do not prepare() twice. See LIMITATIONS.
|
|
33
|
+
if (GENERIC_RENDERERS.has(renderer)) return t;
|
|
34
|
+
t = unshape(t);
|
|
35
|
+
}
|
|
36
|
+
if (ENGINE_RENDERERS.has(renderer)) return reorderForEngine(t, { direction });
|
|
37
|
+
if (GENERIC_RENDERERS.has(renderer)) return toVisual(shape(t), { direction });
|
|
38
|
+
throw new RangeError(`naskh: unknown renderer "${renderer}" (see README integration matrix)`);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
module.exports = {
|
|
42
|
+
prepare,
|
|
43
|
+
shape,
|
|
44
|
+
unshape,
|
|
45
|
+
isShaped,
|
|
46
|
+
toVisual,
|
|
47
|
+
visualRuns,
|
|
48
|
+
visualPieces,
|
|
49
|
+
reorderForEngine,
|
|
50
|
+
version: require('../package.json').version,
|
|
51
|
+
};
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// naskh pdfkit integration: run-placed bidi text.
|
|
2
|
+
// pdfkit/fontkit shapes and reverses each single-direction run correctly on its own,
|
|
3
|
+
// but has no cross-run bidi. We compute UAX#9 visual runs (bidi-js), then place each
|
|
4
|
+
// run left-to-right with measured widths. Works for mixed Arabic/Latin/digits/parens.
|
|
5
|
+
'use strict';
|
|
6
|
+
|
|
7
|
+
const { visualPieces } = require('../bidi');
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Draw (possibly mixed-direction) text into a pdfkit document.
|
|
11
|
+
* Set font and fontSize BEFORE calling. x/y: the anchor point.
|
|
12
|
+
* opts:
|
|
13
|
+
* direction: 'auto' | 'rtl' | 'ltr' (base paragraph direction)
|
|
14
|
+
* align: 'left' | 'right' (anchor side; RTL text is usually 'right')
|
|
15
|
+
* maxWidth: optional; if the measured line is wider, it is left as-is (no wrap in v0.1)
|
|
16
|
+
* Returns the total painted width.
|
|
17
|
+
*/
|
|
18
|
+
function drawText(doc, text, x, y, { direction = 'auto', align = 'left' } = {}) {
|
|
19
|
+
const pieces = visualPieces(text, { direction }).filter((r) => !r.break);
|
|
20
|
+
const widths = pieces.map((p) => doc.widthOfString(p.text));
|
|
21
|
+
const total = widths.reduce((a, b) => a + b, 0);
|
|
22
|
+
let cursor = align === 'right' ? x - total : x;
|
|
23
|
+
pieces.forEach((p, i) => {
|
|
24
|
+
doc.text(p.text, cursor, y, { lineBreak: false, continued: false });
|
|
25
|
+
cursor += widths[i];
|
|
26
|
+
});
|
|
27
|
+
return total;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Draw multiple paragraphs (splits on newlines). Returns final y.
|
|
32
|
+
*/
|
|
33
|
+
function drawParagraphs(doc, text, x, y, { direction = 'auto', align = 'left', lineGap } = {}) {
|
|
34
|
+
const lines = String(text).split(/\r\n|[\n\r\u2028\u2029]/);
|
|
35
|
+
let cy = y;
|
|
36
|
+
for (const line of lines) {
|
|
37
|
+
drawText(doc, line, x, cy, { direction, align });
|
|
38
|
+
cy += lineGap !== undefined ? lineGap : doc.currentLineHeight(true);
|
|
39
|
+
}
|
|
40
|
+
return cy;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
module.exports = { drawText, drawParagraphs };
|
package/src/shaping.js
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
// naskh - Arabic contextual shaping (logical base letters -> Arabic Presentation Forms-B).
|
|
2
|
+
// Pure, dependency-free, O(n). Works on logical-order text; never reorders.
|
|
3
|
+
// Scope: Arabic block U+0621..U+064A, tatweel, lam-alef ligatures, combining marks
|
|
4
|
+
// pass through untouched. Letters outside the table (e.g. Persian-only letters) pass
|
|
5
|
+
// through unshaped - see LIMITATIONS.md.
|
|
6
|
+
|
|
7
|
+
'use strict';
|
|
8
|
+
|
|
9
|
+
// codepoint: [isolated, final, initial, medial] (null = no such form / does not join)
|
|
10
|
+
const SHAPING = {
|
|
11
|
+
0x0621: [0xFE80, null, null, null], // hamza
|
|
12
|
+
0x0622: [0xFE81, 0xFE82, null, null], // alef madda
|
|
13
|
+
0x0623: [0xFE83, 0xFE84, null, null], // alef hamza above
|
|
14
|
+
0x0624: [0xFE85, 0xFE86, null, null], // waw hamza
|
|
15
|
+
0x0625: [0xFE87, 0xFE88, null, null], // alef hamza below
|
|
16
|
+
0x0626: [0xFE89, 0xFE8A, 0xFE8B, 0xFE8C], // yeh hamza
|
|
17
|
+
0x0627: [0xFE8D, 0xFE8E, null, null], // alef
|
|
18
|
+
0x0628: [0xFE8F, 0xFE90, 0xFE91, 0xFE92], // beh
|
|
19
|
+
0x0629: [0xFE93, 0xFE94, null, null], // teh marbuta
|
|
20
|
+
0x062A: [0xFE95, 0xFE96, 0xFE97, 0xFE98], // teh
|
|
21
|
+
0x062B: [0xFE99, 0xFE9A, 0xFE9B, 0xFE9C], // theh
|
|
22
|
+
0x062C: [0xFE9D, 0xFE9E, 0xFE9F, 0xFEA0], // jeem
|
|
23
|
+
0x062D: [0xFEA1, 0xFEA2, 0xFEA3, 0xFEA4], // hah
|
|
24
|
+
0x062E: [0xFEA5, 0xFEA6, 0xFEA7, 0xFEA8], // khah
|
|
25
|
+
0x062F: [0xFEA9, 0xFEAA, null, null], // dal
|
|
26
|
+
0x0630: [0xFEAB, 0xFEAC, null, null], // thal
|
|
27
|
+
0x0631: [0xFEAD, 0xFEAE, null, null], // reh
|
|
28
|
+
0x0632: [0xFEAF, 0xFEB0, null, null], // zain
|
|
29
|
+
0x0633: [0xFEB1, 0xFEB2, 0xFEB3, 0xFEB4], // seen
|
|
30
|
+
0x0634: [0xFEB5, 0xFEB6, 0xFEB7, 0xFEB8], // sheen
|
|
31
|
+
0x0635: [0xFEB9, 0xFEBA, 0xFEBB, 0xFEBC], // sad
|
|
32
|
+
0x0636: [0xFEBD, 0xFEBE, 0xFEBF, 0xFEC0], // dad
|
|
33
|
+
0x0637: [0xFEC1, 0xFEC2, 0xFEC3, 0xFEC4], // tah
|
|
34
|
+
0x0638: [0xFEC5, 0xFEC6, 0xFEC7, 0xFEC8], // zah
|
|
35
|
+
0x0639: [0xFEC9, 0xFECA, 0xFECB, 0xFECC], // ain
|
|
36
|
+
0x063A: [0xFECD, 0xFECE, 0xFECF, 0xFED0], // ghain
|
|
37
|
+
0x0640: [0x0640, 0x0640, 0x0640, 0x0640], // tatweel (joins both ways)
|
|
38
|
+
0x0641: [0xFED1, 0xFED2, 0xFED3, 0xFED4], // feh
|
|
39
|
+
0x0642: [0xFED5, 0xFED6, 0xFED7, 0xFED8], // qaf
|
|
40
|
+
0x0643: [0xFED9, 0xFEDA, 0xFEDB, 0xFEDC], // kaf
|
|
41
|
+
0x0644: [0xFEDD, 0xFEDE, 0xFEDF, 0xFEE0], // lam
|
|
42
|
+
0x0645: [0xFEE1, 0xFEE2, 0xFEE3, 0xFEE4], // meem
|
|
43
|
+
0x0646: [0xFEE5, 0xFEE6, 0xFEE7, 0xFEE8], // noon
|
|
44
|
+
0x0647: [0xFEE9, 0xFEEA, 0xFEEB, 0xFEEC], // heh
|
|
45
|
+
0x0648: [0xFEED, 0xFEEE, null, null], // waw
|
|
46
|
+
0x0649: [0xFEEF, 0xFEF0, null, null], // alef maksura
|
|
47
|
+
0x064A: [0xFEF1, 0xFEF2, 0xFEF3, 0xFEF4], // yeh
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
// lam-alef mandatory ligatures: alefCode -> [isolated, final]
|
|
51
|
+
const LAM_ALEF = {
|
|
52
|
+
0x0622: [0xFEF5, 0xFEF6],
|
|
53
|
+
0x0623: [0xFEF7, 0xFEF8],
|
|
54
|
+
0x0625: [0xFEF9, 0xFEFA],
|
|
55
|
+
0x0627: [0xFEFB, 0xFEFC],
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
const isArabicLetter = (cp) => cp >= 0x0621 && cp <= 0x064A;
|
|
59
|
+
const isCombiningMark = (cp) =>
|
|
60
|
+
(cp >= 0x064B && cp <= 0x065F) || cp === 0x0670 || (cp >= 0x06D6 && cp <= 0x06DC);
|
|
61
|
+
const joinsAfter = (cp) => { const s = SHAPING[cp]; return !!s && s[2] !== null; };
|
|
62
|
+
const joinsBefore = (cp) => { const s = SHAPING[cp]; return !!s && s[1] !== null; };
|
|
63
|
+
|
|
64
|
+
// Shape one maximal run of Arabic letters (with interleaved combining marks).
|
|
65
|
+
// cps: array of codepoints (a single word, no spaces).
|
|
66
|
+
function shapeRun(cps) {
|
|
67
|
+
const out = [];
|
|
68
|
+
const consumed = new Set();
|
|
69
|
+
for (let i = 0; i < cps.length; i++) {
|
|
70
|
+
if (consumed.has(i)) continue;
|
|
71
|
+
const cp = cps[i];
|
|
72
|
+
if (!isArabicLetter(cp)) { out.push(cp); continue; }
|
|
73
|
+
// neighbors, skipping combining marks
|
|
74
|
+
let pi = i - 1; while (pi >= 0 && (isCombiningMark(cps[pi]) || consumed.has(pi))) pi--;
|
|
75
|
+
let ni = i + 1; while (ni < cps.length && isCombiningMark(cps[ni])) ni++;
|
|
76
|
+
let prev = pi >= 0 && isArabicLetter(cps[pi]) ? cps[pi] : null;
|
|
77
|
+
// a lam already consumed into a lam-alef ligature cannot join to the next letter
|
|
78
|
+
if (prev === 0x0644) {
|
|
79
|
+
let li = pi + 1; while (li < cps.length && isCombiningMark(cps[li])) li++;
|
|
80
|
+
if (li < cps.length && LAM_ALEF[cps[li]]) prev = null;
|
|
81
|
+
}
|
|
82
|
+
const next = ni < cps.length && isArabicLetter(cps[ni]) ? cps[ni] : null;
|
|
83
|
+
const joinPrev = prev !== null && joinsAfter(prev) && joinsBefore(cp);
|
|
84
|
+
// mandatory lam-alef ligature (joining context: lam would join next alef)
|
|
85
|
+
if (cp === 0x0644 && next !== null && LAM_ALEF[next] && joinsBefore(next)) {
|
|
86
|
+
const lig = LAM_ALEF[next][joinPrev ? 1 : 0];
|
|
87
|
+
consumed.add(ni);
|
|
88
|
+
out.push(lig);
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
const joinNext = next !== null && joinsAfter(cp) && joinsBefore(next) &&
|
|
92
|
+
!(cp === 0x0644 && LAM_ALEF[next]); // lam before alef is consumed above
|
|
93
|
+
const forms = SHAPING[cp];
|
|
94
|
+
let form;
|
|
95
|
+
if (joinPrev && joinNext) form = forms[3];
|
|
96
|
+
else if (joinPrev) form = forms[1];
|
|
97
|
+
else if (joinNext) form = forms[2];
|
|
98
|
+
else form = forms[0];
|
|
99
|
+
out.push(form !== null && form !== undefined ? form : forms[0]);
|
|
100
|
+
}
|
|
101
|
+
return out;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// Contextually shape all Arabic words in `text` (logical order in, logical order out).
|
|
105
|
+
function shape(text) {
|
|
106
|
+
const cps = [...text].map((c) => c.codePointAt(0));
|
|
107
|
+
const out = [];
|
|
108
|
+
let run = [];
|
|
109
|
+
const flush = () => { if (run.length) { out.push(...shapeRun(run)); run = []; } };
|
|
110
|
+
for (const cp of cps) {
|
|
111
|
+
if (isArabicLetter(cp) || (isCombiningMark(cp) && run.length)) run.push(cp);
|
|
112
|
+
else { flush(); out.push(cp); }
|
|
113
|
+
}
|
|
114
|
+
flush();
|
|
115
|
+
return String.fromCodePoint(...out);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const PRESENTATION_RE = /[\uFB50-\uFDFF\uFE70-\uFEFF]/;
|
|
119
|
+
|
|
120
|
+
// True if the string already contains Arabic presentation forms (already shaped).
|
|
121
|
+
const isShaped = (text) => PRESENTATION_RE.test(text);
|
|
122
|
+
|
|
123
|
+
// Reverse of shape(): presentation forms -> base letters (NFKC folds them back).
|
|
124
|
+
// Fold Arabic presentation forms back to base letters WITHOUT touching the rest
|
|
125
|
+
// of the string (a global NFKC would also compose unrelated sequences, e.g.
|
|
126
|
+
// decomposed latin accents, changing the user's original text).
|
|
127
|
+
const PRESENTATION_ONLY = /[\uFB50-\uFDFF\uFE70-\uFEFF]/g;
|
|
128
|
+
const unshape = (text) =>
|
|
129
|
+
text.replace(PRESENTATION_ONLY, (ch) => ch.normalize('NFKC'));
|
|
130
|
+
|
|
131
|
+
module.exports = { shape, unshape, isShaped, isCombiningMark, isArabicLetter, SHAPING, LAM_ALEF };
|