diff --git a/common/src/app/common/fonts.cljs b/common/src/app/common/fonts.cljs
index ee96b6c9df..9c30aee95c 100644
--- a/common/src/app/common/fonts.cljs
+++ b/common/src/app/common/fonts.cljs
@@ -163,7 +163,10 @@
(def ^:private unicode-ranges
{:japanese #"[\u3040-\u30FF\u31F0-\u31FF\uFF66-\uFF9F]"
- :chinese #"[\u4E00-\u9FFF\u3400-\u4DBF]"
+ ;; Han ideographs, shared by all CJK languages; see `resolve-ambiguous-cjk`.
+ :han #"[\u4E00-\u9FFF\u3400-\u4DBF\uF900-\uFAFF]"
+ ;; CJK punctuation and half/full-width forms, shared; see `resolve-ambiguous-cjk`.
+ :cjk-punctuation #"[\u3000-\u303F\uFF01-\uFF65\uFFE0-\uFFEE]"
:korean #"[\uAC00-\uD7AF]"
:arabic #"[\u0600-\u06FF\u0750-\u077F\u0870-\u089F\u08A0-\u08FF]"
:cyrillic #"[\u0400-\u04FF\u0500-\u052F\u2DE0-\u2DFF\uA640-\uA69F]"
@@ -241,6 +244,41 @@
used
unicode-ranges))
+(defn- language->cjk-font
+ "CJK font class implied by a BCP 47 language tag or an app locale
+ (`ja`, `zh-Hant-TW`, `zh_hant`), or nil for a non-CJK language."
+ [language]
+ (let [[primary & subtags] (str/split (str/lower (str language)) #"[-_]")
+ subtags (set subtags)]
+ (case primary
+ "ja" :japanese
+ "ko" :korean
+ "zh" (cond
+ (some subtags ["hk" "mo"]) :chinese-hongkong
+ (some subtags ["tw" "hant"]) :chinese-traditional
+ :else :chinese)
+ nil)))
+
+(defn resolve-ambiguous-cjk
+ "Resolves the ambiguous CJK classes (:han, :cjk-punctuation) to a
+ concrete font class: a CJK paragraph `language` wins, then an
+ unambiguous script in the same content (kana implies Japanese, hangul
+ implies Korean), then the app `locale`; Chinese is the final default.
+ `language` and `locale` are nil when unset."
+ [langs language locale]
+ (if (or (contains? langs :han)
+ (contains? langs :cjk-punctuation))
+ (let [resolved (or (language->cjk-font language)
+ (cond
+ (contains? langs :japanese) :japanese
+ (contains? langs :korean) :korean)
+ (language->cjk-font locale)
+ :chinese)]
+ (-> langs
+ (disj :han :cjk-punctuation)
+ (conj resolved)))
+ langs))
+
(defn add-emoji-font
[fonts]
(conj fonts {:font-id "gfont-noto-color-emoji"
@@ -253,6 +291,8 @@
(def noto-fonts
{:japanese {:font-id "gfont-noto-sans-jp" :font-variant-id "regular" :style 0 :weight 400 :is-fallback true}
:chinese {:font-id "gfont-noto-sans-sc" :font-variant-id "regular" :style 0 :weight 400 :is-fallback true}
+ :chinese-traditional {:font-id "gfont-noto-sans-tc" :font-variant-id "regular" :style 0 :weight 400 :is-fallback true}
+ :chinese-hongkong {:font-id "gfont-noto-sans-hk" :font-variant-id "regular" :style 0 :weight 400 :is-fallback true}
:korean {:font-id "gfont-noto-sans-kr" :font-variant-id "regular" :style 0 :weight 400 :is-fallback true}
:arabic {:font-id "gfont-noto-sans-arabic" :font-variant-id "regular" :style 0 :weight 400 :is-fallback true}
:cyrillic {:font-id "gfont-noto-sans" :font-variant-id "regular" :style 0 :weight 400 :is-fallback true}
diff --git a/common/src/app/common/render_wasm/enums.clj b/common/src/app/common/render_wasm/enums.clj
index 0e73f76142..3e3284fcb8 100644
--- a/common/src/app/common/render_wasm/enums.clj
+++ b/common/src/app/common/render_wasm/enums.clj
@@ -36,6 +36,21 @@
["fill-data" "RawFillData"]
["text-align" "RawTextAlign"]
["text-direction" "RawTextDirection"]
+ ["writing-mode" "RawWritingMode"]
+ ["text-orientation" "RawTextOrientation"]
+ ["text-combine-upright" "RawTextCombineUpright"]
+ ["text-emphasis" "RawTextEmphasis"]
+ ["text-emphasis-position" "RawTextEmphasisPosition"]
+ ["text-underline-position" "RawTextUnderlinePosition"]
+ ["warichu" "RawWarichu"]
+ ["font-features" "RawFontFeatures"]
+ ["annotation-clearance" "RawAnnotationClearance"]
+ ["ruby-size" "RawRubySize"]
+ ["ruby-align" "RawRubyAlign"]
+ ["ruby-overhang" "RawRubyOverhang"]
+ ["ruby-side" "RawRubySide"]
+ ["korean-wrap" "RawKoreanWrap"]
+ ["line-adjustment" "RawLineAdjustment"]
["text-decoration" "RawTextDecoration"]
["text-transform" "RawTextTransform"]
["list-style-type" "RawListStyleType"]
diff --git a/common/src/app/common/render_wasm/serializers.cljs b/common/src/app/common/render_wasm/serializers.cljs
index b3db247e10..cbd9a4ef12 100644
--- a/common/src/app/common/render_wasm/serializers.cljs
+++ b/common/src/app/common/render_wasm/serializers.cljs
@@ -9,10 +9,12 @@
[app.common.data :as d]
[app.common.data.macros :as dm]
[app.common.files.helpers :as cfh]
+ [app.common.logging :as log]
[app.common.render-wasm.serializers.color :as sr-clr]
[app.common.render-wasm.wasm :as wasm]
[app.common.types.color :as clr]
[app.common.types.shape-tree :as ctst]
+ [app.common.types.text.cjk-layout :as cjk]
[app.common.uuid :as uuid]
[cuerdas.core :as str]))
@@ -312,6 +314,21 @@
[list-style-type]
(untranslate "list-style-type" list-style-type "none"))
+(defn translate-text-layout-enum
+ "Wasm discriminant of the value of the CJK text layout enum `attr`. An
+ unset value takes the default; an unknown one also takes it, with a
+ warning, since content validation should have rejected it. 0 when the
+ enum is not exported."
+ [attr value]
+ (let [default (cjk/enum-default attr)
+ value (some-> value d/name)
+ value (if (str/blank? value) default value)]
+ (if-let [values (unchecked-get wasm/serializers (name attr))]
+ (if-let [discriminant (unchecked-get values value)]
+ discriminant
+ (do (log/wrn :hint "unknown text layout value" :attr attr :value value)
+ (unchecked-get values default)))
+ 0)))
(defn translate-font-style
[font-style]
diff --git a/common/src/app/common/render_wasm/text_content.cljs b/common/src/app/common/render_wasm/text_content.cljs
index a19fb47c47..60d3384cd3 100644
--- a/common/src/app/common/render_wasm/text_content.cljs
+++ b/common/src/app/common/render_wasm/text_content.cljs
@@ -6,8 +6,9 @@
(ns app.common.render-wasm.text-content
"Single source of truth for writing a text shape's content into the WASM design
- state. The binary layout ([num-spans][paragraph attrs][span attrs][text]) is
- identical for the workspace and the headless exporter, and so is the font-id
+ state. The binary layout is [num-spans][paragraph attrs][span attrs][text]
+ [ruby-text][language], identical for the workspace and headless exporter.
+ Both hosts also share the font-id
-> uuid mapping (`cfnt/font-id->uuid`). Only *variant* resolution differs —
the workspace has a loaded fonts DB, the exporter does not — so that part is
injected via the `opts` map passed to `write-shape-text!`.
@@ -21,11 +22,12 @@
[app.common.render-wasm.serializers :as sr]
[app.common.render-wasm.wasm :as wasm]
[app.common.types.fills.impl :as types.fills.impl]
+ [app.common.types.text.cjk-layout :as cjk]
[app.common.uuid :as uuid]
[cuerdas.core :as str]))
-(def ^:const PARAGRAPH-ATTR-U8-SIZE 16)
-(def ^:const SPAN-ATTR-U8-SIZE 64)
+(def ^:const PARAGRAPH-ATTR-U8-SIZE 20)
+(def ^:const SPAN-ATTR-U8-SIZE 80)
(def ^:const MAX-TEXT-FILLS types.fills.impl/MAX-FILLS)
(def ^:private default-font-size 14)
@@ -75,6 +77,13 @@
;; --- binary writers --------------------------------------------------------
+(defn- span-ruby
+ "Ruby annotation text sent to WASM; hidden ruby is omitted."
+ [span]
+ (if (true? (:ruby-hidden span))
+ ""
+ (d/nilv (:ruby span) "")))
+
(defn- encode-text
"Into an UTF8 buffer. Returns an ArrayBuffer instance."
[text]
@@ -104,13 +113,16 @@
(defn- write-paragraph
[offset dview paragraph]
- (let [text-align (sr/translate-text-align (get paragraph :text-align))
- text-direction (sr/translate-text-direction (get paragraph :text-direction))
- text-decoration (sr/translate-text-decoration (get paragraph :text-decoration))
- text-transform (sr/translate-text-transform (get paragraph :text-transform))
- line-height (serialize-line-height (get paragraph :line-height))
- letter-spacing (serialize-letter-spacing (get paragraph :letter-spacing))
- list-style-type (sr/translate-list-style-type (get paragraph :list-style-type))]
+ (let [text-align (sr/translate-text-align (get paragraph :text-align))
+ text-direction (sr/translate-text-direction (get paragraph :text-direction))
+ text-decoration (sr/translate-text-decoration (get paragraph :text-decoration))
+ text-transform (sr/translate-text-transform (get paragraph :text-transform))
+ writing-mode (sr/translate-text-layout-enum :writing-mode (get paragraph :writing-mode))
+ text-orientation (sr/translate-text-layout-enum :text-orientation (get paragraph :text-orientation))
+ korean-wrap (sr/translate-text-layout-enum :korean-wrap (get paragraph :korean-wrap))
+ line-height (serialize-line-height (get paragraph :line-height))
+ letter-spacing (serialize-letter-spacing (get paragraph :letter-spacing))
+ list-style-type (sr/translate-list-style-type (get paragraph :list-style-type))]
(-> offset
(mem/write-u8 dview text-align)
(mem/write-u8 dview text-direction)
@@ -119,10 +131,10 @@
(mem/write-f32 dview line-height)
(mem/write-f32 dview letter-spacing)
(mem/write-u8 dview list-style-type)
- ;; padding
- (mem/write-u8 dview 0)
- (mem/write-u8 dview 0)
- (mem/write-u8 dview 0)
+ (mem/write-u8 dview writing-mode)
+ (mem/write-u8 dview text-orientation)
+ (mem/write-u8 dview korean-wrap)
+ (mem/write-u32 dview (mem/size (encode-text (d/nilv (:text-language paragraph) ""))))
(mem/assert-written offset PARAGRAPH-ATTR-U8-SIZE))))
(defn- write-spans
@@ -131,7 +143,7 @@
paragraph-font-weight (-> paragraph :font-weight serialize-font-weight)
paragraph-line-height (serialize-line-height (get paragraph :line-height))]
(reduce
- (fn [offset span]
+ (fn [offset [previous span]]
(let [font-style (sr/translate-font-style (get span :font-style "normal"))
font-size (serialize-font-size (get span :font-size paragraph-font-size))
line-height (serialize-line-height (get span :line-height) paragraph-line-height)
@@ -141,6 +153,8 @@
font-family (hash (get span :font-family "sourcesanspro"))
text-buffer (encode-text (get span :text ""))
text-length (mem/size text-buffer)
+ ruby-buffer (encode-text (span-ruby span))
+ ruby-length (mem/size ruby-buffer)
fills (take MAX-TEXT-FILLS (get span :fills []))
font-variant-id (get span :font-variant-id)
font-variant-id (if (uuid? font-variant-id) font-variant-id uuid/zero)
@@ -152,12 +166,43 @@
(sr/translate-text-transform "none"))
text-direction (or (sr/translate-text-direction (:text-direction span))
(sr/translate-text-direction (:text-direction paragraph))
- (sr/translate-text-direction "ltr"))]
+ (sr/translate-text-direction "ltr"))
+ text-orientation (sr/translate-text-layout-enum
+ :text-orientation
+ (get span :text-orientation (get paragraph :text-orientation)))
+ text-combine-upright (sr/translate-text-layout-enum :text-combine-upright (get span :text-combine-upright))
+ text-emphasis (sr/translate-text-layout-enum :text-emphasis (get span :text-emphasis))
+ warichu (sr/translate-text-layout-enum :warichu (get span :warichu))
+ font-features (sr/translate-text-layout-enum :font-features (get span :font-features))
+ annotation-clearance (sr/translate-text-layout-enum :annotation-clearance (get span :annotation-clearance))
+ ruby-size (sr/translate-text-layout-enum :ruby-size (get span :ruby-size))
+ ruby-align (sr/translate-text-layout-enum :ruby-align (get span :ruby-align))
+ ruby-overhang (sr/translate-text-layout-enum :ruby-overhang (get span :ruby-overhang))
+ ruby-side (sr/translate-text-layout-enum :ruby-side (get span :ruby-side))
+ emphasis-position (sr/translate-text-layout-enum :text-emphasis-position (get span :text-emphasis-position))
+ underline-position (sr/translate-text-layout-enum :text-underline-position (get span :text-underline-position))]
(-> offset
(mem/write-u8 dview font-style)
(mem/write-u8 dview text-decoration)
(mem/write-u8 dview text-transform)
(mem/write-u8 dview text-direction)
+ (mem/write-u8 dview text-orientation)
+ (mem/write-u8 dview text-combine-upright)
+ (mem/write-u8 dview text-emphasis)
+ (mem/write-u8 dview warichu)
+ (mem/write-u8 dview font-features)
+ (mem/write-u8 dview annotation-clearance)
+ (mem/write-u8 dview ruby-size)
+ (mem/write-u8 dview ruby-align)
+ (mem/write-u8 dview ruby-overhang)
+ ;; Bit 1 selects Zhuyin; bit 2 joins the span to the reading of
+ ;; the span before it (`cjk/ruby-groups`).
+ (mem/write-u8 dview (bit-or ruby-side
+ (if (true? (:ruby-zhuyin span)) 2 0)
+ (if (cjk/ruby-joins-previous? previous span) 4 0)))
+ ;; Use the former padding bytes; the span header stays the same size.
+ (mem/write-u8 dview emphasis-position)
+ (mem/write-u8 dview underline-position)
(mem/write-f32 dview font-size)
(mem/write-f32 dview line-height)
(mem/write-f32 dview letter-spacing)
@@ -166,15 +211,18 @@
(mem/write-i32 dview font-family)
(mem/write-uuid dview (d/nilv font-variant-id uuid/zero))
(mem/write-i32 dview text-length)
+ (mem/write-i32 dview ruby-length)
(mem/write-i32 dview (count fills))
(mem/assert-written offset SPAN-ATTR-U8-SIZE)
(write-span-fills dview fills))))
offset
- spans)))
+ (map vector (cons nil spans) spans))))
(defn write-shape-text!
"Writes one paragraph's spans + text into WASM and appends it to the current
- shape via `_set_shape_text_content`.
+ shape via `_set_shape_text_content`. Ruby annotations are concatenated per
+ span, in span order, after the base text; the reader splits them using the
+ per-span byte lengths.
`opts` injects host-specific font handling:
- `:normalize-font-id` (string font-id -> wasm uuid) defaults to the shared
@@ -187,21 +235,26 @@
:or {normalize-font-id cfnt/font-id->uuid
normalize-paragraph identity
normalize-span (fn [span _paragraph] span)}}]
- (let [paragraph (normalize-paragraph paragraph)
- spans (map #(normalize-span % paragraph) spans)
- num-spans (count spans)
- fills-size (* types.fills.impl/FILL-U8-SIZE MAX-TEXT-FILLS)
- metadata-size (+ PARAGRAPH-ATTR-U8-SIZE
- (* num-spans (+ SPAN-ATTR-U8-SIZE fills-size)))
- text-buffer (encode-text text)
- text-size (mem/size text-buffer)
- total-size (+ 4 metadata-size text-size)
- offset (mem/alloc total-size)
- heapu8 (mem/get-heap-u8)
- dview (mem/get-data-view)]
+ (let [paragraph (normalize-paragraph paragraph)
+ spans (map #(normalize-span % paragraph) spans)
+ num-spans (count spans)
+ fills-size (* types.fills.impl/FILL-U8-SIZE MAX-TEXT-FILLS)
+ metadata-size (+ PARAGRAPH-ATTR-U8-SIZE
+ (* num-spans (+ SPAN-ATTR-U8-SIZE fills-size)))
+ text-buffer (encode-text text)
+ text-size (mem/size text-buffer)
+ ruby-buffer (encode-text (apply str (map span-ruby spans)))
+ ruby-size (mem/size ruby-buffer)
+ language-buffer (encode-text (d/nilv (:text-language paragraph) ""))
+ total-size (+ 4 metadata-size text-size ruby-size (mem/size language-buffer))
+ offset (mem/alloc total-size)
+ heapu8 (mem/get-heap-u8)
+ dview (mem/get-data-view)]
(-> offset
(mem/write-u32 dview num-spans)
(write-paragraph dview paragraph)
(write-spans dview spans paragraph normalize-font-id)
- (mem/write-buffer heapu8 text-buffer))
+ (mem/write-buffer heapu8 text-buffer)
+ (mem/write-buffer heapu8 ruby-buffer)
+ (mem/write-buffer heapu8 language-buffer))
(h/call wasm/internal-module "_set_shape_text_content")))
diff --git a/exporter/src/app/wasm/render.cljs b/exporter/src/app/wasm/render.cljs
index 7889a6e3c5..d3becb8d33 100644
--- a/exporter/src/app/wasm/render.cljs
+++ b/exporter/src/app/wasm/render.cljs
@@ -298,14 +298,24 @@
several languages map to one noto family and provisioning is concurrent —
otherwise they all miss the byte cache at once and refetch the same TTF."
[scene]
- (let [texts (for [shape (vals scene)
- :when (= :text (:type shape))
- node (or (some->> (:content shape) (tree-seq :children :children)) [])
- :let [text (:text node)]
- :when (string? text)]
- text)
- emoji? (boolean (some cfnt/contains-emoji? texts))
- langs (reduce cfnt/collect-used-languages #{} texts)]
+ (let [paragraphs (for [shape (vals scene)
+ :when (= :text (:type shape))
+ node (or (some->> (:content shape) (tree-seq :children :children)) [])
+ :when (= "paragraph" (:type node))]
+ node)
+ ;; Base text and ruby readings of each paragraph, which share its language.
+ texts (map (fn [paragraph]
+ (apply str (mapcat (juxt :text :ruby) (:children paragraph))))
+ paragraphs)
+ emoji? (boolean (some cfnt/contains-emoji? texts))
+ ;; The exporter has no user locale: Han follows the paragraph language,
+ ;; else the content, else Chinese.
+ langs (reduce into #{}
+ (map (fn [paragraph text]
+ (-> (cfnt/collect-used-languages #{} text)
+ (cfnt/resolve-ambiguous-cjk (:text-language paragraph) nil)))
+ paragraphs
+ texts))]
(distinct
(cond-> (cfnt/add-noto-fonts [] langs)
emoji? (cfnt/add-emoji-font)))))
diff --git a/exporter/src/app/wasm/text.cljs b/exporter/src/app/wasm/text.cljs
index 13b037652b..33dd4ad470 100644
--- a/exporter/src/app/wasm/text.cljs
+++ b/exporter/src/app/wasm/text.cljs
@@ -16,7 +16,8 @@
(defn set-shape-text!
"Serializes a text shape's content into the current WASM shape. Mirrors the
- editor's sequence: clear -> vertical-align -> append each paragraph -> layout.
+ editor's sequence: clear -> vertical-align and line adjustment -> append each
+ paragraph -> layout.
Byte writing and font resolution are the shared
`text-content/write-shape-text!` defaults; the exporter has no fonts DB, so
it injects no variant normalization."
@@ -25,6 +26,8 @@
(h/call wasm/internal-module "_clear_shape_text")
(h/call wasm/internal-module "_set_shape_vertical_align"
(sr/translate-vertical-align (get content :vertical-align)))
+ (h/call wasm/internal-module "_set_shape_line_adjustment"
+ (sr/translate-text-layout-enum :line-adjustment (get content :line-adjustment)))
(let [paragraph-set (first (get content :children))
paragraphs (get paragraph-set :children)]
(doseq [paragraph paragraphs]
diff --git a/frontend/src/app/main/ui/shapes/text/fo_text.cljs b/frontend/src/app/main/ui/shapes/text/fo_text.cljs
index 13927d2fce..41cd9153dd 100644
--- a/frontend/src/app/main/ui/shapes/text/fo_text.cljs
+++ b/frontend/src/app/main/ui/shapes/text/fo_text.cljs
@@ -10,7 +10,9 @@
[app.common.data.macros :as dm]
[app.common.geom.shapes :as gsh]
[app.common.types.color :as cc]
+ [app.common.types.text.cjk-layout :as cjk]
[app.main.ui.shapes.text.styles :as sts]
+ [app.util.text.writing-mode :as wm]
[cuerdas.core :as str]
[rumext.v2 :as mf]))
@@ -19,9 +21,32 @@
(let [text (:text node)
style (if (= text "")
(sts/generate-text-styles shape parent)
- (sts/generate-text-styles shape node))]
- [:span.text-node {:style style}
- (if (= text "") "\u00A0" text)]))
+ (sts/generate-text-styles shape node))
+ ruby (cjk/visible-ruby node)]
+ (if (some? ruby)
+ [:ruby.ruby-node {:style (sts/generate-ruby-container-styles node)}
+ [:span.text-node {:style style} (sts/text-children text node)]
+ [:rt {:style (sts/generate-ruby-styles shape node)} ruby]]
+ [:span.text-node {:style style}
+ (if (= text "") "\u00A0" (sts/text-children text node))])))
+
+(mf/defc render-ruby-group*
+ "One reading over the text `nodes` of its base (`cjk/ruby-groups`), each
+ node with its own style. The first node holds the reading."
+ {::mf/private true}
+ [{:keys [nodes shape]}]
+ (let [node (first nodes)
+ ruby (cjk/visible-ruby node)]
+ (if (some? ruby)
+ [:ruby.ruby-node {:style (sts/generate-ruby-container-styles node)}
+ (for [[index node] (d/enumerate nodes)]
+ [:span.text-node {:key index :style (sts/generate-text-styles shape node)}
+ (sts/text-children (:text node) node)])
+ [:rt {:style (sts/generate-ruby-styles shape node)} ruby]]
+ [:*
+ (for [[index node] (d/enumerate nodes)]
+ [:span.text-node {:key index :style (sts/generate-text-styles shape node)}
+ (sts/text-children (:text node) node)])])))
(mf/defc render-root*
[{:keys [node children shape]}]
@@ -55,10 +80,15 @@
"paragraph" render-paragraph*
nil)]
(when component
- [:> component props
- (for [[index child-node] (d/enumerate children)]
- [:> render-node*
- (mf/spread-props props {:node child-node :index index :key index})])])))))
+ (let [children (vec children)]
+ [:> component props
+ (for [[start end] (cjk/ruby-base-runs children)]
+ (if (= (inc start) end)
+ [:> render-node*
+ (mf/spread-props props {:node (nth children start) :index start :key start})]
+ [:> render-ruby-group* {:key start
+ :nodes (subvec children start end)
+ :shape (unchecked-get props "shape")}]))]))))))
(defn- next-color
"Given a set of colors try to get a color not yet used"
@@ -164,7 +194,10 @@
y (dm/get-prop shape :y)
width (dm/get-prop shape :width)
height (dm/get-prop shape :height)
- content (get shape :content)
+ content (wm/renderable-content (get shape :content))
+
+ ;; Vertical text anchors columns to the box edges, so it skips the oversized auto-grow box.
+ vertical? (wm/vertical-text-content? content)
[colors _color-mapping color-mapping-inverse] (retrieve-colors shape)]
@@ -175,8 +208,8 @@
:data-colors (str/join "," colors)
:data-mapping (-> color-mapping-inverse clj->js js/JSON.stringify)
:transform transform
- :width (if (#{:auto-width} grow-type) 100000 width)
- :height (if (#{:auto-height :auto-width} grow-type) 100000 height)
+ :width (if (and (not vertical?) (#{:auto-width} grow-type)) 100000 width)
+ :height (if (and (not vertical?) (#{:auto-height :auto-width} grow-type)) 100000 height)
:ref ref}
;; We use a class here because react has a bug that won't use the appropriate selector for
;; `background-clip`
diff --git a/frontend/src/app/main/ui/shapes/text/html_text.cljs b/frontend/src/app/main/ui/shapes/text/html_text.cljs
index 7ffd80c38c..680d19c288 100644
--- a/frontend/src/app/main/ui/shapes/text/html_text.cljs
+++ b/frontend/src/app/main/ui/shapes/text/html_text.cljs
@@ -10,7 +10,9 @@
[app.common.data.macros :as dm]
[app.common.text :as legacy.txt]
[app.common.types.text :as txt]
+ [app.common.types.text.cjk-layout :as cjk]
[app.main.ui.shapes.text.styles :as sts]
+ [app.util.text.writing-mode :as wm]
[rumext.v2 :as mf]))
(mf/defc render-text*
@@ -19,9 +21,60 @@
style (if (= text "")
(sts/generate-text-styles shape parent)
(sts/generate-text-styles shape node))
- class (when is-code (:$id node))]
- [:span.text-node {:style style :class class}
- (if (= text "") "\u00A0" text)]))
+ class (when is-code (:$id node))
+ ruby (cjk/visible-ruby node)]
+ (cond
+ (and (true? (:ruby-zhuyin node)) (cjk/zhuyin-base? text) (cjk/zhuyin-reading? ruby))
+ [:span {:style #js {:display "inline-block" :position "relative"
+ :width "1.6em" :height "1em" :verticalAlign "middle"
+ :writingMode "horizontal-tb" :direction "ltr"
+ :fontSize (.-fontSize style) :fontFamily (.-fontFamily style)
+ :fontWeight (.-fontWeight style) :fontStyle (.-fontStyle style)}
+ :class (when is-code (dm/str class "-ruby"))}
+ [:span.text-node {:style style :class class} (sts/text-children text node)]
+ (for [[idx slot] (d/enumerate (cjk/zhuyin-slots ruby))]
+ [:span {:key idx :style #js {:position "absolute" :writingMode "horizontal-tb"
+ :left (dm/str (+ 1 (:x slot)) "em")
+ :top (dm/str (:y slot) "em")
+ :transform "translate(-50%, -50%)" :lineHeight 1}}
+ [:span {:style #js {:fontSize "0.3em"}} (:text slot)]])]
+
+ (some? ruby)
+ [:ruby.ruby-node {:style (sts/generate-ruby-container-styles node)
+ :class (when is-code (dm/str class "-ruby"))}
+ [:span.text-node {:style style :class class} (sts/text-children text node)]
+ [:rt {:style (sts/generate-ruby-styles shape node)
+ :class (when is-code (dm/str class "-rt"))}
+ ruby]]
+ :else
+ [:span.text-node {:style style :class class}
+ (if (= text "") "\u00A0" (sts/text-children text node))])))
+
+(mf/defc render-ruby-group*
+ "One reading over the text `nodes` of its base (`cjk/ruby-groups`), each
+ node with its own style. The first node holds the reading."
+ {::mf/private true}
+ [{:keys [nodes shape is-code]}]
+ (let [node (first nodes)
+ class (when is-code (:$id node))
+ ruby (cjk/visible-ruby node)]
+ (if (some? ruby)
+ [:ruby.ruby-node {:style (sts/generate-ruby-container-styles node)
+ :class (when is-code (dm/str class "-ruby"))}
+ (for [[index node] (d/enumerate nodes)]
+ [:span.text-node {:key index
+ :style (sts/generate-text-styles shape node)
+ :class (when is-code (:$id node))}
+ (sts/text-children (:text node) node)])
+ [:rt {:style (sts/generate-ruby-styles shape node)
+ :class (when is-code (dm/str class "-rt"))}
+ ruby]]
+ [:*
+ (for [[index node] (d/enumerate nodes)]
+ [:span.text-node {:key index
+ :style (sts/generate-text-styles shape node)
+ :class (when is-code (:$id node))}
+ (sts/text-children (:text node) node)])])))
(mf/defc render-root*
[{:keys [node children shape is-code]}]
@@ -50,6 +103,26 @@
(declare render-node*)
+(defn- render-ruby-runs
+ "Text nodes of `paragraph`, with the nodes of a ruby base spanning several
+ of them (`cjk/ruby-base-runs`) drawn under one reading."
+ [props paragraph is-code]
+ (let [children (vec (:children paragraph))]
+ (for [[start end] (cjk/ruby-base-runs children)]
+ (if (= (inc start) end)
+ (mf/html
+ [:> render-node*
+ (mf/spread-props props
+ {:node (nth children start)
+ :parent paragraph
+ :index start
+ :key start})])
+ (mf/html
+ [:> render-ruby-group* {:key start
+ :nodes (subvec children start end)
+ :shape (unchecked-get props "shape")
+ :is-code is-code}])))))
+
(defn- render-children
"Child elements of `parent`. In code mode, runs of list paragraphs are
grouped into a `
` of `- `."
@@ -66,7 +139,11 @@
:is-list-item is-list-item})]))
children (d/enumerate (:children parent))]
- (if (and is-code (= "paragraph-set" (:type parent)))
+ (cond
+ (= "paragraph" (:type parent))
+ (render-ruby-runs props parent is-code)
+
+ (and is-code (= "paragraph-set" (:type parent)))
(mapcat (fn [run]
(if (txt/list-paragraph? (second (first run)))
[(mf/html
@@ -75,6 +152,8 @@
(render-child child true))])]
(map #(render-child % false) run)))
(partition-by (comp txt/list-paragraph? second) children))
+
+ :else
(map #(render-child % false) children))))
;; -- Text nodes
@@ -98,7 +177,13 @@
[{:keys [shape grow-type is-code]} ref]
(let [{:keys [id x y width height content]} shape
- content (if is-code (legacy.txt/index-content content) content)
+ ;; Generated code keeps the writing mode whatever the renderer.
+ content (if is-code
+ (legacy.txt/index-content content)
+ (wm/renderable-content content))
+
+ ;; Vertical text anchors columns to the box edges, so it skips the oversized auto-grow box.
+ vertical? (wm/vertical-text-content? content)
style
(when-not is-code
@@ -106,8 +191,8 @@
:left 0
:top 0
:background "white"
- :width (if (#{:auto-width} grow-type) 100000 width)
- :height (if (#{:auto-height :auto-width} grow-type) 100000 height)})]
+ :width (if (and (not vertical?) (#{:auto-width} grow-type)) 100000 width)
+ :height (if (and (not vertical?) (#{:auto-height :auto-width} grow-type)) 100000 height)})]
[:div.text-node-html
{:id (dm/str "html-text-node-" id)
diff --git a/frontend/src/app/main/ui/shapes/text/styles.cljs b/frontend/src/app/main/ui/shapes/text/styles.cljs
index 657857f667..5647f3a9aa 100644
--- a/frontend/src/app/main/ui/shapes/text/styles.cljs
+++ b/frontend/src/app/main/ui/shapes/text/styles.cljs
@@ -10,17 +10,23 @@
[app.common.transit :as transit]
[app.common.types.color :as cc]
[app.common.types.text :as txt]
+ [app.common.types.text.cjk-layout :as cjk]
[app.main.fonts :as fonts]
[app.main.ui.formats :as fmt]
[app.util.color :as uc]
[app.util.object :as obj]
- [cuerdas.core :as str]))
+ [cuerdas.core :as str]
+ [rumext.v2 :as mf]))
(defn generate-root-styles
+ "Root styles. `code?` leaves out the box size, which generated code sets
+ elsewhere. The root writing mode makes paragraph blocks stack
+ right-to-left."
([props node]
(generate-root-styles props node false))
([{:keys [width height]} node code?]
(let [valign (:vertical-align node "top")
+ writing-mode (cjk/stored-writing-mode node)
base #js {:height (when-not code? (fmt/format-pixels height))
:width (when-not code? (fmt/format-pixels width))
:display "flex"
@@ -28,7 +34,8 @@
(cond-> base
(= valign "top") (obj/set! "alignItems" "flex-start")
(= valign "center") (obj/set! "alignItems" "center")
- (= valign "bottom") (obj/set! "alignItems" "flex-end")))))
+ (= valign "bottom") (obj/set! "alignItems" "flex-end")
+ (some? writing-mode) (obj/set! "writingMode" writing-mode)))))
(defn generate-paragraph-set-styles
[{:keys [grow-type] :as shape}]
@@ -55,15 +62,122 @@
line-height
(:line-height txt/default-typography))
- text-align (:text-align data "start")
- base #js {;; Fix a problem when exporting HTML
- :fontSize 0
- :lineHeight line-height
- :margin 0}]
+ chinese (and (string? (:text-language data))
+ (= "zh" (first (str/split (str/lower (:text-language data)) #"-"))))
+ text-align (:text-align data "start")
+ writing-mode (:writing-mode data)
+ text-orientation (:text-orientation data)
+ base #js {;; Fix a problem when exporting HTML
+ :fontSize 0
+ :lineHeight line-height
+ :margin 0}]
(cond-> base
+ chinese (obj/set! "textEmphasisPosition" "under right")
+ chinese (obj/set! "textUnderlinePosition" "under left")
(some? line-height) (obj/set! "lineHeight" line-height)
- (some? text-align) (obj/set! "textAlign" text-align))))
+ (some? line-height) (obj/set! "--paragraph-line-height" (str line-height))
+ (some? text-align) (obj/set! "textAlign" text-align)
+ (= text-align "distribute") (obj/set! "textAlign" "justify")
+ (= text-align "distribute") (obj/set! "textAlignLast" "justify")
+ (= text-align "distribute") (obj/set! "textJustify" "inter-character")
+ (some? writing-mode) (obj/set! "writingMode" writing-mode)
+ (some? writing-mode) (obj/set! "textSpacingTrim" "normal")
+ (= writing-mode "vertical-rl") (obj/set! "textAutospace" "normal")
+ (some? text-orientation) (obj/set! "textOrientation" text-orientation))))
+
+(defn css-text-combine-upright
+ "CSS value for a persisted text-combine-upright, or nil for the digits
+ variants: browsers do not support CSS `digits `, so renderers wrap each
+ digit run (`cjk/digit-combine-segments`) in an `all` span instead."
+ [value]
+ (when-not (cjk/digit-combine? value)
+ value))
+
+;; Style of a combined digit run inside a `digits` span.
+(def tcy-run-style #js {:textCombineUpright "all"})
+
+(defn text-children
+ "Text of a node, with each combined digit run of a `digits` tate-chu-yoko
+ in its own `all` span (class `tcy` for generated code)."
+ [text node]
+ (if-let [segments (cjk/digit-combine-segments text (:text-combine-upright node))]
+ (into-array
+ (for [[index [run combine?]] (d/enumerate segments)]
+ (if combine?
+ (mf/html [:span.tcy {:key index :style tcy-run-style} run])
+ run)))
+ text))
+
+(defn- set-value?
+ "True for a stored style value other than empty or \"none\"."
+ [value]
+ (and (string? value) (pos? (alength value)) (not= "none" value)))
+
+(defn font-feature-settings
+ "CSS `font-feature-settings` for a persisted font-features value, or nil."
+ [font-features]
+ (when (set-value? font-features)
+ (str/format "\"%s\"" font-features)))
+
+(defn- annotation-line-height
+ "CSS line height that adds the room of automatic annotation clearance (the
+ ruby at its size plus the emphasis marks) to the paragraph line height,
+ which paragraphs expose as `--paragraph-line-height`. A span's own line
+ height wins when larger, as in the renderer. Nil under `none`."
+ [data]
+ (when (= "auto" (:annotation-clearance data))
+ (let [room (+ (if (cjk/visible-ruby data) (cjk/ruby-font-scale (:ruby-size data)) 0)
+ (if (set-value? (:text-emphasis data)) cjk/emphasis-font-scale 0))
+ paragraph (str "var(--paragraph-line-height, "
+ (:line-height txt/default-typography) ")")
+ own (js/parseFloat (:line-height data))
+ base (if (js/isNaN own)
+ paragraph
+ (str "max(" paragraph ", " own ")"))]
+ (when (pos? room)
+ (str "calc(" base " + " (fmt/format-number room) ")")))))
+
+(defn- add-cjk-text-styles!
+ [style data]
+ (let [text-combine-upright (:text-combine-upright data)
+ text-emphasis (:text-emphasis data)
+ emphasis-position (:text-emphasis-position data)
+ underline-position (:text-underline-position data)
+ font-features (font-feature-settings (:font-features data))
+ line-height (annotation-line-height data)
+ font-size (:font-size data)]
+ (cond-> style
+ (some? (css-text-combine-upright text-combine-upright))
+ (obj/set! "textCombineUpright" (css-text-combine-upright text-combine-upright))
+
+ ;; Stored kebab values ("filled-dot") become the CSS " "
+ ;; pair ("filled dot").
+ (set-value? text-emphasis)
+ (obj/set! "textEmphasis" (str/replace text-emphasis "-" " "))
+
+ (some? emphasis-position)
+ (obj/set! "textEmphasisPosition" (if (= "auto" emphasis-position) "inherit" (str/replace emphasis-position "-" " ")))
+
+ (some? underline-position)
+ (obj/set! "textUnderlinePosition" (if (= "auto" underline-position) "inherit" (str/replace underline-position "-" " ")))
+
+ (some? font-features)
+ (obj/set! "fontFeatureSettings" font-features)
+
+ (some? line-height)
+ (obj/set! "lineHeight" line-height)
+
+ ;; Warichu (割注): a half-size inline-block as wide as half the
+ ;; characters, so the browser wraps it into two sub-lines.
+ (cjk/warichu-text? data)
+ (-> (obj/set! "display" "inline-block")
+ (obj/set! "fontSize" (if (and (string? font-size) (pos? (alength font-size)))
+ (str (* (js/parseFloat font-size) cjk/warichu-font-scale) "px")
+ "50%"))
+ (obj/set! "lineHeight" "1")
+ (obj/set! "inlineSize"
+ (str (js/Math.ceil (/ (alength (js/Array.from (:text data))) 2)) "em"))))))
(defn generate-text-styles
([shape data]
@@ -154,4 +268,45 @@
(obj/set! "fontWeight" font-weight))
(= grow-type :auto-width)
- (obj/set! "whiteSpace" "pre")))))
+ (obj/set! "whiteSpace" "pre")
+
+ :always
+ (add-cjk-text-styles! data)))))
+
+(defn- ruby-font-size
+ "Pixel size of a span's ruby text. Paragraphs set font-size 0, so a
+ relative size would resolve to nothing."
+ [data]
+ (let [font-size (:font-size data)
+ font-size (js/parseFloat (if (and (string? font-size) (pos? (alength font-size)))
+ font-size
+ (:font-size txt/default-typography)))]
+ (str (* font-size (cjk/ruby-font-scale (:ruby-size data))) "px")))
+
+(defn generate-ruby-styles
+ [shape data]
+ (-> (generate-text-styles shape data)
+ (obj/set! "fontSize" (ruby-font-size data))
+ (obj/set! "lineHeight" "1")
+ (obj/set! "textDecoration" "none")
+ ;; Base-span styles that belong to the base glyphs, not the reading.
+ (obj/unset! "textCombineUpright")
+ (obj/unset! "textEmphasis")
+ (obj/unset! "textEmphasisPosition")
+ (obj/unset! "textUnderlinePosition")
+ (obj/unset! "fontFeatureSettings")
+ (obj/unset! "display")
+ (obj/unset! "inlineSize")))
+
+(defn- enum-or-default
+ "Value of the CJK layout enum `attr` in `data`, or its default when
+ unset or unknown."
+ [data attr]
+ (let [value (get data attr)]
+ (if (cjk/valid-enum-value? attr value) value (cjk/enum-default attr))))
+
+(defn generate-ruby-container-styles
+ [data]
+ #js {:rubyPosition (enum-or-default data :ruby-side)
+ :rubyAlign (enum-or-default data :ruby-align)
+ :rubyOverhang (enum-or-default data :ruby-overhang)})
diff --git a/frontend/src/app/main/ui/shapes/text/svg_text.cljs b/frontend/src/app/main/ui/shapes/text/svg_text.cljs
index a2fbdd1ea5..761e353bd1 100644
--- a/frontend/src/app/main/ui/shapes/text/svg_text.cljs
+++ b/frontend/src/app/main/ui/shapes/text/svg_text.cljs
@@ -9,17 +9,187 @@
[app.common.data :as d]
[app.common.data.macros :as dm]
[app.common.geom.shapes :as gsh]
+ [app.common.types.text.cjk-layout :as cjk]
[app.config :as cf]
[app.main.ui.context :as muc]
[app.main.ui.shapes.attrs :as attrs]
[app.main.ui.shapes.custom-stroke :refer [shape-custom-strokes]]
[app.main.ui.shapes.fills :as fills]
[app.main.ui.shapes.gradients :as grad]
+ [app.main.ui.shapes.text.styles :as sts]
[app.util.object :as obj]
[rumext.v2 :as mf]))
(def fill-attrs [:fill-color :fill-color-gradient :fill-opacity])
+(defn- px
+ "CSS pixel size, or nil for a non-positive size."
+ [size]
+ (when (pos? size) (dm/str size "px")))
+
+(defn- with-font-features
+ [style data]
+ (let [font-features (sts/font-feature-settings (:font-features data))]
+ (cond-> style
+ (some? font-features) (obj/set! "fontFeatureSettings" font-features))))
+
+(defn- annotation-style
+ "Style of a ruby, warichu or emphasis line drawn at `font-size` along a
+ position-data strip."
+ [data font-size vertical? text-orientation fill]
+ (with-font-features
+ #js {:fontFamily (:font-family data)
+ :fontSize (px font-size)
+ :fontWeight (:font-weight data)
+ :fontStyle (:font-style data)
+ :direction (:direction data)
+ :writingMode (if vertical? "vertical-rl" "horizontal-tb")
+ :textSpacingTrim "normal"
+ :textOrientation text-orientation
+ :textAutospace "normal"
+ :whiteSpace "pre"
+ :fill fill}
+ data))
+
+(defn- strip-text-combine-upright
+ "CSS text-combine-upright of a strip. SVG applies it to whole `text`
+ elements only, so the renderer gives each combined digit run of a
+ `digits` span its own strip, which takes `all`."
+ [data]
+ (let [value (:text-combine-upright data)]
+ (if-let [segments (cjk/digit-combine-segments (str (:text data)) value)]
+ (when (and (= 1 (count segments)) (second (first segments)))
+ "all")
+ (sts/css-text-combine-upright value))))
+
+(defn- strip-text-props
+ "Props of the `text` element drawing a position-data strip's base text."
+ [shape data index fill browser-props]
+ (let [style (with-font-features
+ #js {:fontFamily (:font-family data)
+ :fontSize (:font-size data)
+ :fontWeight (:font-weight data)
+ :textTransform (:text-transform data)
+ :textDecoration (:text-decoration data)
+ :textCombineUpright (strip-text-combine-upright data)
+ :letterSpacing (:letter-spacing data)
+ :fontStyle (:font-style data)
+ :direction (:direction data)
+ :textSpacingTrim "normal"
+ :whiteSpace "pre"}
+ data)
+ key (dm/str "text-" (:id shape) "-" index)]
+ (if (= "vertical-rl" (:writing-mode data))
+ ;; Vertical strip: glyphs run down the column; x is the column's
+ ;; central axis and y the strip top (stored y is the strip bottom).
+ #js {:key key
+ :x (+ (:x data) (/ (:width data) 2))
+ :y (- (:y data) (:height data))
+ :textLength (:height data)
+ :lengthAdjust "spacingAndGlyphs"
+ :style (-> style
+ (obj/set! "writingMode" "vertical-rl")
+ (obj/set! "textOrientation" (or (:text-orientation data) "mixed"))
+ (obj/set! "textAutospace" "normal")
+ (obj/set! "fill" fill))}
+ (cond-> #js {:key key
+ :x (if (= "rtl" (:direction data)) (+ (:x data) (:width data)) (:x data))
+ :y (:y data)
+ :dominantBaseline "ideographic"
+ :textLength (:width data)
+ :lengthAdjust "spacingAndGlyphs"
+ :style (obj/set! style "fill" fill)}
+ (some? browser-props)
+ (obj/merge! browser-props)))))
+
+(defn- warichu-line-props
+ "Props of the `text` element drawing one warichu sub-line at half size in
+ its own strip: the renderer splits the span and places each sub-line."
+ [data fill]
+ (let [vertical? (= "vertical-rl" (:writing-mode data))
+ font-size (* (js/parseFloat (:font-size data)) cjk/warichu-font-scale)
+ font-size (if (js/isNaN font-size) 0 font-size)
+ style (annotation-style data font-size vertical? (when vertical? "upright") fill)
+ top (- (:y data) (:height data))]
+ (if vertical?
+ #js {:x (+ (:x data) (/ (:width data) 2))
+ :y top
+ :style style}
+ #js {:x (:x data)
+ :y top
+ :dominantBaseline "hanging"
+ :textLength (:width data)
+ :lengthAdjust "spacingAndGlyphs"
+ :style style})))
+
+(defn- ruby-text-props
+ "Props of the `text` element drawing a strip's ruby annotation beside it
+ (vertical) or above/below it (horizontal), per its side and alignment. A
+ Western reading is centred as one word, never stretched to the base."
+ [shape data index ruby-font-size style]
+ (let [key (dm/str "ruby-" (:id shape) "-" index)
+ ruby-side (:ruby-side data (cjk/enum-default :ruby-side))
+ word? (cjk/western-reading? (cjk/visible-ruby data))]
+ (if (= "vertical-rl" (:writing-mode data))
+ (let [x (if (= "under" ruby-side)
+ (- (:x data) (/ ruby-font-size 2))
+ (+ (:x data) (:width data) (/ ruby-font-size 2)))
+ top (- (:y data) (:height data))]
+ (if word?
+ #js {:key key
+ :x x
+ :y (+ top (/ (:height data) 2))
+ :textAnchor "middle"
+ :style style}
+ #js {:key key
+ :x x
+ :y top
+ :textLength (:height data)
+ :lengthAdjust "spacingAndGlyphs"
+ :style style}))
+ (let [rtl? (= "rtl" (:direction data))
+ ;; A reading over several strips spans its whole base.
+ data (assoc data
+ :x (:ruby-x data (:x data))
+ :width (:ruby-width data (:width data)))
+ ruby-align (if word? "center" (:ruby-align data (cjk/enum-default :ruby-align)))
+ fit? (and (not word?)
+ (or (= "none" (:ruby-overhang data (cjk/enum-default :ruby-overhang)))
+ (= "space-around" ruby-align)))]
+ (cond-> #js {:key key
+ :x (if (= "center" ruby-align)
+ (+ (:x data) (/ (:width data) 2))
+ (if rtl? (+ (:x data) (:width data)) (:x data)))
+ :y (if (= "under" ruby-side)
+ (:y data)
+ (- (:y data) (:height data)))
+ :dominantBaseline (if (= "under" ruby-side) "hanging" "text-after-edge")
+ :style style}
+ (= "center" ruby-align)
+ (obj/set! "textAnchor" "middle")
+
+ (= "start" ruby-align)
+ (obj/set! "textAnchor" (if rtl? "end" "start"))
+
+ fit?
+ (-> (obj/set! "textLength" (:width data))
+ (obj/set! "lengthAdjust" "spacingAndGlyphs"))
+
+ (= "space-between" ruby-align)
+ (-> (obj/set! "textLength" (:width data))
+ (obj/set! "lengthAdjust" "spacing")))))))
+
+(defn- emphasis-mark-props
+ "Props of the `text` element drawing one emphasis mark centred in its em
+ box, as placed by the renderer."
+ [data fill]
+ (let [size (:width data)]
+ #js {:x (+ (:x data) (/ size 2))
+ :y (- (:y data) (/ (:height data) 2))
+ :textAnchor "middle"
+ :dominantBaseline "central"
+ :style (annotation-style data size false nil fill)}))
+
(defn set-white-fill
[shape]
(let [update-color
@@ -71,33 +241,24 @@
[:> :g group-props
(for [[index data] (d/enumerate position-data)]
- (let [rtl? (= "rtl" (:direction data))
+ (let [vertical? (= "vertical-rl" (:writing-mode data))
+ ruby (cjk/visible-ruby data)
+ font-size (js/parseFloat (:font-size data))
+ ruby-font-size (if (js/isNaN font-size)
+ 0
+ (* font-size (cjk/ruby-font-scale (:ruby-size data))))
+ ;; Annotations take the fills of this strip's own render id.
+ annotation-fill (str "url(#fill-" index "-" render-id "-" index ")")
browser-props
- (cond
- (cf/check-browser? :safari)
+ (when (and (not vertical?) (cf/check-browser? :safari))
#js {:dominantBaseline "hanging"
:dy "0.2em"
:y (- (:y data) (:height data))})
- props (-> #js {:key (dm/str "text-" (:id shape) "-" index)
- :x (if rtl? (+ (:x data) (:width data)) (:x data))
- :y (:y data)
- :dominantBaseline "ideographic"
- :textLength (:width data)
- :lengthAdjust "spacingAndGlyphs"
- :style (-> #js {:fontFamily (:font-family data)
- :fontSize (:font-size data)
- :fontWeight (:font-weight data)
- :textTransform (:text-transform data)
- :textDecoration (:text-decoration data)
- :letterSpacing (:letter-spacing data)
- :fontStyle (:font-style data)
- :direction (:direction data)
- :whiteSpace "pre"}
- (obj/set! "fill" (str "url(#fill-" index "-" render-id ")")))}
- (cond-> browser-props
- (obj/merge! browser-props)))
+ text-props (strip-text-props shape data index
+ (str "url(#fill-" index "-" render-id ")")
+ browser-props)
shape (-> shape
(assoc :fills (:fills data))
;; The text elements have the shadow and blur already applied in the
@@ -112,5 +273,23 @@
[:defs
[:& fills/fills {:shape shape :render-id render-id}]]
- [:& shape-custom-strokes {:shape shape :position index :render-id render-id}
- [:> :text props (:text data)]]]))]]))
+ (cond
+ (:zhuyin-glyph data)
+ [:> :text #js {:x (:x data) :y (:y data)
+ :style (annotation-style data font-size false nil annotation-fill)} (:text data)]
+
+ (:emphasis-mark data)
+ ;; Emphasis marks (圏点) are not stroked.
+ [:> :text (emphasis-mark-props data annotation-fill) (:text data)]
+ :else
+ [:*
+ [:& shape-custom-strokes {:shape shape :position index :render-id render-id}
+ (if (= "warichu" (:warichu data))
+ [:> :text (warichu-line-props data annotation-fill) (:text data)]
+ [:> :text text-props (:text data)])]
+ (when (some? ruby)
+ [:> :text (ruby-text-props shape data index ruby-font-size
+ (annotation-style data ruby-font-size vertical?
+ (:text-orientation data "mixed")
+ annotation-fill))
+ ruby])])]))]]))
diff --git a/frontend/src/app/main/ui/workspace/shapes/text/viewport_texts_html.cljs b/frontend/src/app/main/ui/workspace/shapes/text/viewport_texts_html.cljs
index 3869f62a03..bd32ee5c17 100644
--- a/frontend/src/app/main/ui/workspace/shapes/text/viewport_texts_html.cljs
+++ b/frontend/src/app/main/ui/workspace/shapes/text/viewport_texts_html.cljs
@@ -29,6 +29,7 @@
[app.util.text-editor :as ted]
[app.util.text-svg-position :as tsp]
[app.util.text.content :as content]
+ [app.util.text.writing-mode :as wm]
[promesa.core :as p]
[rumext.v2 :as mf]))
@@ -98,11 +99,11 @@
(st/emit! (dwt/clean-text-modifier id))))
;; Always clear the task and log measurement errors.
- (p/catch (fn [cause]
- (log/error :hint "Could not measure text shape"
- :shape-id id
- :cause cause)
- nil))))
+ (p/merr (fn [cause]
+ (log/error :hint "Could not measure text shape"
+ :shape-id id
+ :cause cause)
+ (p/resolved nil)))))
(defn- update-text-modifier
[{:keys [grow-type id] :as shape} node]
@@ -167,6 +168,16 @@
pending-update* (mf/use-state {})
pending-update (deref pending-update*)
+ ;; Vertical texts already measured as horizontal (see `stale-layout?`).
+ remeasured-ref (mf/use-ref #{})
+
+ ;; A vertical text keeps the position data the WASM renderer computed
+ ;; for its columns; measure it once more as horizontal text.
+ stale-layout?
+ (fn [id]
+ (and (not (contains? (mf/ref-val remeasured-ref) id))
+ (wm/stale-vertical-layout? (:content (get text-shapes id)))))
+
text-change?
(fn [id]
(let [new-shape (get text-shapes id)
@@ -176,7 +187,8 @@
(or (and (not remote?) ;; changes caused by a remote peer are not re-calculated
(not (text-properties-equal? old-shape new-shape)))
;; When the position data is nil we force to recalculate
- (nil? (:position-data new-shape)))))
+ (nil? (:position-data new-shape))
+ (stale-layout? id))))
changed-texts
(mf/with-memo [text-shapes pending-update]
@@ -193,6 +205,7 @@
;; Unique to indentify the pending state
(let [uid (uuid/next)
id (:id shape)]
+ (mf/set-ref-val! remeasured-ref (conj (mf/ref-val remeasured-ref) id))
(swap! pending-update* assoc uid id)
;; Callback refs run at the DOM commit boundary. Track the exact
;; measurement promise from that acknowledgement; any resize it
diff --git a/frontend/src/app/render_wasm/api.cljs b/frontend/src/app/render_wasm/api.cljs
index 543a80b982..ab8d53f564 100644
--- a/frontend/src/app/render_wasm/api.cljs
+++ b/frontend/src/app/render_wasm/api.cljs
@@ -31,6 +31,7 @@
[app.common.types.path.impl :as path.impl]
[app.common.types.shape.layout :as ctl]
[app.common.types.text :as txt]
+ [app.common.types.text.cjk-layout :as cjk]
[app.common.uuid :as uuid]
[app.config :as cf]
[app.main.data.event :as-alias ev]
@@ -57,9 +58,11 @@
[app.util.dom :as dom]
[app.util.functions :as fns]
[app.util.globals :as ug]
- [app.util.i18n :refer [tr]]
+ [app.util.i18n :as i18n :refer [tr]]
[app.util.modules :as mod]
[app.util.text.content :as tc]
+ [app.util.text.geometry :as text.geom]
+ [app.util.text.writing-mode :as wm]
[app.util.timers :as timers]
[beicon.v2.core :as rx]
[cuerdas.core :as str]
@@ -111,7 +114,6 @@
;; the next `tiles-complete` arrives.
(defonce ^:private snapshot-capture-in-flight? (atom false))
-
(defn initialized?
"True when the WASM render context is safe for normal application calls.
False while missing/lost or while `reload-renderer!` is reconstructing it.
@@ -124,7 +126,6 @@
(declare sync-workspace-local-viewport!)
-
(defn set-transition-image-from-background!
"Sets `transition-image*` to a data URL representing a solid background color."
[background]
@@ -340,7 +341,7 @@
;; forward declare helpers so render can call them
(declare request-render)
-(declare set-shape-vertical-align fonts-from-text-content)
+(declare set-shape-vertical-align set-shape-line-adjustment fonts-from-text-content ensure-text-content)
(declare reload-renderer!)
(declare request-render-preserving-target)
(declare render-pending?)
@@ -417,26 +418,43 @@
;; See `request-render-preserving-target`.
(defonce ^:private preserve-target-render? (atom false))
+(defn- sync-text-editor-selection-rect!
+ "Store the box around the editor selection when it moved: the selection,
+ the text or its layout changed."
+ []
+ (let [shape-id (text-editor/text-editor-get-active-shape-id)
+ rect (text-editor/text-editor-get-selection-rect)]
+ (when (not= rect (dm/get-in @st/state [:workspace-wasm-editor-selection-rects shape-id]))
+ (st/emit! (texts/v3-update-text-editor-selection-rect shape-id rect)))))
+
(defn- drain-text-editor-events!
"Pop and handle every pending text-editor event.
- StylesChanged syncs the caret's current styles to the toolbar. Returns true
- when some event needs a full shape re-render (content or layout changed)."
+ StylesChanged syncs the caret's current styles to the toolbar, and any
+ event refreshes the box around the selection. Returns true when some event
+ needs a full shape re-render (content or layout changed)."
[]
- (loop [needs-render? false]
+ (loop [needs-render? false
+ drained? false]
(let [ev (text-editor/text-editor-poll-event)]
(if (or (nil? ev) (= ev TEXT_EDITOR_EVENT_NONE))
- needs-render?
+ (do
+ (when drained?
+ (sync-text-editor-selection-rect!))
+ needs-render?)
(do
(when (= ev TEXT_EDITOR_EVENT_STYLES_CHANGED)
- (let [current-styles (text-editor/text-editor-get-current-styles)
+ (let [current-styles (merge
+ (text-editor/text-editor-get-current-styles)
+ (text-editor/text-editor-get-current-cjk-styles))
shape-id (text-editor/text-editor-get-active-shape-id)]
;; Keep the caret color matching the text at the caret position.
(text-editor/text-editor-apply-caret-color (:fills current-styles))
(st/emit! (texts/v3-update-text-editor-styles shape-id current-styles))))
(recur (or needs-render?
(= ev TEXT_EDITOR_EVENT_CONTENT_CHANGED)
- (= ev TEXT_EDITOR_EVENT_NEEDS_LAYOUT))))))))
+ (= ev TEXT_EDITOR_EVENT_NEEDS_LAYOUT))
+ true))))))
;; This should never be called from the outside.
(defn- render
@@ -555,7 +573,6 @@
(when (initialized?)
(h/call wasm/internal-module "_render_preview")))
-
(defonce pending-render (atom false))
(defonce shapes-loading? (atom false))
(defonce deferred-render? (atom false))
@@ -744,12 +761,16 @@
(t/write-shape-text spans paragraph text)))))
(defn- text-content-fonts
- "Content fonts and fallback faces (emoji, Noto, ...) of a text content."
+ "Content fonts and fallback faces (emoji, Noto, ...) of the text content
+ WASM lays out (see `wm/active-content`)."
[content]
- {:fonts (f/get-content-fonts content)
- :fallback-fonts (fonts-from-text-content content false)})
+ (let [content (wm/active-content content)]
+ {:fonts (f/get-content-fonts content)
+ :fallback-fonts (fonts-from-text-content content false)}))
(defn- upload-text-content
+ "The editor caches the stored content; WASM lays out the active one, with
+ the CJK attrs of the text language only (see `wm/active-content`)."
[shape-id content {:keys [fonts fallback-fonts]}]
;; Cache content for text editor sync
@@ -762,13 +783,15 @@
(when (wasm/live?)
(h/call wasm/internal-module "_clear_shape_text")
- (set-shape-vertical-align (get content :vertical-align))
+ (let [content (wm/active-content content)]
+ (set-shape-vertical-align (get content :vertical-align))
+ (set-shape-line-adjustment (get content :line-adjustment))
- (let [result (f/store-fonts (concat fonts fallback-fonts))]
- (write-text-content! content)
- (f/load-fallback-fonts-for-editor! fallback-fonts)
- (h/call wasm/internal-module "_update_shape_text_layout")
- result)))
+ (let [result (f/store-fonts (concat fonts fallback-fonts))]
+ (write-text-content! content)
+ (f/load-fallback-fonts-for-editor! fallback-fonts)
+ (h/call wasm/internal-module "_update_shape_text_layout")
+ result))))
(defn set-shape-text-content
"This function sets shape text content and returns a stream that loads the needed fonts asynchronously"
@@ -1114,6 +1137,12 @@
[vertical-align]
(h/call wasm/internal-module "_set_shape_vertical_align" (sr/translate-vertical-align vertical-align)))
+(defn set-shape-line-adjustment
+ "How the text shape fits lines slightly too long (`cjk/enum-values`)."
+ [line-adjustment]
+ (h/call wasm/internal-module "_set_shape_line_adjustment"
+ (sr/translate-text-layout-enum :line-adjustment line-adjustment)))
+
(defn set-shape-opacity
[opacity]
(h/call wasm/internal-module "_set_shape_opacity" (or opacity 1)))
@@ -1374,6 +1403,20 @@
[shadows]
(props/set-shape-shadows shadows))
+(defn- fallback-font-set
+ "Emoji and Noto faces covering `emoji?` and the resolved scripts in `langs`."
+ [emoji? langs]
+ (-> #{}
+ (cond-> ^boolean emoji? (cfnt/add-emoji-font))
+ (cfnt/add-noto-fonts langs)))
+
+(defn- text-font-languages
+ "Scripts `text` needs, with Han resolved by the paragraph `language`
+ (nil when unset) and then the app locale."
+ [text language]
+ (-> (cfnt/collect-used-languages #{} text)
+ (cfnt/resolve-ambiguous-cjk language @i18n/locale)))
+
(defn fonts-from-text-content [content fallback-fonts-only?]
(let [paragraph-set (first (get content :children))
paragraphs (get paragraph-set :children)
@@ -1390,9 +1433,10 @@
emoji?
langs)
- (let [text (apply str (map :text spans))
- emoji? (if emoji? emoji? (cfnt/contains-emoji? text))
- langs (cfnt/collect-used-languages langs text)]
+ (let [text (apply str (map :text spans))
+ fallback-text (apply str (map #(str (:text %) (:ruby %)) spans))
+ emoji? (if emoji? emoji? (cfnt/contains-emoji? fallback-text))
+ langs (into langs (text-font-languages fallback-text (:text-language paragraph)))]
;; FIXME: this should probably be somewhere else
(when fallback-fonts-only? (t/write-shape-text spans paragraph text))
@@ -1401,14 +1445,54 @@
emoji?
langs))))
- (let [updated-fonts
- (-> #{}
- (cond-> ^boolean emoji? (cfnt/add-emoji-font))
- (cfnt/add-noto-fonts langs))
+ (let [updated-fonts (fallback-font-set emoji? langs)
fallback-fonts (filter #(get % :is-fallback) updated-fonts)]
(if fallback-fonts-only? updated-fonts fallback-fonts))))))
+;; Fallback faces a composition waits on, so preview updates do not queue more relayouts.
+(defonce ^:private composition-pending-faces (atom #{}))
+
+(defn- caret-paragraph-language
+ "Language of the paragraph holding the editor caret in `shape-id`, or nil."
+ [shape-id]
+ (when-let [{:keys [focus-para]} (text-editor/text-editor-get-selection)]
+ (dm/get-in (text-editor/get-cached-content shape-id)
+ [:children 0 :children focus-para :text-language])))
+
+(defn load-composition-fonts!
+ "Fetch the fallback faces (emoji, Noto, ...) that `text` needs and relayout
+ `shape-id` once they are stored. For text that lives only in WASM, such as
+ an IME composition preview; committed content loads its faces through
+ `set-shape-text-content`."
+ [shape-id text]
+ (let [emoji? (cfnt/contains-emoji? text)
+ langs (text-font-languages text (caret-paragraph-language shape-id))
+ waiting @composition-pending-faces
+ fonts (into []
+ (comp (filter :is-fallback)
+ (map (fn [font] [font (f/make-font-data font)]))
+ (remove (fn [[_ font-data]]
+ (or (f/font-ready? font-data)
+ (contains? waiting (f/font-data-key font-data))))))
+ (fallback-font-set emoji? langs))
+ faces (into #{} (map (comp f/font-data-key second)) fonts)]
+ (when (seq faces)
+ (swap! composition-pending-faces into faces)
+ (->> (rx/merge f/font-stored-stream f/font-storage-failed-stream)
+ (rx/filter faces)
+ (rx/scan disj faces)
+ (rx/filter empty?)
+ (rx/take 1)
+ (rx/subs! (fn [_]
+ (swap! composition-pending-faces #(reduce disj % faces))
+ (f/force-update-text-layout shape-id)
+ (request-render-preserving-target "composition-fonts"))))
+ (->> (rx/from (f/store-fonts (map first fonts)))
+ (rx/merge-map (fn [{:keys [callback]}]
+ (if (fn? callback) (callback) (rx/empty))))
+ (rx/subs! noop-fn noop-fn)))))
+
(defn set-shape-grow-type
[grow-type]
(when (initialized?)
@@ -1668,13 +1752,11 @@
(defn- text-selrect-stale?
"Check if the WASM-measured dimensions of an auto-grow text shape differ
from its stored selrect (same 0.1px tolerance as the classic renderer)."
- [{:keys [id selrect grow-type]}]
- (when-let [{:keys [width height]} (get-text-dimensions id)]
- (case grow-type
- :auto-width (or (not (mth/close? width (:width selrect) 0.1))
- (not (mth/close? height (:height selrect) 0.1)))
- :auto-height (not (mth/close? height (:height selrect) 0.1))
- false)))
+ [{:keys [id selrect grow-type content]}]
+ (when-let [dimension (get-text-dimensions id)]
+ (let [{:keys [width height]} (text.geom/resolve-size selrect grow-type content dimension)]
+ (or (not (mth/close? width (:width selrect) 0.1))
+ (not (mth/close? height (:height selrect) 0.1))))))
(defonce ^:private pending-stale-selrect-ids (atom #{}))
(defonce ^:private stale-selrect-sync-token (atom 0))
@@ -1923,7 +2005,6 @@
(request-render "images-loaded")))))))))))]
(process-next-chunk 0 [] [] empty-text-font-state))))))
-
;; This is a version of process-pending that doesn't have sideffects
;; with like request render or update layout.
(defn- process-pending-no-sideffects
@@ -2130,7 +2211,6 @@
heapu32 (mem/get-heap-u32)
heapf32 (mem/get-heap-f32)]
-
(reduce (fn [offset {:keys [type parent id index value]}]
(-> offset
(mem.h32/write-u32 heapu32 (sr/translate-structure-modifier-type type))
@@ -2374,7 +2454,9 @@
(text-editor-wasm?)
(bit-or 2r00000000000000000000000000000100)
(contains? cf/flags :render-wasm-info)
- (bit-or 2r00000000000000000000000000001000)))
+ (bit-or 2r00000000000000000000000000001000)
+ (dbg/enabled? :wasm-text-grid)
+ (bit-or 2r00000000000000000000000000010000)))
(defn set-render-options!
"Updates WASM render options with a new DPR value."
@@ -2872,6 +2954,164 @@
(def POSITION-DATA-U8-SIZE 36)
(def POSITION-DATA-U32-SIZE (/ POSITION-DATA-U8-SIZE 4))
+(def ^:private POSITION-DATA-VERTICAL 2)
+(def ^:private POSITION-DATA-RUBY 3)
+(def ^:private POSITION-DATA-EMPHASIS-MARK 4)
+(def ^:private POSITION-DATA-ZHUYIN 5)
+
+(defn- emphasis-mark-entry
+ "Position-data entry for one emphasis mark (圏点): the geometry is the
+ mark's em box, centred where the canvas paints it."
+ [element {:keys [x y width height]}]
+ (when-let [mark (cjk/emphasis-mark-char (get element :text-emphasis))]
+ (d/patch-object
+ (txt/get-default-text-attrs)
+ (d/without-nils
+ {:x x
+ :y (+ y height)
+ :width width
+ :height height
+ :direction "ltr"
+ :emphasis-mark true
+ :font-id (get element :font-id)
+ :font-family (get element :font-family)
+ :font-size (dm/str width "px")
+ :font-weight (get element :font-weight)
+ :font-style (get element :font-style)
+ :fills (get element :fills)
+ :text mark}))))
+
+(defn- ruby-strip-entry
+ "Position-data entry for a ruby annotation strip: the offsets index the
+ span's ruby string and the geometry is the exact gutter placement the
+ canvas paints."
+ [element {:keys [start-pos end-pos x y width height]}]
+ (when-let [ruby (cjk/visible-ruby element)]
+ (let [text (subs ruby
+ (min start-pos (count ruby))
+ (min end-pos (count ruby)))
+ font-size (js/parseFloat (get element :font-size))]
+ (when (seq text)
+ (d/patch-object
+ (txt/get-default-text-attrs)
+ (d/without-nils
+ {:x x
+ :y (+ y height)
+ :width width
+ :height height
+ :direction "ltr"
+ :writing-mode "vertical-rl"
+ :text-orientation "upright"
+ :font-id (get element :font-id)
+ :font-family (get element :font-family)
+ :font-size (when-not (js/isNaN font-size)
+ (dm/str (* (cjk/ruby-font-scale (:ruby-size element)) font-size) "px"))
+ :font-weight (get element :font-weight)
+ :font-style (get element :font-style)
+ :ruby-size (get element :ruby-size)
+ :ruby-align (get element :ruby-align)
+ :ruby-overhang (get element :ruby-overhang)
+ :ruby-side (get element :ruby-side)
+ :fills (get element :fills)
+ :text text}))))))
+
+(defn- zhuyin-glyph-entry
+ "One upright Zhuyin glyph at the renderer's drawing baseline."
+ [element {:keys [start-pos end-pos x y width height]}]
+ (when-let [reading (cjk/visible-ruby element)]
+ (d/patch-object
+ (txt/get-default-text-attrs)
+ (d/without-nils
+ {:x x :y (+ y height) :width width :height height
+ :direction "ltr" :zhuyin-glyph true
+ :font-id (:font-id element) :font-family (:font-family element)
+ :font-size (dm/str width "px") :font-weight (:font-weight element)
+ :font-style (:font-style element) :fills (:fills element)
+ :text (subs reading start-pos end-pos)}))))
+
+(defn- text-strip-entry
+ "Position-data entry for a strip of base text. Be aware that for RTL texts
+ `start-pos` can be greater than `end-pos`."
+ [paragraph element {:keys [start-pos end-pos direction x y width height]}]
+ (when-let [element-text (:text element)]
+ (let [vertical? (= direction POSITION-DATA-VERTICAL)
+ ruby (cjk/visible-ruby element)]
+ (d/patch-object
+ (txt/get-default-text-attrs)
+ (d/without-nils
+ {:x x
+ :y (+ y height)
+ :width width
+ :height height
+ :direction (dr/translate-direction direction)
+ ;; The SVG renderer draws vertical strips with CSS writing-mode.
+ :writing-mode (when vertical? "vertical-rl")
+ ;; Glyph orientation is stored on the span or its paragraph.
+ :text-orientation (when vertical?
+ (not-empty (or (get element :text-orientation)
+ (get paragraph :text-orientation))))
+ :font-id (get element :font-id)
+ :font-family (get element :font-family)
+ :font-size (dm/str (get element :font-size) "px")
+ :font-weight (get element :font-weight)
+ :text-transform (get element :text-transform)
+ :text-decoration (get element :text-decoration)
+ :text-combine-upright (get element :text-combine-upright)
+ :font-features (let [features (get element :font-features)]
+ (when (and (seq features) (not= "none" features))
+ features))
+ ;; Each warichu sub-line has its own entry, drawn at half size.
+ :warichu (when (= "warichu" (get element :warichu)) "warichu")
+ ;; Horizontal data has no ruby strip; the base entry carries ruby for SVG export.
+ :ruby (when (and (not vertical?) (seq element-text)
+ (not (and (true? (:ruby-zhuyin element))
+ (cjk/zhuyin-base? element-text)
+ (cjk/zhuyin-reading? ruby)))) ruby)
+ :ruby-size (get element :ruby-size)
+ :ruby-align (get element :ruby-align)
+ :ruby-overhang (get element :ruby-overhang)
+ :ruby-side (get element :ruby-side)
+ :letter-spacing (dm/str (get element :letter-spacing) "px")
+ :font-style (get element :font-style)
+ :fills (get element :fills)
+ :text (subs element-text start-pos end-pos)})))))
+
+(defn- ruby-base-starts
+ "First span of the reading of each span of `paragraph` that has one
+ (`cjk/ruby-groups`), by span index."
+ [paragraph]
+ (into {}
+ (mapcat (fn [[start end]] (map (fn [span] [span start]) (range start end))))
+ (cjk/ruby-groups (:children paragraph))))
+
+(defn- join-ruby-strips
+ "A horizontal reading draws once per line of its base. When its base has
+ several strips on a line (spans of other styles, fallback fonts), the
+ first keeps the reading, spread over all of them (`:ruby-x`,
+ `:ruby-width`), and the others drop it. `::ruby-base` keys each strip
+ with a reading by its paragraph and base."
+ [entries]
+ (let [line-of (fn [entry] [(::ruby-base entry) (:y entry)])
+ lines (->> entries
+ (filter #(and (some? (::ruby-base %)) (some? (:ruby %))))
+ (group-by line-of))]
+ (mapv (fn [entry]
+ (let [strips (get lines (line-of entry))
+ first? (identical? entry (first strips))
+ entry (dissoc entry ::ruby-base)]
+ (cond
+ (< (count strips) 2)
+ entry
+
+ first?
+ (let [left (apply min (map :x strips))
+ right (apply max (map #(+ (:x %) (:width %)) strips))]
+ (assoc entry :ruby-x left :ruby-width (- right left)))
+
+ :else
+ (dissoc entry :ruby))))
+ entries)))
+
(defn calculate-position-data
[shape]
(when (initialized?)
@@ -2897,38 +3137,24 @@
(mem/free)
- (into []
- (keep
- (fn [{:keys [paragraph span start-pos end-pos direction x y width height]}]
- (let [element (-> content :children
- (get 0) :children ;; paragraph-set
- (get paragraph) :children ;; paragraph
- (get span))
- element-text (:text element)]
-
- ;; Add comprehensive nil-safety checks
- ;; Be aware that for RTL texts `start-pos` can be greatert han `end-pos`
- (when (and element element-text)
- (let [text (subs element-text start-pos end-pos)]
- (d/patch-object
- (txt/get-default-text-attrs)
- (d/without-nils
- {:x x
- :y (+ y height)
- :width width
- :height height
- :direction (dr/translate-direction direction)
- :font-id (get element :font-id)
- :font-family (get element :font-family)
- :font-size (dm/str (get element :font-size) "px")
- :font-weight (get element :font-weight)
- :text-transform (get element :text-transform)
- :text-decoration (get element :text-decoration)
- :letter-spacing (dm/str (get element :letter-spacing) "px")
- :font-style (get element :font-style)
- :fills (get element :fills)
- :text text})))))))
- result))))
+ (let [base-starts (memoize ruby-base-starts)]
+ (->> result
+ (into []
+ (keep
+ (fn [{:keys [paragraph span direction] :as entry}]
+ (let [paragraph-node (-> content :children
+ (get 0) :children ;; paragraph-set
+ (get paragraph))
+ element (-> paragraph-node :children (get span))]
+ (condp = direction
+ POSITION-DATA-RUBY (ruby-strip-entry element entry)
+ POSITION-DATA-ZHUYIN (zhuyin-glyph-entry element entry)
+ POSITION-DATA-EMPHASIS-MARK (emphasis-mark-entry element entry)
+ (some-> (text-strip-entry paragraph-node element entry)
+ (assoc ::ruby-base
+ (when-let [start (get (base-starts paragraph-node) span)]
+ [paragraph start]))))))))
+ (join-ruby-strips))))))
(defn apply-canvas-blur
[]
@@ -3174,5 +3400,3 @@
viewport mount. Idempotent: the `delay` caches its in-flight promise."
[]
@module)
-
-
diff --git a/frontend/src/app/render_wasm/api/fonts.cljs b/frontend/src/app/render_wasm/api/fonts.cljs
index 0b438c5e20..0d528c0f8e 100644
--- a/frontend/src/app/render_wasm/api/fonts.cljs
+++ b/frontend/src/app/render_wasm/api/fonts.cljs
@@ -282,6 +282,17 @@
(or (contains? @failed-font-data-keys (font-data-key font-data))
(font-stored? font-data (:emoji? font-data))))
+(defn- mark-font-as-fallback!
+ [font-data]
+ (let [id-buffer (uuid/get-u32 (:wasm-id font-data))]
+ (h/call wasm/internal-module "_mark_font_as_fallback"
+ (aget id-buffer 0)
+ (aget id-buffer 1)
+ (aget id-buffer 2)
+ (aget id-buffer 3)
+ (:weight font-data)
+ (:style font-data))))
+
(defn- store-font-id
[font-data asset-id emoji? fallback?]
(if asset-id
@@ -299,6 +310,8 @@
(do
(store-font-url font-data uri)
(clear-font-storage-failure! font-data)
+ (when fallback?
+ (mark-font-as-fallback! font-data))
(tm/schedule #(rx/push! font-stored-stream (font-data-key font-data))))
(fetch-font font-data uri emoji? fallback?)))
;; Report missing font assets asynchronously.
diff --git a/frontend/src/app/util/code_gen/style_css.cljs b/frontend/src/app/util/code_gen/style_css.cljs
index fa04b1e89c..8b7166e1b3 100644
--- a/frontend/src/app/util/code_gen/style_css.cljs
+++ b/frontend/src/app/util/code_gen/style_css.cljs
@@ -16,6 +16,7 @@
[app.common.types.color :as cc]
[app.common.types.shape.layout :as ctl]
[app.common.types.text :as types.text]
+ [app.common.types.text.cjk-layout :as cjk]
[app.main.ui.shapes.text.styles :as sts]
[app.util.code-gen.common :as cgc]
[app.util.code-gen.style-css-formats :refer [format-value format-shadow->css]]
@@ -223,13 +224,19 @@ body {
(shape->css-properties objects properties options)
(format-css-properties options))))
+;; Custom properties generated code keeps; the others carry renderer state.
+(def ^:private code-custom-properties
+ #{"--paragraph-line-height"})
+
(defn format-js-styles
[properties _options]
(format-css-properties
(->> (.keys js/Object properties)
- (remove #(str/starts-with? % "--"))
+ (filter #(or (not (str/starts-with? % "--"))
+ (contains? code-custom-properties %)))
(mapv (fn [key]
- [(str/kebab key) (unchecked-get properties key)])))
+ [(if (str/starts-with? key "--") key (str/kebab key))
+ (unchecked-get properties key)])))
nil))
(defn- list-paragraph?
@@ -283,22 +290,60 @@ body {
(some? color) (obj/set! "color" color))
nil))))
+(defn- ruby-css
+ "Rules for the ruby wrapper and annotation of a text node with a visible
+ reading, or nil."
+ [shape shape-selector node]
+ (when (and (types.text/is-text-node? node) (cjk/visible-ruby node))
+ (dm/fmt
+ ".% {\n%\n}\n.% {\n%\n}"
+ (dm/str shape-selector " ." (:$id node) "-ruby")
+ (format-js-styles (sts/generate-ruby-container-styles node) nil)
+ (dm/str shape-selector " ." (:$id node) "-rt")
+ (format-js-styles (sts/generate-ruby-styles shape node) nil))))
+
+(defn- tcy-css
+ "Rule for the combined digit runs of `digits` tate-chu-yoko spans, or nil."
+ [shape shape-selector]
+ (when (some #(cjk/digit-combine? (:text-combine-upright %))
+ (types.text/node-seq types.text/is-text-node? (:content shape)))
+ (dm/fmt ".% .tcy {\n%\n}" shape-selector (format-js-styles sts/tcy-run-style nil))))
+
+(defn- joined-ruby-ids
+ "Ids of the text nodes that continue the reading of an earlier node
+ (`cjk/ruby-groups`): the markup draws one reading per base, under the
+ wrapper of its first node."
+ [content]
+ (into #{}
+ (comp (filter types.text/is-paragraph-node?)
+ (mapcat (fn [paragraph]
+ (let [nodes (vec (:children paragraph))]
+ (for [[start end] (cjk/ruby-groups nodes)
+ index (range (inc start) end)]
+ (:$id (nth nodes index)))))))
+ (types.text/node-seq content)))
+
(defn generate-text-css
[shape]
(let [selector (cgc/shape->selector shape)
- nodes (->> shape
- :content
- (legacy.txt/index-content)
- (types.text/node-seq))
+ content (legacy.txt/index-content (:content shape))
+ joined (joined-ruby-ids content)
+ nodes (types.text/node-seq content)
node-rules (mapcat (fn [node]
- (cond-> [(node->css shape selector node)]
+ (cond-> [(node->css shape selector node)
+ (when-not (contains? joined (:$id node))
+ (ruby-css shape selector node))]
(list-paragraph? node)
(conj (list-marker-css shape selector node))))
nodes)
list-rules (when (some list-paragraph? nodes)
- [(dm/fmt ".% ul {\n%\n}" selector
+ [(dm/fmt ".% ul {
+%
+}" selector
(format-js-styles #js {:margin 0 :padding 0} nil))])]
- (str/join "\n" (concat node-rules list-rules))))
+ (->> (concat [(tcy-css shape selector)] node-rules list-rules)
+ (remove nil?)
+ (str/join "\n"))))
(defn get-shape-css-selector
([objects shape]
diff --git a/frontend/src/app/util/text/clipboard.cljs b/frontend/src/app/util/text/clipboard.cljs
index f8368aa34a..98de96504f 100644
--- a/frontend/src/app/util/text/clipboard.cljs
+++ b/frontend/src/app/util/text/clipboard.cljs
@@ -25,13 +25,14 @@
"SUMMARY" "TABLE" "TBODY" "TFOOT" "THEAD" "TR" "UL"})
;; Elements whose text is read; any other element is skipped with its children.
-;; `O:P` is Word's paragraph filler, which marks its empty lines.
+;; `O:P` is Word's paragraph filler, which marks its empty lines. Ruby keeps its
+;; base text (`RUBY`, `RB`); the reading (`RT`, `RTC`) and fallback `RP` are skipped.
(def ^:private allowed-tags
(into block-tags
#{"A" "ABBR" "B" "BDI" "BDO" "BIG" "BR" "CENTER" "CITE" "CODE" "DATA"
- "DEL" "DFN" "EM" "FONT" "I" "INS" "KBD" "LABEL" "MARK" "O:P" "Q" "S"
- "SAMP" "SMALL" "SPAN" "STRIKE" "STRONG" "SUB" "SUP" "TD" "TH" "TIME"
- "TT" "U" "VAR" "WBR"}))
+ "DEL" "DFN" "EM" "FONT" "I" "INS" "KBD" "LABEL" "MARK" "O:P" "Q" "RB"
+ "RUBY" "S" "SAMP" "SMALL" "SPAN" "STRIKE" "STRONG" "SUB" "SUP" "TD"
+ "TH" "TIME" "TT" "U" "VAR" "WBR"}))
(def ^:private bold-tags #{"B" "STRONG" "TH" "H1" "H2" "H3" "H4" "H5" "H6"})
(def ^:private italic-tags #{"I" "EM" "CITE" "VAR" "DFN"})
diff --git a/frontend/src/app/util/text/content.cljs b/frontend/src/app/util/text/content.cljs
index 5e6212d3cf..d927639ca8 100644
--- a/frontend/src/app/util/text/content.cljs
+++ b/frontend/src/app/util/text/content.cljs
@@ -24,11 +24,15 @@
(defn v2-default-text-content
"Build the base text tree (root -> paragraph-set -> paragraph -> span) with the
- current default typography. Used by the V2 editor/WASM path when a shape is
- created with no content yet."
+ current default typography and the language new texts take: the one used
+ last in this session, else the file language. Used by the V2 editor/WASM
+ path when a shape is created with no content yet."
[]
(let [default-font (deref refs/default-font)
- text-defaults (merge (txt/get-default-text-attrs) default-font)
+ language (or (deref refs/default-text-language)
+ (deref refs/file-text-language))
+ text-defaults (cond-> (merge (txt/get-default-text-attrs) default-font)
+ (some? language) (assoc :text-language language))
default-span (merge {:text ""}
(select-keys text-defaults txt/text-node-attrs))
default-paragraph (merge {:type "paragraph"
diff --git a/frontend/src/app/util/text/content/styles.cljs b/frontend/src/app/util/text/content/styles.cljs
index e4c50ae22a..2c8d58792c 100644
--- a/frontend/src/app/util/text/content/styles.cljs
+++ b/frontend/src/app/util/text/content/styles.cljs
@@ -22,11 +22,15 @@
(def mapping
{:fills [encode decode]
+ :ruby-zhuyin [encode decode]
:typography-ref-id [encode decode]
:typography-ref-file [encode decode]
:font-id [identity identity]
:font-variant-id [identity identity]
- :vertical-align [identity identity]})
+ :vertical-align [identity identity]
+ ;; Keep canonical enum values intact in the DOM editor's style data.
+ :text-emphasis-position [identity identity]
+ :text-underline-position [identity identity]})
(defn normalize-style-value
"This function adds units to style values"
diff --git a/frontend/src/app/util/text/geometry.cljs b/frontend/src/app/util/text/geometry.cljs
new file mode 100644
index 0000000000..c25829b7c0
--- /dev/null
+++ b/frontend/src/app/util/text/geometry.cljs
@@ -0,0 +1,56 @@
+;; This Source Code Form is subject to the terms of the Mozilla Public
+;; License, v. 2.0. If a copy of the MPL was not distributed with this
+;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
+;;
+;; Copyright (c) KALEIDOS SUBSIDIARY SL
+
+(ns app.util.text.geometry
+ (:require
+ [app.common.geom.point :as gpt]
+ [app.util.text.writing-mode :as wm]))
+
+(defn- live-axis
+ "Measured axis, or the committed one when the measure is missing or not
+ positive, so a failed WASM measure never shows as `0`."
+ [measured committed]
+ (if (and (number? measured) (pos? measured)) measured committed))
+
+(defn resolve-size
+ "Auto-height grows along the block axis: height horizontally, width vertically."
+ [selrect grow-type content dimension]
+ (when (or (= :fixed grow-type) (some? dimension))
+ (let [vertical? (wm/vertical-text-content? content)]
+ {:width (if (or (= :fixed grow-type)
+ (and (= :auto-height grow-type) (not vertical?)))
+ (:width selrect)
+ (live-axis (:width dimension) (:width selrect)))
+ :height (if (or (= :fixed grow-type)
+ (and (= :auto-height grow-type) vertical?))
+ (:height selrect)
+ (live-axis (:height dimension) (:height selrect)))})))
+
+(defn- block-anchor
+ [content]
+ (if (wm/vertical-text-content? content)
+ (case (:vertical-align content) "center" 0.5 "bottom" 0 1)
+ (case (:vertical-align content) "center" 0.5 "bottom" 1 0)))
+
+(defn resize-origin
+ "Keep the text's block alignment anchored when its measured size changes."
+ [{:keys [points content]}]
+ (gpt/lerp (nth points 0)
+ (nth points (if (wm/vertical-text-content? content) 1 3))
+ (block-anchor content)))
+
+(defn live-rect
+ "Bounds of live editor content, before its geometry is committed."
+ [selrect grow-type content dimension]
+ (if-let [{:keys [width height]} (resolve-size selrect grow-type content dimension)]
+ (let [vertical? (wm/vertical-text-content? content)
+ anchor (block-anchor content)]
+ (assoc selrect
+ :x (+ (:x selrect) (if vertical? (* anchor (- (:width selrect) width)) 0))
+ :y (+ (:y selrect) (if vertical? 0 (* anchor (- (:height selrect) height))))
+ :width width
+ :height height))
+ selrect))
diff --git a/frontend/src/app/util/text/layout.cljs b/frontend/src/app/util/text/layout.cljs
new file mode 100644
index 0000000000..d7028e6591
--- /dev/null
+++ b/frontend/src/app/util/text/layout.cljs
@@ -0,0 +1,72 @@
+;; This Source Code Form is subject to the terms of the Mozilla Public
+;; License, v. 2.0. If a copy of the MPL was not distributed with this
+;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
+;;
+;; Copyright (c) KALEIDOS SUBSIDIARY SL
+
+(ns app.util.text.layout
+ "Language of text shapes, as the CJK text options read it. A text has one
+ language: every paragraph carries the same `:text-language` tag."
+ (:require
+ [app.common.types.text :as txt]
+ [app.util.i18n :refer [tr]]))
+
+(defn- get-paragraph-languages
+ "Language of each paragraph of `content`, nil for the ones without; a
+ content without paragraphs reads as one such paragraph."
+ [content]
+ (let [paragraphs (txt/node-seq txt/is-paragraph-node? content)]
+ (if (seq paragraphs)
+ (map :text-language paragraphs)
+ [nil])))
+
+(defn get-texts-language
+ "Language of the text `contents`: the tag all their paragraphs share, nil
+ when none has a language, `:multiple` when they differ. A paragraph
+ without language differs from one with a language."
+ [contents]
+ (let [languages (into #{} (mapcat get-paragraph-languages) contents)]
+ (if (> (count languages) 1)
+ :multiple
+ (first languages))))
+
+(def ^:private language-groups
+ "Languages a text can take, in the order the profile lists show them:
+ each group lists its language tags."
+ [{:id "japanese" :languages ["ja"]}
+ {:id "chinese" :languages ["zh-Hans-CN" "zh-Hant-CN" "zh-Hant-HK" "zh-Hant-TW"]}
+ {:id "korean" :languages ["ko"]}])
+
+(defn- get-group-label
+ [id]
+ (case id
+ "japanese" (tr "workspace.options.text-options.language-group-japanese")
+ "chinese" (tr "workspace.options.text-options.language-group-chinese")
+ "korean" (tr "workspace.options.text-options.language-group-korean")))
+
+(defn language-label
+ "Name of the language `tag`: \"Mixed\" for `:multiple`, the tag itself
+ when it is not one of the listed languages."
+ [tag]
+ (case tag
+ :multiple (tr "settings.multiple")
+ "ja" (tr "workspace.options.text-options.language-japanese")
+ "zh-Hans-CN" (tr "workspace.options.text-options.language-chinese-mainland-simplified")
+ "zh-Hant-CN" (tr "workspace.options.text-options.language-chinese-mainland-traditional")
+ "zh-Hant-HK" (tr "workspace.options.text-options.language-chinese-hong-kong")
+ "zh-Hant-TW" (tr "workspace.options.text-options.language-chinese-taiwan")
+ "ko" (tr "workspace.options.text-options.language-korean")
+ tag))
+
+(defn language-options
+ "Rows of the profile lists: one group per language, a header row
+ `{:id :label :header true}` and then its languages, the `selected` tag
+ checked."
+ [selected]
+ (into []
+ (mapcat (fn [{:keys [id languages]}]
+ (into [{:id id :header true :label (get-group-label id)}]
+ (map (fn [tag]
+ {:id tag :label (language-label tag) :selected (= selected tag)}))
+ languages)))
+ language-groups))
diff --git a/frontend/src/app/util/text/writing_mode.cljs b/frontend/src/app/util/text/writing_mode.cljs
new file mode 100644
index 0000000000..962e0ff431
--- /dev/null
+++ b/frontend/src/app/util/text/writing_mode.cljs
@@ -0,0 +1,72 @@
+;; This Source Code Form is subject to the terms of the Mozilla Public
+;; License, v. 2.0. If a copy of the MPL was not distributed with this
+;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
+;;
+;; Copyright (c) KALEIDOS SUBSIDIARY SL
+
+(ns app.util.text.writing-mode
+ "Text content as the active renderer lays it out. The CJK attrs only apply
+ under the language of the text that uses them (see `cjk/active-content`).
+ Only the WASM renderer supports vertical writing; the SVG renderer lays
+ every text out horizontally and leaves the stored attrs as they are."
+ (:require
+ [app.common.types.shape :as cts]
+ [app.common.types.text :as txt]
+ [app.common.types.text.cjk-layout :as cjk]))
+
+(defn vertical-layout-active?
+ "True when the active renderer lays out vertical writing (WASM)."
+ []
+ cts/wasm-enabled?)
+
+(defn active-content
+ "Text content with the CJK attrs its language uses (see
+ `cjk/active-content`)."
+ [content]
+ (cjk/active-content content))
+
+(defn content-writing-mode
+ "Writing mode the active renderer lays the text content out with."
+ [content]
+ (when ^boolean (vertical-layout-active?)
+ (cjk/active-writing-mode content)))
+
+(defn vertical-text-content?
+ "True when the text content flows vertically under the active renderer."
+ [content]
+ (= "vertical-rl" (content-writing-mode content)))
+
+(defn vertical-values?
+ "True when the text option `values` describe vertical text: vertical
+ writing under a CJK language. Mixed languages count as CJK."
+ [values]
+ (let [language (:text-language values)]
+ (and ^boolean (vertical-layout-active?)
+ (= "vertical-rl" (:writing-mode values))
+ (or (= :multiple language)
+ (some? (cjk/language-family language))))))
+
+(defn stale-vertical-layout?
+ "True when the content is stored as vertical but the active renderer lays
+ it out horizontally, so a WASM-computed layout (such as `:position-data`)
+ does not match."
+ [content]
+ (and (not ^boolean (vertical-layout-active?))
+ (cjk/stored-vertical? content)))
+
+(defn renderable-paragraph
+ "Paragraph attrs as the active renderer lays them out: without the vertical
+ writing attrs when the renderer lays every text out horizontally."
+ [paragraph]
+ (if ^boolean (vertical-layout-active?)
+ paragraph
+ (apply dissoc paragraph cjk/vertical-writing-attrs)))
+
+(defn renderable-content
+ "Text content as the active renderer lays it out (see `active-content` and
+ `renderable-paragraph`)."
+ [content]
+ (let [content (active-content content)]
+ (if ^boolean (vertical-layout-active?)
+ content
+ (txt/transform-nodes txt/is-paragraph-node? renderable-paragraph content))))
diff --git a/frontend/test/frontend_tests/code_gen_style_test.cljs b/frontend/test/frontend_tests/code_gen_style_test.cljs
index 937df0b8ca..e6bc7cb25a 100644
--- a/frontend/test/frontend_tests/code_gen_style_test.cljs
+++ b/frontend/test/frontend_tests/code_gen_style_test.cljs
@@ -15,6 +15,7 @@
[app.common.geom.point :as gpt]
[app.common.geom.rect :as grc]
[app.common.uuid :as uuid]
+ [app.main.ui.shapes.text.fo-text :as fo-text]
[app.main.ui.shapes.text.html-text :as html-text]
[app.util.code-gen.markup-html :as html]
[app.util.code-gen.style-css :as css]
@@ -183,6 +184,29 @@
:children [{:text "Hello"
:fills [{:fill-color "#000000" :fill-opacity 1}]}]}]}]})
+(def ^:private ruby-text-content
+ {:type "root"
+ :children [{:type "paragraph-set"
+ :children [{:type "paragraph" :text-language "ja"
+ :writing-mode "vertical-rl"
+ :text-orientation "upright"
+ :children [{:text "漢字"
+ :ruby "かんじ"
+ :font-size "20"
+ :fill-color "#000000"
+ :fill-opacity 1}]}]}]})
+
+(defn- text-shape
+ [content]
+ (let [tid (uuid/next)]
+ {:id tid :name "Text" :type :text
+ :parent-id uuid/zero :frame-id uuid/zero
+ :x 0 :y 0 :width 100 :height 40
+ :selrect (grc/make-rect 0 0 100 40)
+ :points (pts 0 0 100 40)
+ :grow-type :fixed
+ :content content}))
+
(deftest text-markup-emits-node-id-classes
(testing "generated text markup carries the $id classes the CSS rules target"
(let [tid (uuid/next)
@@ -304,3 +328,199 @@
markup (html/generate-markup (objects text) [text])]
(is (str/includes? markup "
- `, so each digit run gets its own `all` span"
+ (let [text (text-shape tcy-digits2-text-content)
+ markup (rds/renderToStaticMarkup
+ (mf/element fo-text/text-shape* #js {:shape text :grow-type :fixed}))]
+ (is (re-find #"]*style=\"text-combine-upright:all\">31" markup))
+ (is (not (str/includes? markup "digits"))))))
+
+(deftest generated-code-combines-each-digit-run
+ (testing "generated markup marks digit runs and the CSS combines them"
+ (let [text (text-shape tcy-digits2-text-content)
+ markup (html/generate-markup (objects text) [text])
+ css (css/generate-text-css text)]
+ (is (re-find #"31" markup))
+ (is (re-find #"\.tcy \{\s*text-combine-upright: all" css))
+ (is (not (str/includes? css "digits"))))))
+
+(deftest generated-css-keeps-the-writing-mode
+ (testing "code keeps vertical writing whatever renderer is active"
+ (let [css (css/generate-text-css (text-shape ruby-text-content))]
+ (is (str/includes? css "writing-mode: vertical-rl"))
+ (is (str/includes? css "text-orientation: upright")))))
+
+(deftest ruby-text-drops-base-only-styles
+ (testing "the reading does not inherit emphasis marks or font features"
+ (let [content (update-in ruby-text-content [:children 0 :children 0 :children 0]
+ assoc :text-emphasis "filled-dot" :font-features "palt")
+ markup (rds/renderToStaticMarkup
+ (mf/element fo-text/text-shape* #js {:shape (text-shape content) :grow-type :fixed}))
+ rt (re-find #"