powertom 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,204 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "date"
4
+ require "set"
5
+ require_relative "path_resolver"
6
+ require_relative "formatter"
7
+
8
+ module PowerTom
9
+ # 路径取值与标签渲染(§2.2 数据模型约定)。纯 Ruby,不碰 XML。
10
+ # 取值语义统一走 PathResolver(与 Validator 对账共享)。
11
+ #
12
+ # - String / 数字 / Symbol / Date / Time 用 to_s
13
+ # - nil → 空字符串
14
+ # - Hash / Array 渲染为文本 = 错误(路径镜像了数据结构,取值应取到标量)
15
+ class Binder
16
+ attr_reader :used_root_keys
17
+
18
+ def initialize(data, strict:, warnings:)
19
+ @data = data
20
+ @strict = strict
21
+ @warnings = warnings
22
+ @used_root_keys = Set.new
23
+ end
24
+
25
+ # 渲染一个标签路径。缺失字段:strict 抛 MissingDataError;否则填空并记 warning(§2.3)
26
+ #
27
+ # context 可携带作用域(§3.3 #each 页内标签取每次迭代的作用域):
28
+ # scope: 本次迭代的数据项(Hash);nil → 用根数据
29
+ # scope_root: #each 的根路径字段名,用于未使用字段统计
30
+ # spec:formatter 规格(§3.4),如 "currency" / "percent.1";nil → 不格式化
31
+ def render_label(path, context, spec: nil)
32
+ record_root(path, context)
33
+ value = resolve_label(path, context)
34
+ # §2.2:nil 渲染为空字符串,formatter 不参与(避免 currency 之类的报错)
35
+ return "" if value.nil?
36
+ return Formatter.apply(value, spec) if spec
37
+ to_text(value, path)
38
+ rescue MissingDataError => e
39
+ raise if @strict
40
+ @warnings << "#{e.message},已填空字符串"
41
+ ""
42
+ end
43
+
44
+ # 取原始值(不转文本),供 #each(要数组)/ #if(要真假)/ 图片字段(要路径)使用。
45
+ # 遵循 strict 配置:strict 且缺失 → MissingDataError;非 strict → nil + warning。
46
+ # 作用域语义与 render_label 一致(#each 页取迭代项);purpose 仅用于 warning 语境
47
+ def value_at(path, context, purpose: "页级指令")
48
+ record_root(path, context)
49
+ begin
50
+ PathResolver.resolve(context[:scope] || @data, path)
51
+ rescue MissingDataError => e
52
+ raise MissingDataError, "第 #{context[:slide_no]} 页:{{#{path}}} #{e.message}"
53
+ end
54
+ rescue MissingDataError => e
55
+ raise if @strict
56
+ @warnings << "#{e.message}(#{purpose})"
57
+ nil
58
+ end
59
+
60
+ private
61
+
62
+ def record_root(path, context)
63
+ return if (context[:grid_scope] || context[:row_item]) && grid_variable?(path)
64
+
65
+ if context[:scope]
66
+ @used_root_keys << context[:scope_root].to_s if context[:scope_root]
67
+ else
68
+ root_key = path.split(".").first[/\A[A-Za-z0-9_]+/]
69
+ @used_root_keys << root_key if root_key
70
+ end
71
+ end
72
+
73
+ # #grid 作用域变量:row.* / col.* / cell(不是顶层数据字段)
74
+ def grid_variable?(path)
75
+ path == "cell" || path == "row" || path.start_with?("row.") ||
76
+ path == "col" || path.start_with?("col.")
77
+ end
78
+
79
+ def resolve(path, context)
80
+ begin
81
+ PathResolver.resolve(context[:scope] || @data, path)
82
+ rescue MissingDataError => e
83
+ raise MissingDataError, "#{describe(context)}:{{#{path}}} #{e.message}"
84
+ end
85
+ end
86
+
87
+ # 表格行标签:{{数组[].字段}} / {{父数组[].子数组[].字段}} 相对当前行作用域取值。
88
+ # row_scopes: {"groups[]" => 父项, "groups[].items[]" => 子项}(当前行已展开的层级)
89
+ # #grid 作用域另见 resolve_grid_label({{row.x}} / {{col.y}} / {{cell}})。
90
+ def resolve_label(path, context)
91
+ return resolve_grid_label(path, context) if context[:grid_scope]
92
+ if context[:row_item] && (path == "row" || path.start_with?("row."))
93
+ return resolve_row_item_label(path, context)
94
+ end
95
+ return resolve(path, context) unless path.include?("[]")
96
+
97
+ resolve_row_label(path, context)
98
+ end
99
+
100
+ # 行区块里的 {{row.*}}:指向当前记录的字段
101
+ def resolve_row_item_label(path, context)
102
+ item = context[:row_item]
103
+ return item if path == "row"
104
+
105
+ resolve_grid_item(item, path.delete_prefix("row."), path, context)
106
+ end
107
+
108
+ # #grid 单元格作用域:col(Hash/标量)、row(行数据)、cell(行列交叉值)
109
+ def resolve_grid_label(path, context)
110
+ scope = context[:grid_scope]
111
+ return fetch_cell(scope, context) if path == "cell"
112
+
113
+ if path == "row" || path.start_with?("row.")
114
+ item = require_grid_scope!(scope, :row, path)
115
+ return item if path == "row"
116
+
117
+ return resolve_grid_item(item, path.delete_prefix("row."), path, context)
118
+ end
119
+ if path == "col" || path.start_with?("col.")
120
+ item = require_grid_scope!(scope, :col, path)
121
+ return item if path == "col"
122
+
123
+ return resolve_grid_item(item, path.delete_prefix("col."), path, context)
124
+ end
125
+
126
+ resolve(path, context) # 其他标签仍从整页数据取(如静态合计)
127
+ end
128
+
129
+ def fetch_cell(scope, context)
130
+ resolver = scope[:cell]
131
+ unless resolver
132
+ raise PowerTom::Error,
133
+ "{{cell}} 只能在 grid 内容行的数据列里使用" \
134
+ "(需要同时有行数据与列数据)"
135
+ end
136
+ begin
137
+ resolver.call
138
+ rescue MissingDataError => e
139
+ raise MissingDataError, "#{describe(context)}:{{cell}} #{e.message}"
140
+ end
141
+ end
142
+
143
+ def require_grid_scope!(scope, key, path)
144
+ value = scope[key]
145
+ return value unless value.nil?
146
+
147
+ where = key == :row ? "grid 内容行" : "grid 数据列(首列之外)"
148
+ raise PowerTom::Error, "{{#{path}}} 只能在 #{where} 里使用"
149
+ end
150
+
151
+ def resolve_grid_item(item, remainder, path, context)
152
+ begin
153
+ PathResolver.resolve(item, remainder)
154
+ rescue MissingDataError => e
155
+ raise MissingDataError, "#{describe(context)}:{{#{path}}} #{e.message}"
156
+ end
157
+ end
158
+
159
+ def resolve_row_label(path, context)
160
+ scopes = context[:row_scopes]
161
+ if scopes.nil? || scopes.empty?
162
+ raise PowerTom::Error,
163
+ "表格行标签 {{#{path}}} 不在已展开的循环行里:请把标签放进标记了 [] 的模板行"
164
+ end
165
+
166
+ prefix = scopes.keys.select { |item| path == item || path.start_with?("#{item}.") }
167
+ .max_by(&:length)
168
+ unless prefix
169
+ expected = scopes.keys.map { |item| "{{#{item}.字段}}" }.join("、")
170
+ raise PowerTom::Error,
171
+ "表格行标签 {{#{path}}} 与循环数组不匹配(当前行作用域:#{expected})"
172
+ end
173
+
174
+ remainder = path.delete_prefix(prefix).delete_prefix(".")
175
+ if remainder.include?("[]")
176
+ raise PowerTom::Error,
177
+ "表格行标签 {{#{path}}} 引用了未展开的下一级数组" \
178
+ "(当前行只展开到 #{prefix},只支持两级)"
179
+ end
180
+ item = scopes[prefix]
181
+ return item if remainder.empty?
182
+
183
+ begin
184
+ PathResolver.resolve(item, remainder)
185
+ rescue MissingDataError => e
186
+ raise MissingDataError, "#{describe(context)}:{{#{path}}} #{e.message}"
187
+ end
188
+ end
189
+
190
+ def describe(context)
191
+ "第 #{context[:slide_no]} 页 形状'#{context[:shape]}'"
192
+ end
193
+
194
+ def to_text(value, path)
195
+ case value
196
+ when nil then ""
197
+ when String, Numeric, Symbol, Date, Time, DateTime, true, false then value.to_s
198
+ else
199
+ raise PowerTom::Error,
200
+ "{{#{path}}} 取到 #{value.class},v0 只支持把标量渲染为文本;数组请配合页面克隆使用"
201
+ end
202
+ end
203
+ end
204
+ end
@@ -0,0 +1,45 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "date"
4
+ require "tomlrb"
5
+
6
+ module PowerTom
7
+ # 数据装载。TOML 是 gem 的默认数据格式(约定优于配置):
8
+ # PowerTom.render("t.pptx", data: "data.toml") # String → 按路径读 TOML
9
+ # PowerTom.render("t.pptx", data: { ... }) # 直接传 Hash
10
+ module DataLoading
11
+ module_function
12
+
13
+ def coerce(data)
14
+ return data unless data.is_a?(String)
15
+
16
+ unless data.end_with?(".toml")
17
+ raise InvalidTemplateError,
18
+ "数据文件 #{data} 不是 .toml:TOML 是 PowerTom 的默认数据格式,v0 只支持 .toml"
19
+ end
20
+ raise InvalidTemplateError, "数据文件不存在: #{data}" unless File.file?(data)
21
+
22
+ normalize_dates(Tomlrb.load_file(data))
23
+ rescue Tomlrb::ParseError => e
24
+ raise InvalidTemplateError, "TOML 数据文件解析失败(#{data}):#{e.message}"
25
+ end
26
+
27
+ # tomlrb 把 TOML 日期时间解析成自己的 Tomlrb::LocalDate / LocalTime /
28
+ # LocalDateTime,它们不响应 strftime,date formatter 无法处理。
29
+ # 这里统一归一化为 Ruby 的 Date / Time,让 TOML 数据与 Hash 数据行为一致。
30
+ def normalize_dates(value)
31
+ case value
32
+ when Hash then value.transform_values { |v| normalize_dates(v) }
33
+ when Array then value.map { |v| normalize_dates(v) }
34
+ when Tomlrb::LocalDate
35
+ Date.new(value.year, value.month, value.day)
36
+ when Tomlrb::LocalDateTime
37
+ value.to_time
38
+ when Tomlrb::LocalTime
39
+ # 只有时刻没有日期,挂到 1970-01-01(TOML 本地时间的常见处理)
40
+ Time.utc(1970, 1, 1, value.hour, value.min, value.sec)
41
+ else value
42
+ end
43
+ end
44
+ end
45
+ end
@@ -0,0 +1,114 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "date"
4
+
5
+ module PowerTom
6
+ # §3.4 Formatter:{{path:name}} / {{path:name.arg}}
7
+ # 冒号后的词映射到注册的 proc;proc 收到 (value, arg),返回值 to_s 后落盘。
8
+ #
9
+ # 内置 currency / percent / number / date 四族;
10
+ # 自定义:PowerTom.register_formatter("rmb_upper") { |value, arg| ... }
11
+ module Formatter
12
+ class << self
13
+ def register(name, &block)
14
+ raise ArgumentError, "formatter 名不能为空" if name.nil? || name.to_s.empty?
15
+ raise ArgumentError, "formatter 需要接收 (value, arg) 的 block" unless block
16
+ registry[name.to_s] = block
17
+ name.to_s
18
+ end
19
+
20
+ def registered?(name)
21
+ registry.key?(name.to_s)
22
+ end
23
+
24
+ def unregister_formatter(name)
25
+ registry.delete(name.to_s)
26
+ end
27
+
28
+ def registered_names
29
+ registry.keys.sort
30
+ end
31
+
32
+ # spec:"currency" / "percent.1" / "date.year_month";nil → nil(无格式化)
33
+ def apply(value, spec)
34
+ return nil if spec.nil?
35
+ name, arg = parse_spec(spec)
36
+ proc = registry[name]
37
+ unless proc
38
+ raise PowerTom::Error,
39
+ "未注册的 formatter '#{name}'(可用:#{registered_names.join(', ')})"
40
+ end
41
+ proc.call(value, arg).to_s
42
+ end
43
+
44
+ def parse_spec(spec)
45
+ parts = spec.split(".")
46
+ arg = parts.length > 1 ? parts[1..].join(".") : nil
47
+ [parts.first, arg]
48
+ end
49
+
50
+ private
51
+
52
+ def registry
53
+ @registry ||= {}
54
+ end
55
+ end
56
+
57
+ # ---- 内置四族(§3.4)----
58
+
59
+ module_function
60
+
61
+ def numeric!(value, name)
62
+ return value if value.is_a?(Numeric)
63
+ raise PowerTom::Error, "formatter '#{name}' 要求数字,得到 #{value.class}"
64
+ end
65
+
66
+ def thousands(int_str)
67
+ int_str.gsub(/\B(?=(\d{3})+(?!\d))/, ",")
68
+ end
69
+
70
+ def format_decimal(value, precision)
71
+ formatted = format("%.#{precision}f", value)
72
+ sign = formatted.start_with?("-") ? "-" : ""
73
+ int_part, dot, frac = formatted.delete_prefix("-").partition(".")
74
+ "#{sign}#{thousands(int_part)}#{dot}#{frac}"
75
+ end
76
+
77
+ register("currency") do |value, arg|
78
+ v = PowerTom::Formatter.numeric!(value, "currency")
79
+ decimals = arg ? arg.to_i.clamp(0, 6) : 2
80
+ "¥#{PowerTom::Formatter.format_decimal(v, decimals)}"
81
+ end
82
+
83
+ # 比例值 ×100:0.297 → "29.7%"(percent.1);0.297 → "30%"(percent)
84
+ register("percent") do |value, arg|
85
+ v = PowerTom::Formatter.numeric!(value, "percent")
86
+ decimals = arg ? arg.to_i.clamp(0, 6) : 0
87
+ "#{PowerTom::Formatter.format_decimal(v * 100, decimals)}%"
88
+ end
89
+
90
+ register("number") do |value, arg|
91
+ v = PowerTom::Formatter.numeric!(value, "number")
92
+ decimals = arg ? arg.to_i.clamp(0, 6) : 0
93
+ PowerTom::Formatter.format_decimal(v, decimals)
94
+ end
95
+
96
+ DATE_PATTERNS = {
97
+ nil => "%Y-%m-%d",
98
+ "year_month" => "%Y年%m月",
99
+ "cn" => "%Y年%m月%d日",
100
+ "short" => "%m/%d"
101
+ }.freeze
102
+
103
+ register("date") do |value, arg|
104
+ unless value.respond_to?(:strftime)
105
+ raise PowerTom::Error, "formatter 'date' 要求 Date/Time,得到 #{value.class}"
106
+ end
107
+ pattern = DATE_PATTERNS.fetch(arg) do
108
+ raise PowerTom::Error,
109
+ "formatter 'date' 不支持 '#{arg}'(可用:nil, #{DATE_PATTERNS.keys.compact.join(', ')})"
110
+ end
111
+ value.strftime(pattern)
112
+ end
113
+ end
114
+ end
@@ -0,0 +1,53 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "path_resolver"
4
+
5
+ module PowerTom
6
+ # #grid 动态列的取值语义(Binder 与 Validator 共用,保证校验与渲染一致)。
7
+ #
8
+ # 列项:Hash 取 key 字段作为列键;标量列直接作为列键。
9
+ # 交叉值:有 value 参数时取 row[value][col_key],否则取 row[col_key]。
10
+ module GridValue
11
+ module_function
12
+
13
+ def column_key(col)
14
+ return col unless col.is_a?(Hash)
15
+
16
+ key = col.key?(:key) ? col[:key] : col["key"]
17
+ raise MissingDataError, "缺少 'key' 字段" if key.nil?
18
+
19
+ key
20
+ end
21
+
22
+ # 列带里第 template_index 个模板列对应的取值字段:
23
+ # 未声明 value → nil(row[col.key])
24
+ # 声明 1 个 → 所有模板列共用
25
+ # 声明多个 → 与模板列一一对应(数量由 TableLoop 校验)
26
+ def band_value_path(value_paths, template_index)
27
+ return nil if value_paths.nil? || value_paths.empty?
28
+
29
+ value_paths.size == 1 ? value_paths.first : value_paths[template_index]
30
+ end
31
+
32
+ def cell_value(row, col, value_path)
33
+ key = column_key(col)
34
+ container = value_path ? PathResolver.resolve(row, value_path) : row
35
+ unless container.is_a?(Hash)
36
+ label = value_path ? "行数据的 '#{value_path}'" : "行数据"
37
+ raise MissingDataError, "#{label} 需要 Hash,得到 #{container.class}"
38
+ end
39
+
40
+ fetch(container, key)
41
+ end
42
+
43
+ def fetch(container, key)
44
+ return container[key] if container.key?(key)
45
+
46
+ name = key.to_s
47
+ return container[name] if container.key?(name)
48
+ return container[name.to_sym] if container.key?(name.to_sym)
49
+
50
+ raise MissingDataError, "数据里没有字段 '#{name}'"
51
+ end
52
+ end
53
+ end
@@ -0,0 +1,52 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PowerTom
4
+ # 路径解析(§3.2:点路径与下标)。Binder 与 Validator 共用同一套取值语义,
5
+ # 保证"校验时说的"和"渲染时做的"永远一致。
6
+ #
7
+ # 抛出的 MissingDataError 只含原因短语(如"数据里没有字段 'x'"),
8
+ # 页码/形状/标签等定位信息由调用方补充。
9
+ module PathResolver
10
+ SEGMENT_RE = /\A([A-Za-z0-9_]+)(?:\[(\d+)\])?\z/.freeze
11
+
12
+ module_function
13
+
14
+ def resolve(data, path)
15
+ current = data
16
+ path.split(".").each do |segment|
17
+ m = segment.match(SEGMENT_RE)
18
+ unless m
19
+ raise MissingDataError,
20
+ "路径段 '#{segment}' 不合法,只支持 字段 与 字段[下标]"
21
+ end
22
+ current = fetch_field(current, m[1], path)
23
+ current = fetch_index(current, m[2]&.to_i, path) if m[2]
24
+ end
25
+ current
26
+ end
27
+
28
+ def fetch_field(current, name, path)
29
+ case current
30
+ when Hash
31
+ if current.key?(name)
32
+ current[name]
33
+ elsif current.key?(name.to_sym)
34
+ current[name.to_sym]
35
+ else
36
+ raise MissingDataError, "数据里没有字段 '#{name}'"
37
+ end
38
+ when Array
39
+ raise MissingDataError, "路径 '#{path}' 在数组上取字段 '#{name}',数组只能用 [下标]"
40
+ else
41
+ raise MissingDataError, "路径 '#{path}' 在标量 #{current.class} 上继续取字段 '#{name}'"
42
+ end
43
+ end
44
+
45
+ def fetch_index(current, index, path)
46
+ unless current.is_a?(Array) && index < current.size
47
+ raise MissingDataError, "下标 [#{index}] 越界或不在数组上"
48
+ end
49
+ current[index]
50
+ end
51
+ end
52
+ end