diff --git a/CHANGELOG.md b/CHANGELOG.md index 75a703c..e8e944e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,10 +24,10 @@ ### Changes - [improvements] עברית: מנגנון עדכון מובנה עם הורדה ישירה ללא פתיחת דפדפן חיצוני, כתיבה אטומית לקובץ ‎.part, מדדי מהירות ו-ETA ואימות SHA-256 בזמן הורדה | en: Browserless in-app updater with direct streaming download, atomic .part file handling, live speed/ETA, and streaming SHA-256 verification -- [security] עברית: אימות כותרת PE ‏(MZ), גודל מינימלי ותקינות קובץ לפני הפעלת המתקין | en: Validate PE (MZ) header, minimum file size, and installer integrity before execution +- [improvements] עברית: אימות כותרת PE ‏(MZ), גודל מינימלי ותקינות קובץ לפני הפעלת המתקין | en: Validate PE (MZ) header, minimum file size, and installer integrity before execution - [features] עברית: סריקה עמוקה של כוננים חיצוניים ותיקיות מתקינים נפוצות, השוואת SemVer והמלצה על גרסה חדשה | en: Deep external-drive and common installer-folder discovery with SemVer comparison and newest-candidate recommendation - [improvements] עברית: הפעלה מנותקת של המתקין וסגירה מסודרת של התוכנה לשחרור נעילות קבצים | en: Detached installer execution and clean application shutdown to release binary locks -- [tests] עברית: הוספת 11 בדיקות יחידה ורגרסיה למנוע העדכון, אימות PE, SHA-256 וגישור IPC | en: Added 11 unit and regression tests for updater engine, PE validation, SHA-256, and IPC bridge contracts +- [improvements] עברית: הוספת 11 בדיקות יחידה ורגרסיה למנוע העדכון, אימות PE, SHA-256 וגישור IPC | en: Added 11 unit and regression tests for updater engine, PE validation, SHA-256, and IPC bridge contracts - [fixes] עברית: תיקון אתחול ContextualInspector והעברת setFlows לאחר יצירת inspector, לתיקון יצירת מסמכים וייבוא DOCX ב-Issue #28 | en: Fix ContextualInspector initialization order and call setFlows after inspector creation, resolving document creation and DOCX import failures in Issue #28 --- diff --git a/crates/tok-pdf/assets/icc/a2b.bin b/crates/tok-pdf/assets/icc/a2b.bin new file mode 100644 index 0000000..088a0e9 Binary files /dev/null and b/crates/tok-pdf/assets/icc/a2b.bin differ diff --git a/crates/tok-pdf/assets/icc/b2a.bin b/crates/tok-pdf/assets/icc/b2a.bin new file mode 100644 index 0000000..3f4e5aa Binary files /dev/null and b/crates/tok-pdf/assets/icc/b2a.bin differ diff --git a/crates/tok-pdf/assets/icc/gen_icc_luts.py b/crates/tok-pdf/assets/icc/gen_icc_luts.py new file mode 100644 index 0000000..e4edaf5 --- /dev/null +++ b/crates/tok-pdf/assets/icc/gen_icc_luts.py @@ -0,0 +1,152 @@ +#!/usr/bin/env python3 +""" +Generates the two colour-transform tags embedded in every ICC profile that the +PDF engine writes (`crates/tok-pdf/src/color.rs`): + + * a2b.bin - `mft2` (lut16Type) tag data: CMYK -> Lab (PCS), 9^4 grid + * b2a.bin - `mft2` (lut16Type) tag data: Lab -> CMYK, 9^3 grid + +The model is a generic, deterministic, subtractive approximation (it is NOT a +characterisation of a real press condition such as FOGRA39). Run this script +to regenerate the files; the output is byte-for-byte reproducible. + + python3 gen_icc_luts.py +""" +import struct +import sys +from pathlib import Path + +A2B_GRID = 9 +B2A_GRID = 9 + +# D50 reference white +XN, YN, ZN = 0.9642, 1.0, 0.8249 + + +def srgb_to_linear(v): + return v / 12.92 if v <= 0.04045 else ((v + 0.055) / 1.055) ** 2.4 + + +def linear_to_srgb(v): + v = min(max(v, 0.0), 1.0) + return 12.92 * v if v <= 0.0031308 else 1.055 * (v ** (1 / 2.4)) - 0.055 + + +def rgb_to_xyz_d50(r, g, b): + rl, gl, bl = srgb_to_linear(r), srgb_to_linear(g), srgb_to_linear(b) + # sRGB (D65) -> XYZ, then Bradford adaptation to D50 (combined matrix, as in the sRGB D50 profile) + x = 0.4360747 * rl + 0.3850649 * gl + 0.1430804 * bl + y = 0.2225045 * rl + 0.7168786 * gl + 0.0606169 * bl + z = 0.0139322 * rl + 0.0971045 * gl + 0.7141733 * bl + return x, y, z + + +def xyz_d50_to_rgb(x, y, z): + rl = 3.1338561 * x - 1.6168667 * y - 0.4906146 * z + gl = -0.9787684 * x + 1.9161415 * y + 0.0334540 * z + bl = 0.0719453 * x - 0.2289914 * y + 1.4052427 * z + return linear_to_srgb(rl), linear_to_srgb(gl), linear_to_srgb(bl) + + +def f(t): + return t ** (1 / 3) if t > 216 / 24389 else (24389 / 27 * t + 16) / 116 + + +def finv(t): + return t ** 3 if t ** 3 > 216 / 24389 else (116 * t - 16) / (24389 / 27) + + +def xyz_to_lab(x, y, z): + fx, fy, fz = f(x / XN), f(y / YN), f(z / ZN) + return 116 * fy - 16, 500 * (fx - fy), 200 * (fy - fz) + + +def lab_to_xyz(l, a, b): + fy = (l + 16) / 116 + fx, fz = fy + a / 500, fy - b / 200 + return XN * finv(fx), YN * finv(fy), ZN * finv(fz) + + +def cmyk_to_rgb(c, m, y, k): + return (1 - c) * (1 - k), (1 - m) * (1 - k), (1 - y) * (1 - k) + + +def rgb_to_cmyk(r, g, b): + r, g, b = (min(max(v, 0.0), 1.0) for v in (r, g, b)) + k = 1 - max(r, g, b) + if k >= 1 - 1e-9: + return 0.0, 0.0, 0.0, 1.0 + d = 1 - k + return (1 - r - k) / d, (1 - g - k) / d, (1 - b - k) / d, k + + +def u16(v): + return int(min(max(round(v), 0), 65535)) + + +# ICC v2 legacy 16-bit Lab encoding +def enc_l(l): + return u16(l * 65280 / 100) + + +def enc_ab(a): + return u16((a + 128) * 256) + + +def dec_l(v): + return v * 100 / 65280 + + +def dec_ab(v): + return v / 256 - 128 + + +def lut16(in_ch, out_ch, grid, clut): + """Assembles an `mft2` tag: identity matrix, 2-entry identity input/output tables.""" + out = bytearray() + out += b"mft2" + bytes(4) + out += bytes([in_ch, out_ch, grid, 0]) + for i in range(9): + out += struct.pack(">i", 0x00010000 if i % 4 == 0 else 0) + out += struct.pack(">HH", 2, 2) + for _ in range(in_ch): + out += struct.pack(">HH", 0, 65535) + out += b"".join(struct.pack(">H", v) for v in clut) + for _ in range(out_ch): + out += struct.pack(">HH", 0, 65535) + return bytes(out) + + +def build_a2b(): + clut = [] + n = A2B_GRID - 1 + for ci in range(A2B_GRID): + for mi in range(A2B_GRID): + for yi in range(A2B_GRID): + for ki in range(A2B_GRID): + r, g, b = cmyk_to_rgb(ci / n, mi / n, yi / n, ki / n) + l, a, bb = xyz_to_lab(*rgb_to_xyz_d50(r, g, b)) + clut += [enc_l(l), enc_ab(a), enc_ab(bb)] + return lut16(4, 3, A2B_GRID, clut) + + +def build_b2a(): + clut = [] + n = B2A_GRID - 1 + for li in range(B2A_GRID): + for ai in range(B2A_GRID): + for bi in range(B2A_GRID): + l = dec_l(li / n * 65280) + a = dec_ab(ai / n * 65280) + b = dec_ab(bi / n * 65280) + r, g, bl = xyz_d50_to_rgb(*lab_to_xyz(l, a, b)) + c, m, y, k = rgb_to_cmyk(r, g, bl) + clut += [u16(c * 65535), u16(m * 65535), u16(y * 65535), u16(k * 65535)] + return lut16(3, 4, B2A_GRID, clut) + + +if __name__ == "__main__": + out_dir = Path(sys.argv[1] if len(sys.argv) > 1 else ".") + out_dir.mkdir(parents=True, exist_ok=True) + (out_dir / "a2b.bin").write_bytes(build_a2b()) + (out_dir / "b2a.bin").write_bytes(build_b2a()) diff --git a/crates/tok-pdf/src/color.rs b/crates/tok-pdf/src/color.rs index bf272e6..ecb8e0f 100644 --- a/crates/tok-pdf/src/color.rs +++ b/crates/tok-pdf/src/color.rs @@ -262,13 +262,22 @@ impl ColorManagementEngine { } } - /// Generates a valid ISO 15076-1 binary ICC v2.4 `prtr` `CMYK -> Lab` Output Profile - /// for embedding in the PDF/X `DestOutputProfile` stream (`N = 4`). + /// Generates a binary ICC v2.4 `prtr` `CMYK -> Lab` Output Profile for embedding in the + /// PDF/X `DestOutputProfile` stream (`N = 4`). + /// + /// The profile carries real colour transforms (`A2B0..2` and `B2A0..2`, both `lut16Type`) so + /// that colour-managed viewers can build a transform from it. They come from a generic + /// subtractive model (see `assets/icc/gen_icc_luts.py`), not from a measured press condition, + /// and the description says so. pub fn generate_icc_profile_bytes(profile: IccProfileId) -> Vec { - let desc_str = profile.info(); + // CMYK -> Lab and Lab -> CMYK `lut16Type` tag data. + const A2B_LUT: &[u8] = include_bytes!("../assets/icc/a2b.bin"); + const B2A_LUT: &[u8] = include_bytes!("../assets/icc/b2a.bin"); + + let desc_str = format!("TypesetOK approximation of {}", profile.info()); let cprt_str = "Copyright TypesetOK Pre-Press Color Engine (ISO 15076-1)"; - // Build `desc` tag (type 'desc') + // Build `desc` tag (type 'desc', textDescriptionType) let mut desc_tag = Vec::new(); desc_tag.extend_from_slice(b"desc"); desc_tag.extend_from_slice(&[0u8; 4]); @@ -276,11 +285,9 @@ impl ColorManagementEngine { desc_tag.extend_from_slice(&ascii_len.to_be_bytes()); desc_tag.extend_from_slice(desc_str.as_bytes()); desc_tag.push(0); - // Unicode & ScriptCode placeholders (67 bytes per ICC v2 spec) - desc_tag.extend_from_slice(&[0u8; 67]); - while desc_tag.len() % 4 != 0 { - desc_tag.push(0); - } + // Unicode language code + count (4 + 4), ScriptCode code + count + 67-byte buffer + // (2 + 1 + 67): 78 bytes, as the ICC v2 specification requires. + desc_tag.extend_from_slice(&[0u8; 78]); // Build `cprt` tag (type 'text') let mut cprt_tag = Vec::new(); @@ -288,9 +295,6 @@ impl ColorManagementEngine { cprt_tag.extend_from_slice(&[0u8; 4]); cprt_tag.extend_from_slice(cprt_str.as_bytes()); cprt_tag.push(0); - while cprt_tag.len() % 4 != 0 { - cprt_tag.push(0); - } // Build `wtpt` tag (type 'XYZ ', D50 standard illuminant: X=0.9642, Y=1.0000, Z=0.8249) let mut wtpt_tag = Vec::with_capacity(20); @@ -300,13 +304,32 @@ impl ColorManagementEngine { wtpt_tag.extend_from_slice(&0x0001_0000u32.to_be_bytes()); // 1.0000 in s15Fixed16 wtpt_tag.extend_from_slice(&0x0000_D32Du32.to_be_bytes()); // 0.8249 in s15Fixed16 + // Distinct data blocks, stored in this order. Every block starts on a 4-byte boundary. + let blocks: [&[u8]; 5] = [&desc_tag, &cprt_tag, &wtpt_tag, A2B_LUT, B2A_LUT]; + // Tag table: signature and the block it points at. The three rendering intents of each + // transform share one block. + let tags: [(&[u8; 4], usize); 9] = [ + (b"desc", 0), + (b"cprt", 1), + (b"wtpt", 2), + (b"A2B0", 3), + (b"A2B1", 3), + (b"A2B2", 3), + (b"B2A0", 4), + (b"B2A1", 4), + (b"B2A2", 4), + ]; + let header_size = 128u32; - let tag_count = 3u32; + let tag_count = tags.len() as u32; let tag_table_size = 4 + tag_count * 12; - let desc_offset = header_size + tag_table_size; - let cprt_offset = desc_offset + desc_tag.len() as u32; - let wtpt_offset = cprt_offset + cprt_tag.len() as u32; - let total_size = wtpt_offset + wtpt_tag.len() as u32; + let mut offsets = [0u32; 5]; + let mut cursor = header_size + tag_table_size; + for (offset, block) in offsets.iter_mut().zip(blocks.iter()) { + *offset = cursor; + cursor += (block.len() as u32 + 3) & !3; + } + let total_size = cursor; let mut icc = Vec::with_capacity(total_size as usize); @@ -338,23 +361,18 @@ impl ColorManagementEngine { // Tag Table icc.extend_from_slice(&tag_count.to_be_bytes()); - // Tag 1: 'desc' - icc.extend_from_slice(b"desc"); - icc.extend_from_slice(&desc_offset.to_be_bytes()); - icc.extend_from_slice(&(desc_tag.len() as u32).to_be_bytes()); - // Tag 2: 'cprt' - icc.extend_from_slice(b"cprt"); - icc.extend_from_slice(&cprt_offset.to_be_bytes()); - icc.extend_from_slice(&(cprt_tag.len() as u32).to_be_bytes()); - // Tag 3: 'wtpt' - icc.extend_from_slice(b"wtpt"); - icc.extend_from_slice(&wtpt_offset.to_be_bytes()); - icc.extend_from_slice(&(wtpt_tag.len() as u32).to_be_bytes()); + for &(signature, block_index) in &tags { + icc.extend_from_slice(signature); + icc.extend_from_slice(&offsets[block_index].to_be_bytes()); + icc.extend_from_slice(&(blocks[block_index].len() as u32).to_be_bytes()); + } // Tag Data - icc.extend_from_slice(&desc_tag); - icc.extend_from_slice(&cprt_tag); - icc.extend_from_slice(&wtpt_tag); + for block in blocks { + icc.extend_from_slice(block); + let padding = (4 - block.len() % 4) % 4; + icc.extend_from_slice(&[0u8; 3][..padding]); + } icc } @@ -436,5 +454,29 @@ mod tests { assert_eq!(&icc_bytes[12..16], b"prtr"); assert_eq!(&icc_bytes[16..20], b"CMYK"); assert_eq!(&icc_bytes[36..40], b"acsp"); + + // The profile must be structurally consistent and carry both colour transforms. + let be32 = |at: usize| u32::from_be_bytes(icc_bytes[at..at + 4].try_into().unwrap()); + assert_eq!(be32(0) as usize, icc_bytes.len(), "profile size field"); + let tag_count = be32(128) as usize; + assert_eq!(tag_count, 9); + let mut signatures = Vec::new(); + for i in 0..tag_count { + let entry = 132 + i * 12; + let (offset, size) = (be32(entry + 4) as usize, be32(entry + 8) as usize); + assert_eq!(offset % 4, 0, "tag data must be 4-byte aligned"); + assert!( + offset + size <= icc_bytes.len(), + "tag data inside the profile" + ); + signatures.push(icc_bytes[entry..entry + 4].to_vec()); + if icc_bytes[entry..entry + 4] == *b"A2B0" { + assert_eq!(&icc_bytes[offset..offset + 4], b"mft2"); + assert_eq!(icc_bytes[offset + 8], 4, "A2B0 has 4 input channels (CMYK)"); + assert_eq!(icc_bytes[offset + 9], 3, "A2B0 has 3 output channels (Lab)"); + } + } + assert!(signatures.iter().any(|s| s == b"A2B0")); + assert!(signatures.iter().any(|s| s == b"B2A0")); } } diff --git a/crates/tok-pdf/src/pdf_engine.rs b/crates/tok-pdf/src/pdf_engine.rs index d1b8b7e..8c26ae1 100644 --- a/crates/tok-pdf/src/pdf_engine.rs +++ b/crates/tok-pdf/src/pdf_engine.rs @@ -834,35 +834,46 @@ impl PdfPrePressEngine { if let Some(slot) = registry.legacy { let font = &embedded[slot]; let folio_font_size = 10.0; - let cids: Vec = p_box + // Each glyph with its advance, in logical (reading) order. + let glyphs: Vec<(u16, f32)> = p_box .page_number_gematria .chars() .filter_map(|ch| legacy_face.glyph_index(ch)) .filter_map(|gid| font.cid(gid.0)) - .flat_map(u16::to_be_bytes) + .map(|cid| { + let adv = font + .subset + .cid_widths_1000 + .get(usize::from(cid)) + .copied() + .unwrap_or(500.0); + (cid, adv / 1000.0 * folio_font_size) + }) .collect(); - if !cids.is_empty() { - let total_width: f32 = p_box + if !glyphs.is_empty() { + let total_width: f32 = glyphs.iter().map(|(_, adv)| *adv).sum(); + let left_x = origin_x + (p_box.dimensions.width - total_width) / 2.0; + let folio_y = origin_y + 25.0; + // A Hebrew numeral (e.g. "י״א") reads right to left. The glyphs stay in + // logical order in the stream, so copy and search give the right text, and + // each one is placed explicitly so the geresh and gershayim land on the left. + let is_rtl = p_box .page_number_gematria .chars() - .filter_map(|ch| legacy_face.glyph_index(ch)) - .filter_map(|gid| font.cid(gid.0)) - .map(|cid| { - let adv = font - .subset - .cid_widths_1000 - .get(usize::from(cid)) - .copied() - .unwrap_or(500.0); - adv / 1000.0 * folio_font_size - }) - .sum(); - let folio_x = origin_x + (p_box.dimensions.width - total_width) / 2.0; - let folio_y = origin_y + 25.0; + .any(|ch| ('\u{0590}'..='\u{05FF}').contains(&ch)); + let mut pen_x = if is_rtl { left_x + total_width } else { left_x }; content.begin_text(); content.set_font(Name(font.resource.as_bytes()), folio_font_size); - content.set_text_matrix([1.0, 0.0, 0.0, 1.0, folio_x, folio_y]); - content.show(Str(&cids)); + for (cid, adv) in &glyphs { + if is_rtl { + pen_x -= *adv; + } + content.set_text_matrix([1.0, 0.0, 0.0, 1.0, pen_x, folio_y]); + content.show(Str(&cid.to_be_bytes())); + if !is_rtl { + pen_x += *adv; + } + } content.end_text(); } } @@ -1101,9 +1112,20 @@ mod tests { .unwrap(); assert!(bytes.starts_with(b"%PDF-")); // The heuristic glyph is drawn through the legacy font by character. + // Ignore embedded font/resource streams: their binary bytes may contain + // the byte sequence "TJ" even though it is not a PDF text operator. let decompressed = decompress_flate_streams(&bytes); - let tj_count: usize = decompressed.iter().map(|st| count(st, b"TJ")).sum(); - assert_eq!(tj_count, 1); + // A PDF content stream starts its text object with the BT operator. + // Do not require a particular newline after ET: pdf-writer may serialize + // the closing operator with different whitespace. + let text_streams = decompressed + .iter() + .filter(|stream| stream.windows(3).any(|window| window == b"BT\n")); + let tj_count: usize = text_streams.map(|stream| count(stream, b"TJ")).sum(); + assert_eq!( + tj_count, 1, + "Expected exactly one text-show operator for the supported fallback glyph" + ); } #[test] diff --git a/crates/tok-typeset/src/polygon_flow.rs b/crates/tok-typeset/src/polygon_flow.rs index 68e4322..e090897 100644 --- a/crates/tok-typeset/src/polygon_flow.rs +++ b/crates/tok-typeset/src/polygon_flow.rs @@ -320,20 +320,19 @@ mod tests { ); // First 4 lines should fall in the upper band (x_offset = 200, span width = 100) - for i in 0..4 { - let l = &result.lines[i]; + for (i, line) in result.lines.iter().take(4).enumerate() { assert_eq!( - l.x_offset, 200.0, + line.x_offset, 200.0, "Line {} x_offset should be in upper band", i ); assert!( - l.width <= 100.5, + line.width <= 100.5, "Line {} width ({}) exceeded upper band width 100", i, - l.width + line.width ); - assert_eq!(l.baseline_y, ((i + 1) as f32) * 15.0); + assert_eq!(line.baseline_y, ((i + 1) as f32) * 15.0); } // Line 4 and subsequent lines should transition into lower expanded band (x_offset = 0, span width = 300) diff --git a/packages/tok-ui/src/app.ts b/packages/tok-ui/src/app.ts index a7fed80..ac239d0 100644 --- a/packages/tok-ui/src/app.ts +++ b/packages/tok-ui/src/app.ts @@ -39,8 +39,10 @@ import { import { documentStateToDocumentRoot, documentRootToDocumentState, - importResultToDocumentState + importResultToDocumentState, + stripHtmlTags } from './engine/documentBridge'; +import type { LineRunLookup, LineRunSource } from './engine/lineRuns'; import { importDocument, parseDocxXml, ImportResult } from './engine/textImporter'; import { layoutToPageDescriptors } from './engine/typesetBridge'; @@ -570,6 +572,11 @@ export class TypesetOkApp { this.showToast(t('toastPreflightOk')); }, onWordCountClick: () => this.openTextStatsDialog(), + onPageClick: () => { + if (this.currentViewMode === 'canvas') return; + this.setViewMode('canvas'); + this.topBar?.setViewMode('canvas'); + }, onExportPdf: () => this.handleSystemAction('export-pdf') }); this.root.appendChild(this.statusBar.element); @@ -964,6 +971,26 @@ export class TypesetOkApp { return key ? t(key) : canonical; } + /** Paragraph formatting that page view paints on top of the engine's line text. */ + private buildLineRunLookup(): LineRunLookup { + const sources = new Map(); + for (const paragraphs of Object.values(this.documentState.flows)) { + for (const p of paragraphs || []) { + const spans = p.spans || []; + const color = p.patch?.color; + if (!p.id || (spans.length === 0 && !color)) continue; + sources.set(p.id, { text: stripHtmlTags(p.text || ''), spans, color }); + } + } + return (paragraphId) => sources.get(paragraphId); + } + + /** Shows the flow that is really being edited in the status bar. Call after the active flow or the flow list changes. */ + private syncStatusBarFlow(): void { + if (!this.statusBar || !this.activeFlowId) return; + this.statusBar.updateStats({ activeFlow: this.flowDisplayName(this.activeFlowId) }); + } + private get welcomeModal(): WelcomeModal { if (!this.welcomeModalInstance) { this.welcomeModalInstance = new WelcomeModal({ @@ -2103,7 +2130,10 @@ export class TypesetOkApp { pageIndex: p.pageIndex, gematria: p.gematriaNumber, label: tf('appPageThumb', { page: p.gematriaNumber }), - isSpreadRight: isRightHandPage(idx) + isSpreadRight: isRightHandPage(idx), + htmlContent: p.htmlContent, + widthPt: p.widthPt, + heightPt: p.heightPt })), this.activePageIndex ); @@ -2235,7 +2265,7 @@ export class TypesetOkApp { return; } if (res && res.success && Array.isArray(res.pages)) { - newPages = layoutToPageDescriptors(res.pages); + newPages = layoutToPageDescriptors(res.pages, this.buildLineRunLookup()); } } catch (err: any) { if (requestId !== this.latestTypesetRequestId || abortCtrl.signal.aborted) { @@ -2353,6 +2383,7 @@ export class TypesetOkApp { this.storyEditor.loadStory(this.documentState.flows.gemara); // The side panel must list the flows of this template, not whatever was loaded before. this.structureBar.setFlows(getFlowsForTemplate(this.documentState.templateType)); + this.syncStatusBarFlow(); this.activePageIndex = 0; this.structureBar.setActivePage(0); this.repaginateAndSync(true); @@ -2488,6 +2519,7 @@ export class TypesetOkApp { this.structureBar.setFlows(getFlowsForTemplate(newState.templateType)); this.inspector.setFlows(getFlowsForTemplate(newState.templateType)); this.structureBar.setActiveFlow(activeKey); + this.syncStatusBarFlow(); const activeStory = newState.flows[activeKey] || []; this.storyEditor.loadStory(activeStory); @@ -2695,6 +2727,7 @@ export class TypesetOkApp { const activeTemplate = this.documentState.templateType; this.structureBar.setFlows(getFlowsForTemplate(activeTemplate)); this.inspector.setFlows(getFlowsForTemplate(activeTemplate)); + this.syncStatusBarFlow(); this.inspector.setGrepRules(this.documentState.grepRules); this.inspector.setFootnoteApparatuses(this.documentState.footnoteApparatuses); this.activePageIndex = 0; @@ -2775,6 +2808,7 @@ export class TypesetOkApp { } const targetFlow = this.activeFlowId; this.structureBar.setActiveFlow(targetFlow); + this.syncStatusBarFlow(); this.storyEditor.loadStory(this.documentState.flows[targetFlow] || []); // If there is an associated import path, remember the new choice diff --git a/packages/tok-ui/src/components/ContextualInspector.ts b/packages/tok-ui/src/components/ContextualInspector.ts index 0a6ccad..f1c0d78 100644 --- a/packages/tok-ui/src/components/ContextualInspector.ts +++ b/packages/tok-ui/src/components/ContextualInspector.ts @@ -8,8 +8,8 @@ import { } from '../types'; import { getBuiltinGrepRules, getDefaultMultiApparatusConfigs } from '../engine/documentBridge'; import { IconName } from '../icons'; -import { t, i18n } from '../i18n'; -import { el, icon, button, switchRow, segmented, selectField } from '../ui'; +import { t, tf, i18n } from '../i18n'; +import { el, icon, button, iconButton, switchRow, segmented, selectField } from '../ui'; import { DOCUMENT_FONTS, DEFAULT_DOCUMENT_FONT, FONT_WEIGHT_BOLD, FONT_WEIGHT_REGULAR, getAvailableFonts } from '../fonts'; import { UpdatesBellButton } from '../updates/UpdatesBellButton'; @@ -357,7 +357,7 @@ export class ContextualInspector { // 3. Footer with Settings button if (this.callbacks.onOpenSettings) { const footer = el('footer', 'tok-inspector-footer'); - const settingsBtn = el('button', 'tok-btn tok-btn-ghost tok-insp-settings-btn', { + const settingsBtn = el('button', 'tok-btn tok-btn-ghost tok-insp-settings-btn tok-insp-settings-btn-labeled', { type: 'button', title: t('sidebarSettings'), 'aria-label': t('sidebarSettings') @@ -788,21 +788,40 @@ export class ContextualInspector { this.callbacks.onGrepRulesChange?.([...this.grepRules]); }, { focusKey: `grep-${rule.id}` }); row.setAttribute('data-grep-rule-id', rule.id); - grepCard.appendChild(row); + if (!rule.id.startsWith('grep-custom-')) { + grepCard.appendChild(row); + continue; + } + // User-added rules can be removed again; the built-in presets can only be switched on or off. + const removable = el('div', 'tok-grep-rule-row'); + removable.appendChild(row); + removable.appendChild(iconButton('trash', t('inspLiveGrepRemove'), () => { + this.grepRules = this.grepRules.filter((r) => r.id !== rule.id); + this.callbacks.onGrepRulesChange?.([...this.grepRules]); + this.render(); + }, { size: 14, className: 'tok-icon-btn tok-grep-rule-remove', attrs: { 'data-action': 'remove-grep-rule', 'data-grep-remove-id': rule.id } })); + grepCard.appendChild(removable); } const customWrap = el('div', 'tok-grep-custom-wrap', { style: 'display:flex;flex-direction:column;gap:6px;margin-top:8px;padding-top:6px;border-top:1px solid var(--tok-border-subtle);' }); + customWrap.appendChild(el('div', 'tok-inspector-sub', undefined, t('inspLiveGrepNewRule'))); const patternInput = el('input', 'tok-input', { type: 'text', dir: 'ltr', - placeholder: 'Regex (e.g. \\([^()]+\\))', + placeholder: t('inspLiveGrepPlaceholder'), + 'aria-label': t('inspLiveGrepNewRule'), 'data-grep-custom-pattern': 'true' }); + const patternError = el('div', 'tok-grep-error', { role: 'alert', hidden: true }); + patternInput.addEventListener('input', () => { + patternError.hidden = true; + patternInput.removeAttribute('aria-invalid'); + }); const styleSelect = el('select', 'tok-input', { 'data-grep-custom-style': 'true' }); for (const opt of [ - { id: 'parens-80', label: '80% גודל + אפור עדין (מראי מקומות)' }, - { id: 'bold-700', label: 'הדגשה (Bold 700)' }, - { id: 'rashi-font', label: 'גופן רש״י (Noto Rashi Hebrew)' } + { id: 'parens-80', label: t('inspLiveGrepStyleCitation') }, + { id: 'bold-700', label: t('inspLiveGrepStyleBold') }, + { id: 'rashi-font', label: t('inspLiveGrepStyleRashi') } ]) { const o = el('option', undefined, { value: opt.id }, opt.label); styleSelect.appendChild(o); @@ -815,10 +834,19 @@ export class ContextualInspector { onClick: () => { const pat = patternInput.value.trim(); if (!pat) return; + try { + // Same flags the live evaluator uses, so a pattern accepted here always runs. + new RegExp(pat, 'gu'); + } catch { + patternError.textContent = t('inspLiveGrepInvalid'); + patternError.hidden = false; + patternInput.setAttribute('aria-invalid', 'true'); + return; + } const mode = styleSelect.value; const newRule: GrepRuleData = { id: `grep-custom-${Date.now()}`, - name: `כלל מותאם: ${pat}`, + name: tf('inspLiveGrepCustomName', { p: pat }), pattern: pat, target_style_id: `char-custom-${mode}`, format: mode === 'parens-80' @@ -835,6 +863,8 @@ export class ContextualInspector { } }); customWrap.appendChild(patternInput); + customWrap.appendChild(el('div', 'tok-inspector-sub', undefined, t('inspLiveGrepPatternHint'))); + customWrap.appendChild(patternError); customWrap.appendChild(styleSelect); customWrap.appendChild(addBtn); grepCard.appendChild(customWrap); diff --git a/packages/tok-ui/src/components/SettingsModal.ts b/packages/tok-ui/src/components/SettingsModal.ts index 5318692..c864680 100644 --- a/packages/tok-ui/src/components/SettingsModal.ts +++ b/packages/tok-ui/src/components/SettingsModal.ts @@ -240,6 +240,16 @@ export class SettingsModal { const light = THEME_PALETTES.find((p) => p.id === 'light')!; const dark = THEME_PALETTES.find((p) => p.id === 'dark')!; + // Language is also switchable with the keyboard shortcut; this is the discoverable place for it. + const languages: { id: Language; label: string }[] = [ + { id: 'he', label: 'עברית' }, + { id: 'en', label: 'English' } + ]; + container.appendChild(group(t('appearanceLanguage'), segmented(t('appearanceLanguage'), languages, i18n.getLanguage(), (id) => { + i18n.setLanguage(id); + this.callbacks.onLanguageChange(id); + }, { fill: true, focusPrefix: 'language' }))); + // Main themes: light / dark / follow the system const themes = el('div', 'tok-theme-grid', { role: 'radiogroup', 'aria-label': t('appearanceTheme') }); themes.appendChild(this.themeCard('light', localizedPresetName(light.name), appMiniature(light, 150), settings.paletteId === 'light')); diff --git a/packages/tok-ui/src/components/SpreadCanvas.ts b/packages/tok-ui/src/components/SpreadCanvas.ts index 93a9426..56aa251 100644 --- a/packages/tok-ui/src/components/SpreadCanvas.ts +++ b/packages/tok-ui/src/components/SpreadCanvas.ts @@ -639,7 +639,8 @@ export class SpreadCanvas { // 1. Running head: page number on the outer corner. const head = el('div', 'tok-page-head', { 'data-layer-id': 'decorations' }); - const pageNo = el('span', undefined, undefined, `דף ${page.gematriaNumber} ${amud}`); + // Hebrew numerals read right to left whatever the interface language is. + const pageNo = el('span', undefined, { dir: 'rtl', style: 'unicode-bidi: isolate;' }, `דף ${page.gematriaNumber} ${amud}`); if (isRightPage) head.append(pageNo); else head.append(pageNo); sheet.appendChild(head); @@ -757,7 +758,7 @@ export class SpreadCanvas { } // 3. Running foot. - sheet.appendChild(el('div', 'tok-page-foot', { 'aria-hidden': 'true', 'data-layer-id': 'decorations' }, `- ${page.gematriaNumber} -`)); + sheet.appendChild(el('div', 'tok-page-foot', { 'aria-hidden': 'true', 'data-layer-id': 'decorations', dir: 'rtl', style: 'unicode-bidi: isolate;' }, `- ${page.gematriaNumber} -`)); // Guides (margin rectangle, baseline grid). const guides = el('div', 'tok-guides-layer', { 'aria-hidden': 'true', 'data-layer-id': 'guides' }); diff --git a/packages/tok-ui/src/components/StatusBar.ts b/packages/tok-ui/src/components/StatusBar.ts index d3759a8..e61cf46 100644 --- a/packages/tok-ui/src/components/StatusBar.ts +++ b/packages/tok-ui/src/components/StatusBar.ts @@ -127,11 +127,18 @@ export class StatusBar { private build(): void { this.element.innerHTML = ''; - // Page indicator (display only, does NOT open command search) - const pageItem = el('div', 'tok-status-btn tok-status-static', { title: tf('structurePageLabel', { g: this.pageLabel }) }); + // Page indicator: opens the page view (it does NOT open command search) + const pageItem = el('button', 'tok-status-btn', { + type: 'button', + title: tf('structurePageLabel', { g: this.pageLabel }), + style: 'cursor:pointer' + }); pageItem.appendChild(icon('pages', 14)); this.pageText = el('span'); pageItem.appendChild(this.pageText); + pageItem.addEventListener('click', () => { + this.callbacks.onPageClick?.(); + }); this.element.appendChild(pageItem); // Word count button (opens detailed text statistics modal) diff --git a/packages/tok-ui/src/components/StructureBar.ts b/packages/tok-ui/src/components/StructureBar.ts index 7658358..c18d437 100644 --- a/packages/tok-ui/src/components/StructureBar.ts +++ b/packages/tok-ui/src/components/StructureBar.ts @@ -30,6 +30,46 @@ function pageThumbDrawing(_rightHandPage: boolean): string {
`; } +const THUMB_PT_TO_PX = 96 / 72; +/** Width of the thumbnail content box (the 50px thumb minus its 1px borders). */ +const THUMB_INNER_WIDTH_PX = 48; + +/** Height of a thumbnail that keeps the real page proportions. */ +function thumbHeightPx(p: PageThumbnailItem): number | null { + if (!p.widthPt || !p.heightPt) return null; + return Math.round((THUMB_INNER_WIDTH_PX + 2) * (p.heightPt / p.widthPt)); +} + +/** Replaces the generic drawing with the page itself, scaled down. Static: no ids, no frames, no pointer events. */ +function mountPageMiniature(thumb: HTMLElement, p: PageThumbnailItem): void { + const html = p.htmlContent; + if (!html || !html.trim() || !p.widthPt || !p.heightPt) return; + const engine = html.includes('tok-page-layout-rust'); + const mini = el('div', 'tok-thumb-mini', { 'aria-hidden': 'true' }); + mini.style.width = `${p.widthPt}pt`; + mini.style.height = `${p.heightPt}pt`; + mini.style.transform = `scale(${THUMB_INNER_WIDTH_PX / (p.widthPt * THUMB_PT_TO_PX)})`; + const sheet = el('div', engine ? 'tok-page-sheet tok-page-engine-layout' : 'tok-page-sheet'); + sheet.style.width = `${p.widthPt}pt`; + sheet.style.height = `${p.heightPt}pt`; + if (engine) sheet.style.padding = '0'; + const content = el('div', 'tok-page-content', { + style: engine ? 'position:absolute;inset:0;overflow:hidden;' : 'flex:1;min-height:0;overflow:hidden;' + }); + content.innerHTML = html; + // The canvas owns these identifiers; a second copy in the DOM must not be found by its lookups. + content.querySelectorAll('[id],[data-para-id],[data-frame-id],.tok-interactive-frame').forEach((n) => { + n.removeAttribute('id'); + n.removeAttribute('data-para-id'); + n.removeAttribute('data-frame-id'); + n.classList.remove('tok-interactive-frame'); + }); + sheet.appendChild(content); + mini.appendChild(sheet); + thumb.textContent = ''; + thumb.appendChild(mini); +} + /** * Leading side of the workbench: an icon rail (pages, flows, styles, layers, settings, * about) and the panel it controls. Clicking the active rail item hides the panel. @@ -42,6 +82,9 @@ export class StructureBar { private activePageIndex = 0; private activeFlowId = 'gemara'; private pages: PageThumbnailItem[] = []; + /** Miniatures are drawn only for thumbnails that scroll into view (books can have hundreds of pages). */ + private thumbObserver: IntersectionObserver | null = null; + private pendingMiniatures = new Map void>(); private rail!: HTMLElement; private panel!: HTMLElement; @@ -61,10 +104,11 @@ export class StructureBar { { id: 'style-footnotes', name: 'הערות שוליים', fontFamily: 'Frank Ruhl Libre', fontSizePt: 10, fontWeight: FONT_WEIGHT_REGULAR, flowId: 'notes' } ]; - private layers: { id: string; name: string; visible: boolean; locked: boolean }[] = [ + /** `lockable: false` hides the lock: that layer holds nothing the user could move yet. */ + private layers: { id: string; name: string; visible: boolean; locked: boolean; lockable?: boolean }[] = [ { id: 'text-main', name: 'שכבת טקסט ראשי', visible: true, locked: false }, { id: 'text-commentary', name: 'שכבת פירושים', visible: true, locked: false }, - { id: 'decorations', name: 'עיטורים ומסגרות', visible: true, locked: false }, + { id: 'decorations', name: 'עיטורים ומסגרות', visible: true, locked: false, lockable: false }, { id: 'guides', name: 'קווי עזר ושוליים', visible: true, locked: true } ]; @@ -265,7 +309,7 @@ export class StructureBar { this.setPanelOpen(false); this.callbacks.onPanelToggle?.(false); this.callbacks.onActiveTabChange?.(this.activeTab, false); - }, { size: 16, attrs: { style: 'width:28px;height:28px', 'class': 'tok-panel-collapse-btn' } })); + }, { size: 16, className: 'tok-icon-btn tok-panel-collapse-btn', attrs: { style: 'width:28px;height:28px' } })); return head; } @@ -312,7 +356,32 @@ export class StructureBar { return `${p.label || tf('structurePageLabel', { g: p.gematria })} · ${tf('structurePageNumber', { n: p.pageIndex + 1 })} · ${side} (${amud})`; } + private observeMiniature(thumb: HTMLElement, p: PageThumbnailItem): void { + if (!p.htmlContent) return; + const mount = () => mountPageMiniature(thumb, p); + if (typeof IntersectionObserver === 'undefined') { + mount(); + return; + } + if (!this.thumbObserver) { + this.thumbObserver = new IntersectionObserver((entries, observer) => { + for (const entry of entries) { + if (!entry.isIntersecting) continue; + observer.unobserve(entry.target); + const run = this.pendingMiniatures.get(entry.target); + this.pendingMiniatures.delete(entry.target); + run?.(); + } + }, { rootMargin: '200px' }); + } + this.pendingMiniatures.set(thumb, mount); + this.thumbObserver.observe(thumb); + } + private renderPagesView(container: HTMLElement): void { + this.thumbObserver?.disconnect(); + this.thumbObserver = null; + this.pendingMiniatures.clear(); const list = el('div', 'tok-pages-list', { role: 'list' }); list.style.display = 'flex'; list.style.flexDirection = 'column'; @@ -334,6 +403,9 @@ export class StructureBar { title: this.pageDescription(p) }); thumb.innerHTML = pageThumbDrawing(isRightHandPage(p.pageIndex)); + const thumbHeight = thumbHeightPx(p); + if (thumbHeight) thumb.style.height = `${thumbHeight}px`; + this.observeMiniature(thumb, p); thumb.addEventListener('click', () => { this.activePageIndex = p.pageIndex; this.highlightActivePage(); @@ -441,7 +513,11 @@ export class StructureBar { const main = el('span', 'tok-list-main'); main.appendChild(el('span', 'tok-list-title', undefined, l.name)); - const subSpan = el('span', 'tok-list-sub', undefined, `${t(l.visible ? 'structureLayerVisible' : 'structureLayerHidden')} · ${t(l.locked ? 'structureLayerLocked' : 'structureLayerUnlocked')}`); + const lockable = l.lockable !== false; + const visibilityText = t(l.visible ? 'structureLayerVisible' : 'structureLayerHidden'); + const subSpan = el('span', 'tok-list-sub', undefined, lockable + ? `${visibilityText} · ${t(l.locked ? 'structureLayerLocked' : 'structureLayerUnlocked')}` + : visibilityText); main.appendChild(subSpan); row.appendChild(main); @@ -460,7 +536,7 @@ export class StructureBar { this.callbacks.onLockLayer?.(l.id, l.locked); }); syncLock(); - row.appendChild(lock); + if (lockable) row.appendChild(lock); container.appendChild(row); } diff --git a/packages/tok-ui/src/components/UpdatesDrawer.ts b/packages/tok-ui/src/components/UpdatesDrawer.ts index 3e43d0a..7854923 100644 --- a/packages/tok-ui/src/components/UpdatesDrawer.ts +++ b/packages/tok-ui/src/components/UpdatesDrawer.ts @@ -184,9 +184,10 @@ export class UpdatesDrawer { return; } + const currentVersion = this.stateManager.getLatestEntry()?.version; for (let idx = 0; idx < entries.length; idx++) { const entry = entries[idx]; - const isCurrent = idx === 0; + const isCurrent = entry.version === currentVersion; const card = new ChangelogEntryCard(entry, { isCurrent, defaultExpanded: isCurrent }); this.cardsContainer.appendChild(card.element); } diff --git a/packages/tok-ui/src/engine/lineRuns.ts b/packages/tok-ui/src/engine/lineRuns.ts new file mode 100644 index 0000000..20eacc8 --- /dev/null +++ b/packages/tok-ui/src/engine/lineRuns.ts @@ -0,0 +1,144 @@ +/** + * Line runs + * + * The Rust engine lays out every line and reports its text, but not the + * character formatting inside it. This module recovers that formatting from the + * paragraph's spans, so page view can paint italic, underline, colour, weight, + * family and size on the part of the line that has them, the same way the + * story editor shows them. + * + * Layout is never changed here: the engine already measured the line with the + * span fonts and sizes. Only the painting of the line text is richer. + */ + +import type { CharacterFormat, TextSpan } from 'tok-story-editor'; + +/** What page view needs to know about one paragraph of the document. */ +export interface LineRunSource { + /** Paragraph text exactly as it was sent to the engine. */ + text: string; + spans: TextSpan[]; + /** Paragraph-level text colour (style patch), applied to the whole line. */ + color?: string; +} + +export type LineRunLookup = (paragraphId: string) => LineRunSource | undefined; + +/** Resolves a font family from a span to a CSS `font-family` value. */ +export type FamilyToCss = (family: string) => string; + +interface LineRef { + text: string; + paragraph_id?: string | null; + is_drop_cap?: boolean; +} + +export interface LocatedLine { + source: LineRunSource; + /** Character offset of the line's first character in the paragraph text. */ + start: number; +} + +// Plain colour notations only: this value ends up inside a style attribute. +const SAFE_COLOR = /^(#[0-9a-f]{3,8}|rgba?\([\d\s.,%]+\)|hsla?\([\d\s.,%a-z]+\)|[a-z]{3,20})$/i; + +export function safeCssColor(value: string | undefined): string | undefined { + if (!value) return undefined; + const v = value.trim(); + return SAFE_COLOR.test(v) ? v : undefined; +} + +function escapeText(str: string): string { + return str + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); +} + +/** True when a span changes how text looks (a link or a style id alone does not). */ +function hasVisibleFormat(f: CharacterFormat | undefined): boolean { + if (!f) return false; + return Boolean( + f.italic || + f.underline || + safeCssColor(f.color) || + f.fontWeight !== undefined || + f.fontFamily || + (f.fontSizePt !== undefined && f.fontSizePt > 0) + ); +} + +/** + * Finds where each engine line starts inside its paragraph. + * + * A paragraph's lines arrive in reading order and each line's text is the next + * slice of the paragraph, so a moving cursor locates them. A line whose text + * cannot be found (for example when the engine collapsed repeated spaces) is + * left out and keeps its plain rendering. + */ +export function locateLines(lines: Iterable, lookup: LineRunLookup): Map { + const located = new Map(); + const cursors = new Map(); + for (const line of lines) { + const pid = line.paragraph_id; + if (!pid || line.is_drop_cap || !line.text) continue; + const source = lookup(String(pid)); + if (!source) continue; + const from = cursors.get(String(pid)) ?? 0; + const at = source.text.indexOf(line.text, from); + if (at < 0) continue; + located.set(line, { source, start: at }); + cursors.set(String(pid), at + line.text.length); + } + return located; +} + +function cssForFormat(f: CharacterFormat, familyToCss: FamilyToCss): string { + const css: string[] = []; + if (f.fontFamily) css.push(`font-family: ${familyToCss(f.fontFamily)};`); + if (f.fontSizePt !== undefined && f.fontSizePt > 0 && Number.isFinite(f.fontSizePt)) { + css.push(`font-size: ${f.fontSizePt}pt;`); + } + if (f.fontWeight !== undefined) css.push(`font-weight: ${f.fontWeight >= 600 ? 700 : 400};`); + if (f.italic) css.push('font-style: italic;'); + if (f.underline) css.push('text-decoration: underline;'); + const color = safeCssColor(f.color); + if (color) css.push(`color: ${color};`); + return css.join(' '); +} + +/** + * Line text as HTML with one `` per run of identical formatting. + * Returns null when nothing in the line is formatted, so the caller keeps the + * existing plain rendering. + */ +export function renderStyledLine(lineText: string, located: LocatedLine, familyToCss: FamilyToCss): string | null { + const start = located.start; + const end = start + lineText.length; + const spans = located.source.spans.filter((s) => s.end > start && s.start < end && hasVisibleFormat(s.format)); + if (spans.length === 0) return null; + + const cuts = new Set([start, end]); + for (const s of spans) { + cuts.add(Math.max(start, s.start)); + cuts.add(Math.min(end, s.end)); + } + const points = [...cuts].sort((a, b) => a - b); + + let html = ''; + for (let i = 0; i + 1 < points.length; i++) { + const a = points[i]; + const b = points[i + 1]; + const piece = escapeText(lineText.slice(a - start, b - start)); + // Later spans win over earlier ones where they overlap. + const merged: CharacterFormat = {}; + for (const s of spans) { + if (s.start <= a && s.end >= b) Object.assign(merged, s.format); + } + const css = cssForFormat(merged, familyToCss); + html += css ? `${piece}` : piece; + } + return html; +} diff --git a/packages/tok-ui/src/engine/typesetBridge.ts b/packages/tok-ui/src/engine/typesetBridge.ts index bf2dd1f..44c3acf 100644 --- a/packages/tok-ui/src/engine/typesetBridge.ts +++ b/packages/tok-ui/src/engine/typesetBridge.ts @@ -8,6 +8,7 @@ import { PageDescriptor } from 'tok-viewer'; import { toHebrewGematria } from '../gematria.js'; +import { LineRunLookup, locateLines, renderStyledLine, safeCssColor } from './lineRuns.js'; export interface PhysicalPoint { x: number; @@ -121,11 +122,17 @@ export function renderLineText(text: string, isDropCap = false): string { * Uses exact text positions, line heights, baselines, paragraph IDs, * and page dimensions calculated by the Rust typesetting engine. */ -export function layoutToPageDescriptors(pages: PageLayoutBox[]): PageDescriptor[] { +export function layoutToPageDescriptors(pages: PageLayoutBox[], lineRuns?: LineRunLookup): PageDescriptor[] { if (!Array.isArray(pages) || pages.length === 0) { return []; } + // The engine reports line text only. Where each line sits inside its paragraph tells us + // which formatting (italic, underline, colour, ...) to paint on which part of it. + const locatedLines = lineRuns + ? locateLines(pages.flatMap((p) => (p.frames || []).flatMap((f) => f.lines || [])), lineRuns) + : null; + return pages.map((pageBox) => { const pageIndex = typeof pageBox.page_index === 'number' ? pageBox.page_index : 0; const gematriaNumber = pageBox.page_number_gematria || toHebrewGematria(pageIndex + 1); @@ -215,9 +222,14 @@ export function layoutToPageDescriptors(pages: PageLayoutBox[]): PageDescriptor[ const fontStyle = `font-family: ${engineFont.fontFamily}; font-size: ${lineFontSizePt.toFixed(2)}pt;` + (isBoldLine ? ` font-weight: 700;` : ''); const paraAttr = line.paragraph_id ? ` data-para-id="${escapeHtml(String(line.paragraph_id))}"` : ''; const offsetStyle = line.x_offset ? (line.is_rtl ? ` margin-right: ${line.x_offset.toFixed(2)}pt;` : ` margin-left: ${line.x_offset.toFixed(2)}pt;`) : ''; - const contentHtml = renderLineText(line.text, line.is_drop_cap); - - return `
${contentHtml}
`; + const located = locatedLines?.get(line); + const contentHtml = (located + ? renderStyledLine(line.text, located, (family) => formatEngineFont(family, isPrimary).fontFamily) + : null) ?? renderLineText(line.text, line.is_drop_cap); + const paraColor = safeCssColor(located?.source.color); + const colorStyle = paraColor ? ` color: ${paraColor};` : ''; + + return `
${contentHtml}
`; }).join('\n'); const emptyNotice = (!frame.lines || frame.lines.length === 0) diff --git a/packages/tok-ui/src/i18n.ts b/packages/tok-ui/src/i18n.ts index d0d3888..44963b5 100644 --- a/packages/tok-ui/src/i18n.ts +++ b/packages/tok-ui/src/i18n.ts @@ -57,8 +57,8 @@ export const strings: Translations = { importDocument: { he: 'ייבא מסמך...', en: 'Import Document...' }, importDocumentDesc: { he: 'ייבוא קובץ Word (.docx), Markdown (.md) או טקסט פשוט (.txt)', en: 'Import Word (.docx), Markdown (.md) or plain text (.txt)' }, importChooseTemplateTitle: { he: 'בחירת תבנית עימוד עבור: {title}', en: 'Choose Layout Template for: {title}' }, - importChooseTemplateSub: { he: 'התוכן המיובא ({count} פסקאות) ישובץ בתבנית הנבחרת ללא דריסת טקסט', en: 'Imported content ({count} paragraphs) will be placed in the selected template' }, - newDocChooseTemplateTitle: { he: 'בחירת תבנית עימוד למסמך חדש', en: 'Choose Layout Template for New Document' }, + importChooseTemplateSub: { he: 'התוכן המיובא ({count} פסקאות) ישובץ בתבנית הנבחרת ללא דריסת טקסט', en: 'Imported content ({count} paragraphs) will be placed in the selected template' }, + newDocChooseTemplateTitle: { he: 'בחירת תבנית עימוד למסמך חדש', en: 'Choose Layout Template for New Document' }, newDocChooseTemplateSub: { he: 'בחר את תבנית העימוד לפרויקט החדש (מומלץ: ספר רציף)', en: 'Select a layout template for your new document (Recommended: Continuous Prose)' }, menuSave: { he: 'שמירת מסמך', en: 'Save Document' }, menuSaveAs: { he: 'שמירה בשם...', en: 'Save As...' }, @@ -105,30 +105,30 @@ export const strings: Translations = { structureFlowsTitle: { he: 'תזרימים', en: 'Flows' }, structureChangeTemplate: { he: 'החלפת תבנית ספר…', en: 'Change book layout…' }, structureFlowsDesc: { he: 'כל תזרים הוא טקסט רציף אחד. המנוע מפזר אותו על פני העמודים לפי צורת הדף.', en: 'Each flow is one continuous text. The engine pours it across the pages following the page layout.' }, - structureFlowPosition: { he: 'מיקום', en: 'Position' }, - structureAddFlow: { he: 'הוספת תזרים חדש', en: 'Add New Flow' }, - structureAddFlowCompact: { he: '+ תזרים מותאם אישית', en: '+ Custom Flow' }, - customFlowModalTitle: { he: 'עיצוב והוספת תזרים טקסט', en: 'Design & Add Text Flow' }, - customFlowModalSub: { he: 'הגדר את מבנה התזרים והמיקום שלו בעמוד (כולל תמיכה בבלוקים מפוצלים בקצוות)', en: 'Configure flow structure and page placement (including split edge blocks)' }, - customFlowNameLabel: { he: 'שם התזרים', en: 'Flow Name' }, - customFlowRoleLabel: { he: 'תפקיד / תיאור', en: 'Role / Description' }, - customFlowColorLabel: { he: 'צבע זיהוי', en: 'Identity Color' }, - customFlowPlacementLabel: { he: 'תבנית מיקום בעמוד', en: 'Page Placement Layout' }, - customFlowPlaceSplitEdges: { he: 'חצי בלוק בקצה אחד וחצי בקצה שני ללא חיבור (זרימה לפי גובה)', en: 'Split edge blocks on opposite margins (flow by height, no bridge)' }, - customFlowPlaceBottom: { he: 'תחתית העמוד (הערות שוליים וציונים)', en: 'Bottom of page (Footnotes & References)' }, - customFlowPlaceMargin: { he: 'טור שוליים חיצוניים', en: 'Outer Margin Column' }, - customFlowPlaceFree: { he: 'תיבה חופשית בעמוד (ניתנת להזזה ונעילה)', en: 'Free floating box (Draggable & Lockable)' }, - customFlowSubmit: { he: 'צור והוסף תזרים', en: 'Create & Add Flow' }, + structureFlowPosition: { he: 'מיקום', en: 'Position' }, + structureAddFlow: { he: 'הוספת תזרים חדש', en: 'Add New Flow' }, + structureAddFlowCompact: { he: '+ תזרים מותאם אישית', en: '+ Custom Flow' }, + customFlowModalTitle: { he: 'עיצוב והוספת תזרים טקסט', en: 'Design & Add Text Flow' }, + customFlowModalSub: { he: 'הגדר את מבנה התזרים והמיקום שלו בעמוד (כולל תמיכה בבלוקים מפוצלים בקצוות)', en: 'Configure flow structure and page placement (including split edge blocks)' }, + customFlowNameLabel: { he: 'שם התזרים', en: 'Flow Name' }, + customFlowRoleLabel: { he: 'תפקיד / תיאור', en: 'Role / Description' }, + customFlowColorLabel: { he: 'צבע זיהוי', en: 'Identity Color' }, + customFlowPlacementLabel: { he: 'תבנית מיקום בעמוד', en: 'Page Placement Layout' }, + customFlowPlaceSplitEdges: { he: 'חצי בלוק בקצה אחד וחצי בקצה שני ללא חיבור (זרימה לפי גובה)', en: 'Split edge blocks on opposite margins (flow by height, no bridge)' }, + customFlowPlaceBottom: { he: 'תחתית העמוד (הערות שוליים וציונים)', en: 'Bottom of page (Footnotes & References)' }, + customFlowPlaceMargin: { he: 'טור שוליים חיצוניים', en: 'Outer Margin Column' }, + customFlowPlaceFree: { he: 'תיבה חופשית בעמוד (ניתנת להזזה ונעילה)', en: 'Free floating box (Draggable & Lockable)' }, + customFlowSubmit: { he: 'צור והוסף תזרים', en: 'Create & Add Flow' }, toastFlowCreated: { he: 'התזרים "{name}" נוסף בהצלחה', en: 'Flow "{name}" added successfully' }, structureStylesTitle: { he: 'סגנונות', en: 'Styles' }, - structureLayersTitle: { he: 'שכבות עבודה', en: 'Layers' }, - structureLayersDesc: { - he: 'שכבות מאפשרות להציג, להסתיר או לנעול אלמנטים בעמוד (טקסט ראשי, פירושים, עיטורים וקווי עזר) כדי לעבוד בנוחות ולמנוע הזזה בשוגג.', - en: 'Layers let you show/hide or lock page elements (main text, commentaries, decorations, guides) to focus or prevent accidental moving.' - }, - structureLayerVisible: { he: 'מוצג', en: 'Visible' }, - structureLayerHidden: { he: 'מוסתר', en: 'Hidden' }, - structureLayerLocked: { he: 'נעול', en: 'Locked' }, + structureLayersTitle: { he: 'שכבות עבודה', en: 'Layers' }, + structureLayersDesc: { + he: 'שכבות מאפשרות להציג, להסתיר או לנעול אלמנטים בעמוד (טקסט ראשי, פירושים, עיטורים וקווי עזר) כדי לעבוד בנוחות ולמנוע הזזה בשוגג.', + en: 'Layers let you show/hide or lock page elements (main text, commentaries, decorations, guides) to focus or prevent accidental moving.' + }, + structureLayerVisible: { he: 'מוצג', en: 'Visible' }, + structureLayerHidden: { he: 'מוסתר', en: 'Hidden' }, + structureLayerLocked: { he: 'נעול', en: 'Locked' }, structureLayerUnlocked: { he: 'פתוח לעריכה', en: 'Unlocked' }, structureHideLayer: { he: 'הסתר שכבה', en: 'Hide layer' }, structureShowLayer: { he: 'הצג שכבה', en: 'Show layer' }, @@ -183,23 +183,23 @@ export const strings: Translations = { updatesStatusAvailable: { he: 'גרסה חדשה זמינה להורדה והתקנה', en: 'A newer version is available for download' }, updatesCheckNow: { he: 'בדיקת עדכונים', en: 'Check for updates' }, updatesAutoCheck: { he: 'בדיקת עדכונים אוטומטית בעת פתיחת התוכנה', en: 'Automatically check for updates on startup' }, - updatesDownload: { he: 'הורדת חבילת העדכון', en: 'Download Update Package' }, - updatesDownloadInApp: { he: 'הורדה והתקנה ישירה (ללא דפדפן)', en: 'Direct In-App Download (No browser)' }, - updatesDownloading: { he: 'מוריד עדכון...', en: 'Downloading update...' }, - updatesDownloadSuccess: { he: 'ההורדה הושלמה בהצלחה והקובץ אומת (SHA-256). הפעלת העדכון כעת תסגור את התוכנה ותתקין את הגרסה החדשה.', en: 'Download complete and verified (SHA-256). Launching update will close the app and install.' }, - updatesApplyNow: { he: 'הפעל עדכון וסגור תוכנה', en: 'Apply Update & Relaunch' }, - updatesSpeed: { he: 'מהירות', en: 'Speed' }, - updatesEta: { he: 'נותרו כ-{sec} שניות', en: '~{sec}s remaining' }, - updatesSha256: { he: 'חתימת אימות SHA-256', en: 'SHA-256 Checksum' }, - updatesOfflineTitle: { he: 'עדכון לא מקוון מדיסק-און-קי / קובץ', en: 'Offline Update from USB / File' }, - updatesOfflineDesc: { he: 'מתאים למחשבים מנותקים מאינטרנט (ישיבות, כוללים, עמדות סגורות). סריקה עמוקה של כונני USB ותיקיות הורדה.', en: 'For air-gapped computers (yeshivas, offline study halls). Deep scan of USB drives and local files.' }, - updatesOfflineSelectFile: { he: 'בחר קובץ עדכון מדיסק-און-קי...', en: 'Select Update File from USB...' }, - updatesOfflineScanUsb: { he: 'סריקת כונני USB', en: 'Scan USB Drives' }, - updatesOfflineFoundOnUsb: { he: 'נמצא קובץ עדכון {ver} בכונן {drive}:', en: 'Found update {ver} on drive {drive}:' }, - updatesOfflineNoFilesFound: { he: 'לא נמצאו קובצי עדכון של TypesetOK בכונני ה-USB', en: 'No TypesetOK update files found on USB drives' }, - updatesOfflineSelected: { he: 'קובץ נבחר: {file} (גרסה {ver})', en: 'Selected file: {file} (v{ver})' }, - updatesOfflineApply: { he: 'התקן מקובץ זה', en: 'Install From This File' }, - updatesOfflineFileInvalid: { he: 'הקובץ שנבחר אינו קובץ התקנה תקין של TypesetOK (נדרש קובץ תקין וחתום)', en: 'Selected file is not a valid TypesetOK installer binary' }, + updatesDownload: { he: 'הורדת חבילת העדכון', en: 'Download Update Package' }, + updatesDownloadInApp: { he: 'הורדה והתקנה ישירה (ללא דפדפן)', en: 'Direct In-App Download (No browser)' }, + updatesDownloading: { he: 'מוריד עדכון...', en: 'Downloading update...' }, + updatesDownloadSuccess: { he: 'ההורדה הושלמה בהצלחה והקובץ אומת (SHA-256). הפעלת העדכון כעת תסגור את התוכנה ותתקין את הגרסה החדשה.', en: 'Download complete and verified (SHA-256). Launching update will close the app and install.' }, + updatesApplyNow: { he: 'הפעל עדכון וסגור תוכנה', en: 'Apply Update & Relaunch' }, + updatesSpeed: { he: 'מהירות', en: 'Speed' }, + updatesEta: { he: 'נותרו כ-{sec} שניות', en: '~{sec}s remaining' }, + updatesSha256: { he: 'חתימת אימות SHA-256', en: 'SHA-256 Checksum' }, + updatesOfflineTitle: { he: 'עדכון לא מקוון מדיסק-און-קי / קובץ', en: 'Offline Update from USB / File' }, + updatesOfflineDesc: { he: 'מתאים למחשבים מנותקים מאינטרנט (ישיבות, כוללים, עמדות סגורות). סריקה עמוקה של כונני USB ותיקיות הורדה.', en: 'For air-gapped computers (yeshivas, offline study halls). Deep scan of USB drives and local files.' }, + updatesOfflineSelectFile: { he: 'בחר קובץ עדכון מדיסק-און-קי...', en: 'Select Update File from USB...' }, + updatesOfflineScanUsb: { he: 'סריקת כונני USB', en: 'Scan USB Drives' }, + updatesOfflineFoundOnUsb: { he: 'נמצא קובץ עדכון {ver} בכונן {drive}:', en: 'Found update {ver} on drive {drive}:' }, + updatesOfflineNoFilesFound: { he: 'לא נמצאו קובצי עדכון של TypesetOK בכונני ה-USB', en: 'No TypesetOK update files found on USB drives' }, + updatesOfflineSelected: { he: 'קובץ נבחר: {file} (גרסה {ver})', en: 'Selected file: {file} (v{ver})' }, + updatesOfflineApply: { he: 'התקן מקובץ זה', en: 'Install From This File' }, + updatesOfflineFileInvalid: { he: 'הקובץ שנבחר אינו קובץ התקנה תקין של TypesetOK (נדרש קובץ תקין וחתום)', en: 'Selected file is not a valid TypesetOK installer binary' }, updatesOfflineRecommended: { he: 'גרסה מומלצת', en: 'Recommended' }, updatesCheckFailed: { he: 'בדיקת העדכונים נכשלה', en: 'Update check failed' }, actionFailed: { he: 'הפעולה נכשלה', en: 'Action failed' }, @@ -331,10 +331,10 @@ export const strings: Translations = { inspLeft: { he: 'שמאל', en: 'Left' }, inspVAlign: { he: 'יישור אנכי', en: 'Vertical alignment' }, inspCenter: { he: 'מרכז', en: 'Center' }, - inspJustify: { he: 'מלא', en: 'Justify' }, - inspLockFrame: { he: 'נעל מיקום וגודל תיבה', en: 'Lock Frame Position & Size' }, - inspUnlockFrame: { he: 'שחרר נעילת תיבה (ניתן להזזה)', en: 'Unlock Frame (Draggable)' }, - toastFrameLocked: { he: 'תיבת הטקסט ננעלה במקומה', en: 'Text frame locked in place' }, + inspJustify: { he: 'מלא', en: 'Justify' }, + inspLockFrame: { he: 'נעל מיקום וגודל תיבה', en: 'Lock Frame Position & Size' }, + inspUnlockFrame: { he: 'שחרר נעילת תיבה (ניתן להזזה)', en: 'Unlock Frame (Draggable)' }, + toastFrameLocked: { he: 'תיבת הטקסט ננעלה במקומה', en: 'Text frame locked in place' }, toastFrameUnlocked: { he: 'תיבת הטקסט שוחררה להזזה חופשית', en: 'Text frame unlocked for free movement' }, inspTypography: { he: 'טיפוגרפיה', en: 'Typography' }, inspStyleToken: { he: 'סגנון פסקה', en: 'Paragraph style' }, @@ -463,6 +463,7 @@ export const strings: Translations = { appPageStatus: { he: 'דף {page} · {index} מתוך {total}', en: 'Page {page} · {index} of {total}' }, appLangHebrewRtl: { he: 'עברית (RTL)', en: 'Hebrew (RTL)' }, appLangEnglishLtr: { he: 'English (LTR)', en: 'English (LTR)' }, + appearanceLanguage: { he: 'שפת התוכנה', en: 'Application language' }, appLangHebrew: { he: 'עברית', en: 'Hebrew' }, appLangEnglish: { he: 'English', en: 'English' }, appLayerShown: { he: 'מוצגת', en: 'shown' }, @@ -553,8 +554,8 @@ export const strings: Translations = { draftRecoveryFound: { he: 'נמצאה טיוטה שנשמרה אוטומטית ({time}). האם לשחזר אותה?', en: 'Found an autosaved draft ({time}). Would you like to restore it?' }, restoreDraftBtn: { he: 'שחזר טיוטה', en: 'Restore Draft' }, discardDraftBtn: { he: 'מחק טיוטה', en: 'Discard Draft' }, - settingsDocAutosave: { he: 'שמירה אוטומטית של המסמך', en: 'Continuous document autosave' }, - settingsDocAutosaveEnable: { he: 'הפעלת שמירה רציפה ברקע', en: 'Enable continuous background autosave' }, + settingsDocAutosave: { he: 'שמירה אוטומטית של המסמך', en: 'Continuous document autosave' }, + settingsDocAutosaveEnable: { he: 'הפעלת שמירה רציפה ברקע', en: 'Enable continuous background autosave' }, settingsDocAutosaveHelp: { he: 'שומר אוטומטית שינויים במסמך 2.5 שניות לאחר סיום ההקלדה ומגבה טיוטות', en: 'Automatically saves document changes 2.5 seconds after typing stops and backs up drafts' }, settingsDone: { he: 'סיום', en: 'Done' }, settingsCategories: { he: 'קטגוריות הגדרות', en: 'Settings categories' }, @@ -587,12 +588,21 @@ export const strings: Translations = { exportProfileIsoCoated: { he: 'ISO Coated v2 · 100% K', en: 'ISO Coated v2 · 100% K' }, exportProfileGracol: { he: 'GRACoL 2013 · אופסט אמריקאי מצופה', en: 'GRACoL 2013 · US Coated Offset' }, exportProfileSwop: { he: 'US Web Coated (SWOP) v2 · דפוס רוטציה', en: 'US Web Coated (SWOP) v2 · Web Offset' }, - inspLiveGrepTitle: { he: 'מנוע חוקי GREP חי', en: 'Live GREP Rules Engine' }, - inspLiveGrepSub: { he: 'עיצוב דינמי בזמן אמת ללא שינוי טקסט המקור', en: 'Non-destructive real-time regex styling' }, - inspLiveGrepAddBtn: { he: 'הוסף כלל GREP מותאם', en: 'Add Custom GREP Rule' }, + inspLiveGrepTitle: { he: 'עיצוב אוטומטי לפי תבנית (GREP)', en: 'Auto-formatting by Pattern (GREP)' }, + inspLiveGrepSub: { he: 'מעצב אוטומטית כל קטע טקסט התואם לתבנית, למשל כל מראה מקום בסוגריים, בלי לשנות את הטקסט עצמו. הפעילו כלל מוכן או הוסיפו תבנית משלכם.', en: 'Automatically styles every piece of text that matches a pattern, such as every citation in parentheses, without changing the text itself. Turn on a ready-made rule or add your own pattern.' }, + inspLiveGrepAddBtn: { he: 'הוסף כלל', en: 'Add rule' }, + inspLiveGrepPlaceholder: { he: 'התבנית לחיפוש, לדוגמה: \\([^()]+\\)', en: 'Pattern to match, for example: \\([^()]+\\)' }, + inspLiveGrepPatternHint: { he: 'התבנית נכתבת כביטוי רגולרי. הדוגמה מסמנת כל טקסט שבתוך סוגריים.', en: 'The pattern is a regular expression. The example matches any text inside parentheses.' }, + inspLiveGrepNewRule: { he: 'כלל חדש', en: 'New rule' }, + inspLiveGrepInvalid: { he: 'התבנית אינה תקינה, בדקו אותה ונסו שוב.', en: 'The pattern is not valid. Check it and try again.' }, + inspLiveGrepRemove: { he: 'הסר כלל', en: 'Remove rule' }, + inspLiveGrepCustomName: { he: 'כלל מותאם: {p}', en: 'Custom rule: {p}' }, + inspLiveGrepStyleCitation: { he: 'הקטנה ל-80% ואפור עדין (מראי מקומות)', en: '80% size, soft grey (citations)' }, + inspLiveGrepStyleBold: { he: 'הדגשה (Bold)', en: 'Bold' }, + inspLiveGrepStyleRashi: { he: 'גופן רש״י', en: 'Rashi font' }, inspMultiApparatusTitle: { he: 'מדורי הערות שוליים מקבילים', en: 'Multi-Apparatus Footnotes' }, - inspMultiApparatusSub: { he: 'ניהול מדורים עצמאיים בתחתית העמוד (מקורות + ביאורים)', en: 'Independent bottom footnote bands (Sources + Commentary)' }, - inspMultiApparatusPresetDual: { he: 'הפעל 2 מדורים (מקורות 2 טורים + ביאורים טור 1)', en: 'Enable Dual Apparatus (Sources 2-col + Commentary 1-col)' }, + inspMultiApparatusSub: { he: 'מאפשר להציג כמה מדורי הערות נפרדים בתחתית העמוד, לכל אחד מספור וכמות טורים משלו, למשל מקורות וציונים לצד ביאורים.', en: 'Shows several separate footnote bands at the bottom of the page, each with its own numbering and column count, for example sources next to commentary.' }, + inspMultiApparatusPresetDual: { he: 'הפעל שני מדורים: מקורות (2 טורים) וביאורים (טור אחד)', en: 'Enable two bands: Sources (2 columns) and Commentary (1 column)' }, inspMultiApparatusAdd: { he: 'הוסף מדור הערות נוסף', en: 'Add Footnote Apparatus' }, exportFileName: { he: 'שם הקובץ', en: 'File name' }, exportCancel: { he: 'ביטול', en: 'Cancel' }, diff --git a/packages/tok-ui/src/index.html b/packages/tok-ui/src/index.html index 50a5358..067c614 100644 --- a/packages/tok-ui/src/index.html +++ b/packages/tok-ui/src/index.html @@ -158,6 +158,7 @@ ::-webkit-scrollbar { width: 10px; height: 10px; } ::-webkit-scrollbar-track { background: transparent; } + ::-webkit-scrollbar-corner { background: transparent; } ::-webkit-scrollbar-thumb { background: var(--tok-border-strong); border-radius: 5px; border: 2px solid transparent; background-clip: padding-box; } ::-webkit-scrollbar-thumb:hover { background: var(--tok-text-muted); background-clip: padding-box; border: 2px solid transparent; } @@ -437,7 +438,8 @@ .tok-spread-card:hover { background: var(--tok-bg-surface-hover); } .tok-spread-pages { display: flex; box-shadow: 0 1px 3px rgba(27, 26, 23, 0.18); } .tok-spread-label { font-size: 12px; } - .tok-thumb { width: 50px; height: 70px; position: relative; background: var(--tok-paper); border: 1px solid var(--tok-border-strong); cursor: pointer; } + .tok-thumb { width: 50px; height: 70px; position: relative; background: var(--tok-paper); border: 1px solid var(--tok-border-strong); cursor: pointer; overflow: hidden; padding: 0; } + .tok-thumb .tok-thumb-mini { position: absolute; top: 0; left: 0; transform-origin: 0 0; pointer-events: none; user-select: none; } .tok-thumb.tok-thumb-empty { background: transparent; border-color: transparent; cursor: default; } .tok-thumb[aria-current="page"] { outline: 2px solid var(--tok-accent-text); outline-offset: 1px; z-index: 1; } .tok-thumb i { position: absolute; display: block; } @@ -664,6 +666,9 @@ .tok-insp-settings-btn:hover { background: var(--tok-bg-surface-hover); color: var(--tok-text-primary); } + .tok-insp-settings-btn.tok-insp-settings-btn-labeled { + width: auto; padding: 0 10px; gap: 6px; font-size: 12px; white-space: nowrap; + } .tok-insp-head { padding: 12px 14px; border-bottom: 1px solid var(--tok-border-subtle); display: flex; flex-direction: column; gap: 3px; background: var(--tok-bg-surface-1); } .tok-insp-eyebrow { font-size: 11px; font-weight: 500; color: var(--tok-text-muted); text-transform: uppercase; letter-spacing: 0.03em; } @@ -683,7 +688,15 @@ font-size: 12px; font-weight: 700; color: var(--tok-text-primary); display: flex; align-items: center; justify-content: space-between; padding-bottom: 6px; border-bottom: 1px solid var(--tok-border-subtle); margin-bottom: 2px; } - .tok-inspector-sub { font-size: 11.5px; font-weight: 500; color: var(--tok-text-secondary); margin-top: 2px; } + .tok-inspector-sub { font-size: 11.5px; font-weight: 500; color: var(--tok-text-secondary); margin-top: 2px; line-height: 1.45; } + /* Long labels wrap inside inspector cards instead of running past the panel edge */ + .tok-inspector-card .tok-btn-block { + height: auto; min-height: 28px; padding: 6px 10px; white-space: normal; line-height: 1.35; text-align: center; + } + .tok-grep-rule-row { display: flex; align-items: center; gap: 4px; } + .tok-grep-rule-row > .tok-switch-row { flex: 1; min-width: 0; } + .tok-grep-rule-remove { flex: none; width: 24px; height: 24px; } + .tok-grep-error { font-size: 11.5px; color: var(--tok-status-error); } .tok-insp-spacer { flex: 1; min-height: 12px; } .tok-status-line { display: flex; align-items: center; justify-content: space-between; gap: 8px; font-size: 12px; min-height: 22px; } .tok-status-line > span:first-child { color: var(--tok-text-secondary); } @@ -1057,7 +1070,7 @@ display: flex; align-items: center; } - .tok-updates-search-wrap svg { + .tok-updates-search-wrap > .tok-icon-wrap { position: absolute; top: 50%; transform: translateY(-50%); @@ -1141,13 +1154,17 @@ display: flex; align-items: center; justify-content: space-between; - gap: 8px; + flex-wrap: wrap; + gap: 6px 8px; } .tok-changelog-version-group { display: flex; align-items: center; - gap: 8px; + flex-wrap: wrap; + gap: 6px 8px; + min-width: 0; } + .tok-changelog-version-group .tok-badge { white-space: nowrap; } .tok-changelog-version-tag { font-size: 14px; font-weight: 700; @@ -1156,17 +1173,23 @@ font-variant-numeric: tabular-nums; } .tok-changelog-date { + white-space: nowrap; font-size: 11.5px; color: var(--tok-text-muted); } .tok-changelog-header-right { display: flex; align-items: center; + flex: none; gap: 10px; + white-space: nowrap; + margin-inline-start: auto; } .tok-changelog-toggle-btn { display: inline-flex; align-items: center; + flex: none; + white-space: nowrap; gap: 4px; padding: 3px 8px; font-size: 11px; diff --git a/packages/tok-ui/src/types.ts b/packages/tok-ui/src/types.ts index 5a3e7e4..4e5d9d8 100644 --- a/packages/tok-ui/src/types.ts +++ b/packages/tok-ui/src/types.ts @@ -108,7 +108,7 @@ export interface MultiFlowItem { color: string; role: string; wordCount: number; - isActive: boolean; + isActive: boolean; layoutPlacement?: 'split-edges' | 'bottom' | 'margin-outer' | 'free'; } @@ -194,15 +194,19 @@ export interface PageThumbnailItem { // Right-hand page of its spread. In an RTL-bound book the right page is the verso // (ע"ב); use isRightHandPage()/isRectoPage() from components/SpreadCanvas to derive it. isSpreadRight: boolean; -} - -export type { - HierarchyLevelJson, - GematriaPunctuationJson, - NumberingScopeJson, - NumberingSchemeJson, - DocumentHierarchyNodeJson, - DocumentOutlineJson, - LevelNumberingRuleJson, - OutlineNumberingConfigJson -} from './engine/documentBridge.js'; + /** Rendered page body and size, used to draw a real miniature of the page. Absent: a generic sheet is drawn. */ + htmlContent?: string; + widthPt?: number; + heightPt?: number; +} + +export type { + HierarchyLevelJson, + GematriaPunctuationJson, + NumberingScopeJson, + NumberingSchemeJson, + DocumentHierarchyNodeJson, + DocumentOutlineJson, + LevelNumberingRuleJson, + OutlineNumberingConfigJson +} from './engine/documentBridge.js'; diff --git a/packages/tok-ui/src/updates/ChangelogEntryCard.ts b/packages/tok-ui/src/updates/ChangelogEntryCard.ts index 1b6125d..6981380 100644 --- a/packages/tok-ui/src/updates/ChangelogEntryCard.ts +++ b/packages/tok-ui/src/updates/ChangelogEntryCard.ts @@ -1,4 +1,4 @@ -import { ChangelogEntry } from './types'; +import { ChangelogEntry, LocalizedString } from './types'; import { i18n, Language } from '../i18n'; import { el, icon } from '../ui'; import { createVersionBadge, createCategoryPill } from './updatePills'; @@ -8,6 +8,17 @@ export interface ChangelogCardOptions { defaultExpanded?: boolean; } +/** + * "Current" and "previous" are decided by the card from the list position, never by the data. + * Older changelog entries carry these words as their badge, so they are ignored as custom badges. + */ +const LIFECYCLE_BADGE_TEXTS = new Set(['גרסה נוכחית', 'גרסה קודמת', 'current version', 'previous version']); + +function isLifecycleBadge(badge?: LocalizedString): boolean { + if (!badge) return false; + return LIFECYCLE_BADGE_TEXTS.has((badge.he || '').trim()) || LIFECYCLE_BADGE_TEXTS.has((badge.en || '').trim().toLowerCase()); +} + export class ChangelogEntryCard { public element: HTMLElement; private entry: ChangelogEntry; @@ -41,14 +52,12 @@ export class ChangelogEntryCard { const versionTitle = el('h3', 'tok-changelog-version-tag', undefined, `v${this.entry.version}`); titleGroup.appendChild(versionTitle); - // Only show "Current Version" badge if this is truly the current version - const badgeData = this.isCurrent - ? this.entry.badge - : (this.entry.badge?.he === 'גרסה נוכחית' ? undefined : this.entry.badge); - - if (badgeData || this.isCurrent) { - const badge = createVersionBadge(this.entry.importance, badgeData || { he: 'גרסה נוכחית', en: 'Current Version' }); - titleGroup.appendChild(badge); + // "Current Version" is shown only on the running version; a real custom badge (e.g. "Major Release") is kept next to it. + if (this.isCurrent) { + titleGroup.appendChild(el('span', 'tok-badge tok-badge-success', undefined, lang === 'he' ? 'גרסה נוכחית' : 'Current Version')); + } + if (this.entry.badge && !isLifecycleBadge(this.entry.badge)) { + titleGroup.appendChild(createVersionBadge(this.entry.importance, this.entry.badge)); } header.appendChild(titleGroup); diff --git a/packages/tok-ui/src/updates/changelogData.ts b/packages/tok-ui/src/updates/changelogData.ts index 54cd492..0a85938 100644 --- a/packages/tok-ui/src/updates/changelogData.ts +++ b/packages/tok-ui/src/updates/changelogData.ts @@ -5,6 +5,117 @@ import { ChangelogEntry } from './types'; export const CHANGELOG_ENTRIES: ChangelogEntry[] = [ + { + "version": "0.35.2", + "releaseDate": "2026-11-09", + "importance": "patch", + "title": { + "he": "שדרוג מנגנון העדכון ותיקון אתחול מסמכים", + "en": "Upgraded In-App Updater & Document Initialization Fix" + }, + "summary": { + "he": "שדרוג מקיף של מנגנון העדכון עם הורדה ישירה מתוך התוכנה ללא תלות בדפדפן, אימות תקינות וקובץ SHA-256 בזמן ההורדה, איתור מתקינים מקומיים בכוננים חיצוניים ובתיקיות נפוצות והשוואת גרסאות אוטומטית. בנוסף, תיקון סדר אתחול ContextualInspector כדי לאפשר יצירה וייבוא תקינים של מסמכים ולמנוע סביבת עבודה ריקה.", + "en": "Comprehensive in-app updater improvements with browserless direct downloads, streaming SHA-256 and executable validation, local installer discovery across external drives and common folders, and automatic version comparison. Also fixes ContextualInspector initialization order so document creation and DOCX import work correctly instead of opening a blank workspace." + }, + "changes": [ + { + "category": "improvements", + "text": { + "he": "מנגנון עדכון מובנה עם הורדה ישירה ללא פתיחת דפדפן חיצוני, כתיבה אטומית לקובץ ‎.part, מדדי מהירות ו-ETA ואימות SHA-256 בזמן הורדה", + "en": "Browserless in-app updater with direct streaming download, atomic .part file handling, live speed/ETA, and streaming SHA-256 verification" + } + }, + { + "category": "improvements", + "text": { + "he": "אימות כותרת PE ‏(MZ), גודל מינימלי ותקינות קובץ לפני הפעלת המתקין", + "en": "Validate PE (MZ) header, minimum file size, and installer integrity before execution" + } + }, + { + "category": "features", + "text": { + "he": "סריקה עמוקה של כוננים חיצוניים ותיקיות מתקינים נפוצות, השוואת SemVer והמלצה על גרסה חדשה", + "en": "Deep external-drive and common installer-folder discovery with SemVer comparison and newest-candidate recommendation" + } + }, + { + "category": "improvements", + "text": { + "he": "הפעלה מנותקת של המתקין וסגירה מסודרת של התוכנה לשחרור נעילות קבצים", + "en": "Detached installer execution and clean application shutdown to release binary locks" + } + }, + { + "category": "improvements", + "text": { + "he": "הוספת 11 בדיקות יחידה ורגרסיה למנוע העדכון, אימות PE, SHA-256 וגישור IPC", + "en": "Added 11 unit and regression tests for updater engine, PE validation, SHA-256, and IPC bridge contracts" + } + }, + { + "category": "fixes", + "text": { + "he": "תיקון אתחול ContextualInspector והעברת setFlows לאחר יצירת inspector, לתיקון יצירת מסמכים וייבוא DOCX ב-Issue #28", + "en": "Fix ContextualInspector initialization order and call setFlows after inspector creation, resolving document creation and DOCX import failures in Issue #28" + } + } + ], + "highlights": [ + { + "id": "updater-streaming", + "icon": "download", + "title": { + "he": "הורדה ישירה ובטוחה מתוך התוכנה", + "en": "Direct & Resilient In-App Downloads" + }, + "description": { + "he": "הורדה בזרימה לקובץ זמני עם מדדי מהירות וזמן משוער, אימות SHA-256 בזמן ההעברה ובדיקת כותרת PE וגודל הקובץ לפני הפעלה.", + "en": "Stream downloads to a temporary file with live speed and ETA, streaming SHA-256 verification, and PE header and file-size checks before execution." + }, + "badge": { + "he": "עדכון מובנה", + "en": "In-App Updates" + } + }, + { + "id": "local-installer-discovery", + "icon": "hard-drive", + "title": { + "he": "איתור מתקינים בכוננים ותיקיות מקומיות", + "en": "Local & External Installer Discovery" + }, + "description": { + "he": "סריקה היוריסטית של כוננים חיצוניים ותיקיות נפוצות, השוואת SemVer והמלצה על המתקין העדכני ביותר.", + "en": "Heuristic scanning of external drives and common folders, SemVer comparison, and recommendation of the newest installer." + }, + "badge": { + "he": "איתור מתקינים", + "en": "Installer Discovery" + } + }, + { + "id": "document-init-fix", + "icon": "file-check", + "title": { + "he": "תיקון יצירת מסמכים וייבוא Word", + "en": "Fixed Document Creation & Word Import" + }, + "description": { + "he": "תיקון סדר יצירת ContextualInspector והפעלת setFlows לאחר האתחול, למניעת מסמכים ריקים.", + "en": "Corrected ContextualInspector initialization order and moved setFlows after initialization to prevent blank documents." + }, + "badge": { + "he": "תיקון אתחול", + "en": "Initialization Fix" + } + } + ], + "badge": { + "he": "תיקון ושדרוג", + "en": "Fixes & Update Improvements" + } + }, { "version": "0.35.1", "releaseDate": "2026-11-08", diff --git a/test/story_editor.test.mjs b/test/story_editor.test.mjs index 1c83a6d..8922e42 100644 --- a/test/story_editor.test.mjs +++ b/test/story_editor.test.mjs @@ -548,3 +548,84 @@ describe('Stage 11: Long Document Scalability & Performance', () => { editor.destroy(); }); }); + +describe('Page view paints span formatting on engine lines', () => { + let lineRuns; + let bridge; + const toCss = (family) => `'${family}'`; + + before(async () => { + lineRuns = await import('../packages/tok-ui/dist/engine/lineRuns.js'); + bridge = await import('../packages/tok-ui/dist/engine/typesetBridge.js'); + }); + + const line = (text, extra = {}) => ({ line_index: 0, paragraph_id: 'P1', text, baseline_y: 12, height: 14, width: 100, is_rtl: true, ...extra }); + + test('lines are located as consecutive slices of their paragraph', () => { + const source = { text: 'אחת שתיים שלוש ארבע', spans: [] }; + const a = line('אחת שתיים'); + const b = line('שלוש ארבע', { line_index: 1 }); + const located = lineRuns.locateLines([a, b], (id) => (id === 'P1' ? source : undefined)); + assert.equal(located.get(a).start, 0); + assert.equal(located.get(b).start, 10); + }); + + test('a line that is not part of the paragraph keeps plain rendering', () => { + const located = lineRuns.locateLines([line('טקסט אחר')], () => ({ text: 'אחת שתיים', spans: [] })); + assert.equal(located.size, 0); + }); + + test('italic, underline and colour become styled runs, the rest stays plain', () => { + const source = { + text: 'אחת שתיים שלוש', + spans: [ + { start: 4, end: 9, format: { italic: true, underline: true } }, + { start: 10, end: 14, format: { color: '#aa0000' } } + ] + }; + const l = line('אחת שתיים שלוש'); + const located = lineRuns.locateLines([l], () => source).get(l); + const html = lineRuns.renderStyledLine(l.text, located, toCss); + assert.ok(html.startsWith('אחת ')); + assert.match(html, /שתיים<\/span>/); + assert.match(html, /שלוש<\/span>/); + }); + + test('a span that starts on an earlier line is still painted on the following line', () => { + const source = { text: 'אחת שתיים שלוש ארבע', spans: [{ start: 0, end: 19, format: { italic: true } }] }; + const b = line('שלוש ארבע'); + const located = lineRuns.locateLines([b], () => source).get(b); + assert.equal(lineRuns.renderStyledLine(b.text, located, toCss), 'שלוש ארבע'); + }); + + test('lines without visible formatting return null', () => { + const source = { text: 'אחת שתיים', spans: [{ start: 0, end: 4, format: { linkUrl: 'https://example.org' } }] }; + const l = line('אחת שתיים'); + const located = lineRuns.locateLines([l], () => source).get(l); + assert.equal(lineRuns.renderStyledLine(l.text, located, toCss), null); + }); + + test('text and colours are escaped before they reach the page', () => { + const source = { text: 'a source).get(l); + const html = lineRuns.renderStyledLine(l.text, located, toCss); + assert.equal(html, 'a<b'); + assert.equal(lineRuns.safeCssColor('red;background:url(x)'), undefined); + }); + + test('layoutToPageDescriptors paints runs and paragraph colour, and is unchanged without a lookup', () => { + const pages = [{ + page_index: 0, + page_number_gematria: 'א', + dimensions: { x: 0, y: 0, width: 400, height: 600 }, + frames: [{ frame_id: 'f1', flow_id: 'gemara', rect: { x: 10, y: 10, width: 300, height: 500 }, lines: [line('אחת שתיים')] }] + }]; + const plain = bridge.layoutToPageDescriptors(pages)[0].htmlContent; + assert.ok(!plain.includes('font-style: italic')); + const lookup = () => ({ text: 'אחת שתיים', color: '#112233', spans: [{ start: 4, end: 9, format: { italic: true } }] }); + const styled = bridge.layoutToPageDescriptors(pages, lookup)[0].htmlContent; + assert.match(styled, /שתיים<\/span>/); + assert.match(styled, /color: #112233;/); + }); +}); diff --git a/test/whats_new_system.test.mjs b/test/whats_new_system.test.mjs index 0defff9..66ec66d 100644 --- a/test/whats_new_system.test.mjs +++ b/test/whats_new_system.test.mjs @@ -1,273 +1,292 @@ -import { test, describe, beforeEach } from 'node:test'; -import assert from 'node:assert/strict'; -import * as fs from 'node:fs'; -import * as path from 'node:path'; -import { fileURLToPath } from 'node:url'; - -const __filename = fileURLToPath(import.meta.url); -const __dirname = path.dirname(__filename); -const rootDir = path.resolve(__dirname, '..'); - -import { CHANGELOG_ENTRIES } from '../packages/tok-ui/dist/updates/changelogData.js'; -import { UpdatesStateManager, compareSemver } from '../packages/tok-ui/dist/updates/updatesManager.js'; -import { parseChangelogMarkdown } from '../scripts/sync-changelog.mjs'; -import { strings } from '../packages/tok-ui/dist/i18n.js'; - -describe("What's New System - Full Test Suite", () => { - beforeEach(() => { - UpdatesStateManager.resetInstance(); - }); - - describe('Changelog Registry & Data Integrity', () => { - test('changelog entries exist and are ordered descending by semver', () => { - assert.ok(CHANGELOG_ENTRIES.length >= 3, 'Should have at least 3 historical releases'); - - for (let i = 0; i < CHANGELOG_ENTRIES.length - 1; i++) { - const vCurr = CHANGELOG_ENTRIES[i].version; - const vNext = CHANGELOG_ENTRIES[i + 1].version; - assert.ok( - compareSemver(vCurr, vNext) >= 0, - `Version ${vCurr} should be >= ${vNext}` - ); - } - }); - - test('every entry has complete Hebrew and English metadata', () => { - for (const entry of CHANGELOG_ENTRIES) { - assert.ok(entry.version, 'Entry must have a version'); - assert.match(entry.releaseDate, /^\d{4}-\d{2}-\d{2}$/, 'Release date must be YYYY-MM-DD'); - assert.ok(['major', 'minor', 'patch'].includes(entry.importance), 'Valid importance'); - - // Bilingual title and summary - assert.ok(entry.title?.he && entry.title.he.trim().length > 0, `Hebrew title missing in v${entry.version}`); - assert.ok(entry.title?.en && entry.title.en.trim().length > 0, `English title missing in v${entry.version}`); - assert.ok(entry.summary?.he && entry.summary.he.trim().length > 0, `Hebrew summary missing in v${entry.version}`); - assert.ok(entry.summary?.en && entry.summary.en.trim().length > 0, `English summary missing in v${entry.version}`); - - // Changes - assert.ok(Array.isArray(entry.changes) && entry.changes.length > 0, `Changes missing in v${entry.version}`); - for (const change of entry.changes) { - assert.ok(change.category, 'Category must be defined'); - assert.ok(change.text?.he, 'Hebrew text must be defined'); - assert.ok(change.text?.en, 'English text must be defined'); - } - - // Major releases must contain visual highlight cards - if (entry.importance === 'major') { - assert.ok(Array.isArray(entry.highlights) && entry.highlights.length > 0, `Major release v${entry.version} must have highlights`); - for (const hl of entry.highlights) { - assert.ok(hl.title?.he && hl.title?.en, 'Highlight must have bilingual title'); - assert.ok(hl.description?.he && hl.description?.en, 'Highlight must have bilingual description'); - assert.ok(hl.icon, 'Highlight must specify an icon'); - } - } - } - }); - }); - - describe('CHANGELOG.md Markdown Source-of-Truth & Parser', () => { - test('CHANGELOG.md exists in project root and parses cleanly', () => { - const changelogFile = path.join(rootDir, 'CHANGELOG.md'); - assert.ok(fs.existsSync(changelogFile), 'CHANGELOG.md must exist in root'); - - const content = fs.readFileSync(changelogFile, 'utf8'); - const parsed = parseChangelogMarkdown(content); - - assert.ok(parsed.length >= 3, 'Must parse at least 3 releases'); - const v0304 = parsed.find(e => e.version === '0.30.4'); - assert.ok(v0304, '0.30.4 must be parsed'); - const v0300 = parsed.find(e => e.version === '0.30.0'); - assert.ok(v0300, '0.30.0 must be parsed'); - assert.equal(v0300.importance, 'major'); - assert.ok(v0300.highlights.length >= 4, 'Major release must parse highlights'); - }); - - test('Strict No-Emoji & No-Vibe-Coding Policy in changelog and UI text', () => { - const emojiRegex = /[\u{1F300}-\u{1F5FF}\u{1F600}-\u{1F64F}\u{1F680}-\u{1F6FF}\u{2600}-\u{26FF}\u{2700}-\u{27BF}\u{1F900}-\u{1F9FF}\u{1FA70}-\u{1FAFF}]/u; - - const changelogContent = fs.readFileSync(path.join(rootDir, 'CHANGELOG.md'), 'utf8'); - assert.equal(emojiRegex.test(changelogContent), false, 'CHANGELOG.md must NOT contain any emojis (official vector icons only)'); - - const dataContent = fs.readFileSync(path.join(rootDir, 'packages/tok-ui/src/updates/changelogData.ts'), 'utf8'); - assert.equal(emojiRegex.test(dataContent), false, 'changelogData.ts must NOT contain any emojis'); - }); - }); - - describe('Semver Comparison Logic', () => { - test('compares standard versions correctly', () => { - assert.equal(compareSemver('0.30.4', '0.30.0'), 1); - assert.equal(compareSemver('0.30.0', '0.30.4'), -1); - assert.equal(compareSemver('0.30.0', '0.30.0'), 0); - }); - - test('handles v prefix and varying component lengths', () => { - assert.equal(compareSemver('v1.0.0', '0.9.9'), 1); - assert.equal(compareSemver('0.30', '0.30.0'), 0); - assert.equal(compareSemver('1.2.3', 'v1.2.3'), 0); - }); - }); - - describe('UpdatesStateManager Business Rules', () => { - const mockEntries = [ - { - version: '1.1.0', - releaseDate: '2026-11-01', - importance: 'minor', - title: { he: 'עדכון קל', en: 'Minor Update' }, - summary: { he: 'תיקונים ושיפורים קטנים', en: 'Small fixes and tweaks' }, - changes: [ - { category: 'improvements', text: { he: 'שיפור ביצועים', en: 'Performance tweak' } }, - { category: 'fixes', text: { he: 'תיקון באג', en: 'Bug fix' } } - ] - }, - { - version: '1.0.0', - releaseDate: '2026-10-15', - importance: 'major', - title: { he: 'גרסה ראשית 1.0', en: 'Major Release 1.0' }, - summary: { he: 'מהפכה במערכת', en: 'Massive milestone' }, - highlights: [ - { - id: 'engine', - title: { he: 'מנוע חדש', en: 'New Engine' }, - description: { he: 'מהיר', en: 'Fast' }, - icon: 'sparkle' - } - ], - changes: [ - { category: 'features', text: { he: 'פיצ׳ר ענק', en: 'Huge feature' } }, - { category: 'typography', text: { he: 'ניקוד מדויק', en: 'Precise niqqud' } } - ] - }, - { - version: '0.9.0', - releaseDate: '2026-09-01', - importance: 'minor', - title: { he: 'גרסה ישנה', en: 'Old version' }, - summary: { he: 'בסיס', en: 'Base' }, - changes: [ - { category: 'features', text: { he: 'בסיס', en: 'Base' } } - ] - } - ]; - - test('shouldPromptMajorUpdate triggers only for unread major releases', () => { - const manager = UpdatesStateManager.getInstance(mockEntries); - - // 1.0.0 is major, hasn't been seen -> true - assert.equal(manager.shouldPromptMajorUpdate('1.0.0'), true); - - // 1.1.0 is minor -> false (minor updates do NOT trigger popup!) - assert.equal(manager.shouldPromptMajorUpdate('1.1.0'), false); - - // After user sees 1.0.0 -> should no longer prompt - manager.markVersionAsSeen('1.0.0'); - assert.equal(manager.shouldPromptMajorUpdate('1.0.0'), false); - - // Dismissing major prompt prevents prompt - UpdatesStateManager.resetInstance(); - const manager2 = UpdatesStateManager.getInstance(mockEntries); - assert.equal(manager2.shouldPromptMajorUpdate('1.0.0'), true); - manager2.dismissMajorPrompt('1.0.0'); - assert.equal(manager2.shouldPromptMajorUpdate('1.0.0'), false); - }); - - test('hasUnreadMinorUpdates identifies unread minor releases without prompting popup', () => { - const manager = UpdatesStateManager.getInstance(mockEntries); - - // Initially user has seen 0.0.0, so 1.1.0 is unread - assert.equal(manager.hasUnreadMinorUpdates('1.1.0'), true); - - // 1.0.0 is major, so hasUnreadMinorUpdates should return false for it - assert.equal(manager.hasUnreadMinorUpdates('1.0.0'), false); - - // Once marked as seen, 1.1.0 is no longer unread - manager.markVersionAsSeen('1.1.0'); - assert.equal(manager.hasUnreadMinorUpdates('1.1.0'), false); - }); - - test('filterEntries accurately filters by importance, category and query', () => { - const manager = UpdatesStateManager.getInstance(mockEntries); - - // Filter by importance - const majorEntries = manager.filterEntries({ importance: 'major' }); - assert.equal(majorEntries.length, 1); - assert.equal(majorEntries[0].version, '1.0.0'); - - // Filter by category - const typoEntries = manager.filterEntries({ category: 'typography' }); - assert.equal(typoEntries.length, 1); - assert.equal(typoEntries[0].version, '1.0.0'); - - // Filter by textual query in Hebrew - const searchHeb = manager.filterEntries({ searchQuery: 'ביצועים' }); - assert.equal(searchHeb.length, 1); - assert.equal(searchHeb[0].version, '1.1.0'); - - // Filter by textual query in English - const searchEng = manager.filterEntries({ searchQuery: 'Huge feature' }); - assert.equal(searchEng.length, 1); - assert.equal(searchEng[0].version, '1.0.0'); - }); - }); - - describe('Localization & i18n Key Coverage', () => { - test('all What\'s New translation keys exist and are non-empty in Hebrew and English', () => { - const requiredKeys = [ - 'whatsNewTitle', - 'whatsNewSubtitle', - 'whatsNewMajorTitle', - 'whatsNewMajorSubtitle', - 'whatsNewBadgeMajor', - 'whatsNewBadgeMinor', - 'whatsNewBadgePatch', - 'whatsNewFilterAll', - 'whatsNewFilterMajor', - 'whatsNewFilterMinor', - 'whatsNewFilterFixes', - 'whatsNewFilterTypography', - 'whatsNewSearchPlaceholder', - 'whatsNewExploreAll', - 'whatsNewGotIt', - 'whatsNewDontShowAgain', - 'whatsNewViewHistory', - 'whatsNewCheckUpdates', - 'whatsNewNoResults', - 'whatsNewCatFeatures', - 'whatsNewCatImprovements', - 'whatsNewCatFixes', - 'whatsNewCatTypography', - 'whatsNewCatPerformance', - 'whatsNewUnreadAria', - 'menuWhatsNew', - 'commandPaletteWhatsNew' - ]; - - for (const k of requiredKeys) { - assert.ok(strings[k], `Missing i18n key: ${k}`); - assert.ok(strings[k].he && strings[k].he.trim().length > 0, `Key ${k} must have Hebrew string`); - assert.ok(strings[k].en && strings[k].en.trim().length > 0, `Key ${k} must have English string`); - } - }); - }); - - describe('UI Component Integration & Wiring', () => { - test('UpdatesDrawer source defines side panel with filter chips and search', () => { - const drawerSrc = fs.readFileSync(path.join(rootDir, 'packages/tok-ui/src/components/UpdatesDrawer.ts'), 'utf8'); - assert.ok(drawerSrc.includes('tok-updates-drawer'), 'Must declare drawer class'); - assert.ok(drawerSrc.includes('tok-filter-chip'), 'Must support filter chips'); - assert.ok(drawerSrc.includes('tok-updates-search-input'), 'Must support search input'); - assert.ok(drawerSrc.includes('populateCards'), 'Must have card populating logic'); - }); - - test('MajorUpdateModal source defines popup dialog with highlights grid and dismissal checkbox', () => { - const modalSrc = fs.readFileSync(path.join(rootDir, 'packages/tok-ui/src/components/MajorUpdateModal.ts'), 'utf8'); - assert.ok(modalSrc.includes('tok-major-dialog'), 'Must declare major dialog class'); - assert.ok(modalSrc.includes('tok-major-showcase-grid'), 'Must include showcase grid'); - assert.ok(modalSrc.includes('dontShowAgainCheckbox'), 'Must include dont-show-again checkbox'); - assert.ok(modalSrc.includes('dismissMajorPrompt'), 'Must hook into dismissal logic'); - }); - +import { test, describe, beforeEach } from 'node:test'; +import assert from 'node:assert/strict'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); +const rootDir = path.resolve(__dirname, '..'); + +import { CHANGELOG_ENTRIES } from '../packages/tok-ui/dist/updates/changelogData.js'; +import { UpdatesStateManager, compareSemver } from '../packages/tok-ui/dist/updates/updatesManager.js'; +import { parseChangelogMarkdown } from '../scripts/sync-changelog.mjs'; +import { strings } from '../packages/tok-ui/dist/i18n.js'; + +describe("What's New System - Full Test Suite", () => { + beforeEach(() => { + UpdatesStateManager.resetInstance(); + }); + + describe('Changelog Registry & Data Integrity', () => { + test('changelog entries exist and are ordered descending by semver', () => { + assert.ok(CHANGELOG_ENTRIES.length >= 3, 'Should have at least 3 historical releases'); + + for (let i = 0; i < CHANGELOG_ENTRIES.length - 1; i++) { + const vCurr = CHANGELOG_ENTRIES[i].version; + const vNext = CHANGELOG_ENTRIES[i + 1].version; + assert.ok( + compareSemver(vCurr, vNext) >= 0, + `Version ${vCurr} should be >= ${vNext}` + ); + } + }); + + test('every entry has complete Hebrew and English metadata', () => { + for (const entry of CHANGELOG_ENTRIES) { + assert.ok(entry.version, 'Entry must have a version'); + assert.match(entry.releaseDate, /^\d{4}-\d{2}-\d{2}$/, 'Release date must be YYYY-MM-DD'); + assert.ok(['major', 'minor', 'patch'].includes(entry.importance), 'Valid importance'); + + // Bilingual title and summary + assert.ok(entry.title?.he && entry.title.he.trim().length > 0, `Hebrew title missing in v${entry.version}`); + assert.ok(entry.title?.en && entry.title.en.trim().length > 0, `English title missing in v${entry.version}`); + assert.ok(entry.summary?.he && entry.summary.he.trim().length > 0, `Hebrew summary missing in v${entry.version}`); + assert.ok(entry.summary?.en && entry.summary.en.trim().length > 0, `English summary missing in v${entry.version}`); + + // Changes + assert.ok(Array.isArray(entry.changes) && entry.changes.length > 0, `Changes missing in v${entry.version}`); + for (const change of entry.changes) { + assert.ok(change.category, 'Category must be defined'); + assert.ok(change.text?.he, 'Hebrew text must be defined'); + assert.ok(change.text?.en, 'English text must be defined'); + } + + // Major releases must contain visual highlight cards + if (entry.importance === 'major') { + assert.ok(Array.isArray(entry.highlights) && entry.highlights.length > 0, `Major release v${entry.version} must have highlights`); + for (const hl of entry.highlights) { + assert.ok(hl.title?.he && hl.title?.en, 'Highlight must have bilingual title'); + assert.ok(hl.description?.he && hl.description?.en, 'Highlight must have bilingual description'); + assert.ok(hl.icon, 'Highlight must specify an icon'); + } + } + } + }); + }); + + describe('CHANGELOG.md Markdown Source-of-Truth & Parser', () => { + test('CHANGELOG.md exists in project root and parses cleanly', () => { + const changelogFile = path.join(rootDir, 'CHANGELOG.md'); + assert.ok(fs.existsSync(changelogFile), 'CHANGELOG.md must exist in root'); + + const content = fs.readFileSync(changelogFile, 'utf8'); + const parsed = parseChangelogMarkdown(content); + + assert.ok(parsed.length >= 3, 'Must parse at least 3 releases'); + const v0304 = parsed.find(e => e.version === '0.30.4'); + assert.ok(v0304, '0.30.4 must be parsed'); + const v0300 = parsed.find(e => e.version === '0.30.0'); + assert.ok(v0300, '0.30.0 must be parsed'); + assert.equal(v0300.importance, 'major'); + assert.ok(v0300.highlights.length >= 4, 'Major release must parse highlights'); + }); + + test('changelogData.ts is in sync with CHANGELOG.md (run npm run sync:changelog)', () => { + const content = fs.readFileSync(path.join(rootDir, 'CHANGELOG.md'), 'utf8'); + const parsed = parseChangelogMarkdown(content); + assert.deepEqual( + CHANGELOG_ENTRIES.map((e) => e.version), + parsed.map((e) => e.version), + 'changelogData.ts is stale compared to CHANGELOG.md' + ); + }); + + test('every change category is one the UI knows how to render', () => { + const allowed = ['features', 'improvements', 'fixes', 'typography', 'performance']; + for (const entry of CHANGELOG_ENTRIES) { + for (const change of entry.changes) { + assert.ok(allowed.includes(change.category), `v${entry.version} uses unknown category "${change.category}"`); + } + } + }); + + test('Strict No-Emoji & No-Vibe-Coding Policy in changelog and UI text', () => { + const emojiRegex = /[\u{1F300}-\u{1F5FF}\u{1F600}-\u{1F64F}\u{1F680}-\u{1F6FF}\u{2600}-\u{26FF}\u{2700}-\u{27BF}\u{1F900}-\u{1F9FF}\u{1FA70}-\u{1FAFF}]/u; + + const changelogContent = fs.readFileSync(path.join(rootDir, 'CHANGELOG.md'), 'utf8'); + assert.equal(emojiRegex.test(changelogContent), false, 'CHANGELOG.md must NOT contain any emojis (official vector icons only)'); + + const dataContent = fs.readFileSync(path.join(rootDir, 'packages/tok-ui/src/updates/changelogData.ts'), 'utf8'); + assert.equal(emojiRegex.test(dataContent), false, 'changelogData.ts must NOT contain any emojis'); + }); + }); + + describe('Semver Comparison Logic', () => { + test('compares standard versions correctly', () => { + assert.equal(compareSemver('0.30.4', '0.30.0'), 1); + assert.equal(compareSemver('0.30.0', '0.30.4'), -1); + assert.equal(compareSemver('0.30.0', '0.30.0'), 0); + }); + + test('handles v prefix and varying component lengths', () => { + assert.equal(compareSemver('v1.0.0', '0.9.9'), 1); + assert.equal(compareSemver('0.30', '0.30.0'), 0); + assert.equal(compareSemver('1.2.3', 'v1.2.3'), 0); + }); + }); + + describe('UpdatesStateManager Business Rules', () => { + const mockEntries = [ + { + version: '1.1.0', + releaseDate: '2026-11-01', + importance: 'minor', + title: { he: 'עדכון קל', en: 'Minor Update' }, + summary: { he: 'תיקונים ושיפורים קטנים', en: 'Small fixes and tweaks' }, + changes: [ + { category: 'improvements', text: { he: 'שיפור ביצועים', en: 'Performance tweak' } }, + { category: 'fixes', text: { he: 'תיקון באג', en: 'Bug fix' } } + ] + }, + { + version: '1.0.0', + releaseDate: '2026-10-15', + importance: 'major', + title: { he: 'גרסה ראשית 1.0', en: 'Major Release 1.0' }, + summary: { he: 'מהפכה במערכת', en: 'Massive milestone' }, + highlights: [ + { + id: 'engine', + title: { he: 'מנוע חדש', en: 'New Engine' }, + description: { he: 'מהיר', en: 'Fast' }, + icon: 'sparkle' + } + ], + changes: [ + { category: 'features', text: { he: 'פיצ׳ר ענק', en: 'Huge feature' } }, + { category: 'typography', text: { he: 'ניקוד מדויק', en: 'Precise niqqud' } } + ] + }, + { + version: '0.9.0', + releaseDate: '2026-09-01', + importance: 'minor', + title: { he: 'גרסה ישנה', en: 'Old version' }, + summary: { he: 'בסיס', en: 'Base' }, + changes: [ + { category: 'features', text: { he: 'בסיס', en: 'Base' } } + ] + } + ]; + + test('shouldPromptMajorUpdate triggers only for unread major releases', () => { + const manager = UpdatesStateManager.getInstance(mockEntries); + + // 1.0.0 is major, hasn't been seen -> true + assert.equal(manager.shouldPromptMajorUpdate('1.0.0'), true); + + // 1.1.0 is minor -> false (minor updates do NOT trigger popup!) + assert.equal(manager.shouldPromptMajorUpdate('1.1.0'), false); + + // After user sees 1.0.0 -> should no longer prompt + manager.markVersionAsSeen('1.0.0'); + assert.equal(manager.shouldPromptMajorUpdate('1.0.0'), false); + + // Dismissing major prompt prevents prompt + UpdatesStateManager.resetInstance(); + const manager2 = UpdatesStateManager.getInstance(mockEntries); + assert.equal(manager2.shouldPromptMajorUpdate('1.0.0'), true); + manager2.dismissMajorPrompt('1.0.0'); + assert.equal(manager2.shouldPromptMajorUpdate('1.0.0'), false); + }); + + test('hasUnreadMinorUpdates identifies unread minor releases without prompting popup', () => { + const manager = UpdatesStateManager.getInstance(mockEntries); + + // Initially user has seen 0.0.0, so 1.1.0 is unread + assert.equal(manager.hasUnreadMinorUpdates('1.1.0'), true); + + // 1.0.0 is major, so hasUnreadMinorUpdates should return false for it + assert.equal(manager.hasUnreadMinorUpdates('1.0.0'), false); + + // Once marked as seen, 1.1.0 is no longer unread + manager.markVersionAsSeen('1.1.0'); + assert.equal(manager.hasUnreadMinorUpdates('1.1.0'), false); + }); + + test('filterEntries accurately filters by importance, category and query', () => { + const manager = UpdatesStateManager.getInstance(mockEntries); + + // Filter by importance + const majorEntries = manager.filterEntries({ importance: 'major' }); + assert.equal(majorEntries.length, 1); + assert.equal(majorEntries[0].version, '1.0.0'); + + // Filter by category + const typoEntries = manager.filterEntries({ category: 'typography' }); + assert.equal(typoEntries.length, 1); + assert.equal(typoEntries[0].version, '1.0.0'); + + // Filter by textual query in Hebrew + const searchHeb = manager.filterEntries({ searchQuery: 'ביצועים' }); + assert.equal(searchHeb.length, 1); + assert.equal(searchHeb[0].version, '1.1.0'); + + // Filter by textual query in English + const searchEng = manager.filterEntries({ searchQuery: 'Huge feature' }); + assert.equal(searchEng.length, 1); + assert.equal(searchEng[0].version, '1.0.0'); + }); + }); + + describe('Localization & i18n Key Coverage', () => { + test('all What\'s New translation keys exist and are non-empty in Hebrew and English', () => { + const requiredKeys = [ + 'whatsNewTitle', + 'whatsNewSubtitle', + 'whatsNewMajorTitle', + 'whatsNewMajorSubtitle', + 'whatsNewBadgeMajor', + 'whatsNewBadgeMinor', + 'whatsNewBadgePatch', + 'whatsNewFilterAll', + 'whatsNewFilterMajor', + 'whatsNewFilterMinor', + 'whatsNewFilterFixes', + 'whatsNewFilterTypography', + 'whatsNewSearchPlaceholder', + 'whatsNewExploreAll', + 'whatsNewGotIt', + 'whatsNewDontShowAgain', + 'whatsNewViewHistory', + 'whatsNewCheckUpdates', + 'whatsNewNoResults', + 'whatsNewCatFeatures', + 'whatsNewCatImprovements', + 'whatsNewCatFixes', + 'whatsNewCatTypography', + 'whatsNewCatPerformance', + 'whatsNewUnreadAria', + 'menuWhatsNew', + 'commandPaletteWhatsNew' + ]; + + for (const k of requiredKeys) { + assert.ok(strings[k], `Missing i18n key: ${k}`); + assert.ok(strings[k].he && strings[k].he.trim().length > 0, `Key ${k} must have Hebrew string`); + assert.ok(strings[k].en && strings[k].en.trim().length > 0, `Key ${k} must have English string`); + } + }); + }); + + describe('UI Component Integration & Wiring', () => { + test('UpdatesDrawer source defines side panel with filter chips and search', () => { + const drawerSrc = fs.readFileSync(path.join(rootDir, 'packages/tok-ui/src/components/UpdatesDrawer.ts'), 'utf8'); + assert.ok(drawerSrc.includes('tok-updates-drawer'), 'Must declare drawer class'); + assert.ok(drawerSrc.includes('tok-filter-chip'), 'Must support filter chips'); + assert.ok(drawerSrc.includes('tok-updates-search-input'), 'Must support search input'); + assert.ok(drawerSrc.includes('populateCards'), 'Must have card populating logic'); + }); + + test('MajorUpdateModal source defines popup dialog with highlights grid and dismissal checkbox', () => { + const modalSrc = fs.readFileSync(path.join(rootDir, 'packages/tok-ui/src/components/MajorUpdateModal.ts'), 'utf8'); + assert.ok(modalSrc.includes('tok-major-dialog'), 'Must declare major dialog class'); + assert.ok(modalSrc.includes('tok-major-showcase-grid'), 'Must include showcase grid'); + assert.ok(modalSrc.includes('dontShowAgainCheckbox'), 'Must include dont-show-again checkbox'); + assert.ok(modalSrc.includes('dismissMajorPrompt'), 'Must hook into dismissal logic'); + }); + test('Left sidebar includes unread bell button and TopSystemBar includes quick menu entry', () => { const inspSrc = fs.readFileSync(path.join(rootDir, 'packages/tok-ui/src/components/ContextualInspector.ts'), 'utf8'); assert.ok(inspSrc.includes('UpdatesBellButton'), 'Left sidebar must use UpdatesBellButton'); @@ -276,20 +295,20 @@ describe("What's New System - Full Test Suite", () => { assert.ok(barSrc.includes('open-whats-new'), 'Must dispatch open-whats-new action'); }); - test('App shell exposes openWhatsNew, openMajorUpdate, and command palette action', () => { - const appSrc = fs.readFileSync(path.join(rootDir, 'packages/tok-ui/src/app.ts'), 'utf8'); - assert.ok(appSrc.includes('openWhatsNew('), 'Must provide openWhatsNew method'); - assert.ok(appSrc.includes('openMajorUpdate('), 'Must provide openMajorUpdate method'); - assert.ok(appSrc.includes('cmd-whats-new'), 'Must register palette command'); - assert.ok(appSrc.includes('checkStartupUpdatesPrompt'), 'Must check updates prompt on startup'); - }); - - test('AboutModal and SettingsModal offer direct links to What\'s New', () => { - const aboutSrc = fs.readFileSync(path.join(rootDir, 'packages/tok-ui/src/components/AboutModal.ts'), 'utf8'); - assert.ok(aboutSrc.includes('whatsNewTitle'), 'AboutModal must link to What\'s New'); - - const settingsSrc = fs.readFileSync(path.join(rootDir, 'packages/tok-ui/src/components/SettingsModal.ts'), 'utf8'); - assert.ok(settingsSrc.includes('whatsNewViewHistory'), 'SettingsModal updates tab must link to What\'s New history'); - }); - }); -}); + test('App shell exposes openWhatsNew, openMajorUpdate, and command palette action', () => { + const appSrc = fs.readFileSync(path.join(rootDir, 'packages/tok-ui/src/app.ts'), 'utf8'); + assert.ok(appSrc.includes('openWhatsNew('), 'Must provide openWhatsNew method'); + assert.ok(appSrc.includes('openMajorUpdate('), 'Must provide openMajorUpdate method'); + assert.ok(appSrc.includes('cmd-whats-new'), 'Must register palette command'); + assert.ok(appSrc.includes('checkStartupUpdatesPrompt'), 'Must check updates prompt on startup'); + }); + + test('AboutModal and SettingsModal offer direct links to What\'s New', () => { + const aboutSrc = fs.readFileSync(path.join(rootDir, 'packages/tok-ui/src/components/AboutModal.ts'), 'utf8'); + assert.ok(aboutSrc.includes('whatsNewTitle'), 'AboutModal must link to What\'s New'); + + const settingsSrc = fs.readFileSync(path.join(rootDir, 'packages/tok-ui/src/components/SettingsModal.ts'), 'utf8'); + assert.ok(settingsSrc.includes('whatsNewViewHistory'), 'SettingsModal updates tab must link to What\'s New history'); + }); + }); +});