@h-ai/ui 1.0.0-beta.34 → 1.0.0-beta.35
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +4 -0
- package/README.ja.md +4 -0
- package/README.md +4 -0
- package/auto-import.d.ts +2 -0
- package/auto-import.js +2 -0
- package/dist/components/compounds/CronExpressionBuilder.svelte +655 -0
- package/dist/components/compounds/CronExpressionBuilder.svelte.d.ts +40 -0
- package/dist/components/compounds/DatePicker.svelte +5 -1
- package/dist/components/compounds/DatePicker.svelte.d.ts +2 -0
- package/dist/components/compounds/ScheduleInput.svelte +475 -0
- package/dist/components/compounds/ScheduleInput.svelte.d.ts +51 -0
- package/dist/components/compounds/cron-expression-builder-types.d.ts +97 -0
- package/dist/components/compounds/cron-expression-builder-types.js +1 -0
- package/dist/components/compounds/cron-expression-builder.d.ts +63 -0
- package/dist/components/compounds/cron-expression-builder.js +293 -0
- package/dist/components/compounds/index.d.ts +6 -0
- package/dist/components/compounds/index.js +5 -0
- package/dist/components/compounds/schedule-input-config.d.ts +8 -0
- package/dist/components/compounds/schedule-input-config.js +7 -0
- package/dist/components/compounds/schedule-input.d.ts +170 -0
- package/dist/components/compounds/schedule-input.js +262 -0
- package/dist/components/scenes/ai/AiDocumentEditor.svelte +15 -3
- package/dist/components/scenes/ai/document-parse.d.ts +2 -0
- package/dist/components/scenes/ai/document-parse.js +9 -5
- package/dist/components/scenes/ai/document-source-range.d.ts +10 -0
- package/dist/components/scenes/ai/document-source-range.js +90 -0
- package/dist/components/scenes/ai/document-types.d.ts +20 -0
- package/dist/components/scenes/ai/index.d.ts +1 -1
- package/dist/components/scenes/ai/markdown-parse.d.ts +2 -0
- package/dist/components/scenes/ai/markdown-parse.js +8 -5
- package/dist/components/scenes/ai/safe-html.d.ts +12 -2
- package/dist/components/scenes/ai/safe-html.js +22 -8
- package/dist/messages/en-US.json +28 -0
- package/dist/messages/ja-JP.json +28 -0
- package/dist/messages/zh-CN.json +28 -0
- package/package.json +8 -2
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ScheduleInput 的 schema 配置和分钟级日期时间工具。
|
|
3
|
+
* 计算使用配置的 IANA 时区,并保留有效回填值的显式 UTC 偏移。
|
|
4
|
+
*/
|
|
5
|
+
import { parseAbsolute, parseZonedDateTime } from '@internationalized/date';
|
|
6
|
+
const SCHEDULE_INPUT_TIMEZONE = 'Asia/Shanghai';
|
|
7
|
+
const SCHEDULE_INPUT_PRECISION = 'minute';
|
|
8
|
+
const SCHEDULE_INPUT_CONFIG_KEYS = new Set([
|
|
9
|
+
'kind',
|
|
10
|
+
'timezone',
|
|
11
|
+
'precision',
|
|
12
|
+
'allowCron',
|
|
13
|
+
]);
|
|
14
|
+
/**
|
|
15
|
+
* ScheduleInput 的默认 schema 配置。
|
|
16
|
+
*
|
|
17
|
+
* @example 模块内部上下文
|
|
18
|
+
* ```ts
|
|
19
|
+
* const config = { ...DEFAULT_SCHEDULE_INPUT_CONFIG, allowCron: true }
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
export const DEFAULT_SCHEDULE_INPUT_CONFIG = {
|
|
23
|
+
kind: 'schedule',
|
|
24
|
+
timezone: SCHEDULE_INPUT_TIMEZONE,
|
|
25
|
+
precision: SCHEDULE_INPUT_PRECISION,
|
|
26
|
+
allowCron: false,
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* 归一化 schema 元数据;未知值和不支持的配置不会被静默降级。
|
|
30
|
+
*
|
|
31
|
+
* `allowCron` 是唯一可省略的字段,省略时统一归一化为 `false`。
|
|
32
|
+
*
|
|
33
|
+
* @param value 待校验的 schema 元数据。
|
|
34
|
+
* @returns 归一化后的配置;不支持或格式错误时返回 undefined。
|
|
35
|
+
*
|
|
36
|
+
* @example
|
|
37
|
+
* ```ts
|
|
38
|
+
* import { normalizeScheduleInputConfig } from '@h-ai/ui'
|
|
39
|
+
* const config = normalizeScheduleInputConfig({
|
|
40
|
+
* kind: 'schedule', timezone: 'Asia/Shanghai', precision: 'minute',
|
|
41
|
+
* })
|
|
42
|
+
* ```
|
|
43
|
+
*/
|
|
44
|
+
export function normalizeScheduleInputConfig(value) {
|
|
45
|
+
if (!isRecord(value)) {
|
|
46
|
+
return undefined;
|
|
47
|
+
}
|
|
48
|
+
if (Object.keys(value).some(key => !SCHEDULE_INPUT_CONFIG_KEYS.has(key))) {
|
|
49
|
+
return undefined;
|
|
50
|
+
}
|
|
51
|
+
if (value.kind !== 'schedule'
|
|
52
|
+
|| !isIanaTimezone(value.timezone)
|
|
53
|
+
|| value.precision !== SCHEDULE_INPUT_PRECISION
|
|
54
|
+
|| (value.allowCron !== undefined && typeof value.allowCron !== 'boolean')) {
|
|
55
|
+
return undefined;
|
|
56
|
+
}
|
|
57
|
+
return {
|
|
58
|
+
kind: 'schedule',
|
|
59
|
+
timezone: value.timezone,
|
|
60
|
+
precision: SCHEDULE_INPUT_PRECISION,
|
|
61
|
+
allowCron: value.allowCron ?? false,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
const DATE_RE = /^(\d{4})-(\d{2})-(\d{2})$/;
|
|
65
|
+
const VALUE_RE = /^(\d{4}-\d{2}-\d{2})T(\d{2}):(\d{2}):(\d{2})(Z|[+-]\d{2}:\d{2})$/;
|
|
66
|
+
const HOUR_OR_MINUTE_RE = /^\d{1,2}$/;
|
|
67
|
+
/**
|
|
68
|
+
* 将公开的 canonical 日期时间值拆成可编辑字段;非 canonical 值也会保留其精度信息。
|
|
69
|
+
*
|
|
70
|
+
* @param value 待解析的日期时间值。
|
|
71
|
+
* @returns 解析后的字段和精度信息;格式不匹配时返回 undefined。
|
|
72
|
+
*
|
|
73
|
+
* @example 模块内部上下文
|
|
74
|
+
* ```ts
|
|
75
|
+
* const parsed = parseScheduleDateTimeValue('2026-11-22T10:05:00+08:00')
|
|
76
|
+
* ```
|
|
77
|
+
*/
|
|
78
|
+
export function parseScheduleDateTimeValue(value) {
|
|
79
|
+
if (typeof value !== 'string') {
|
|
80
|
+
return undefined;
|
|
81
|
+
}
|
|
82
|
+
const match = VALUE_RE.exec(value);
|
|
83
|
+
if (!match) {
|
|
84
|
+
return undefined;
|
|
85
|
+
}
|
|
86
|
+
return {
|
|
87
|
+
date: match[1] ?? '',
|
|
88
|
+
hour: match[2] ?? '',
|
|
89
|
+
minute: match[3] ?? '',
|
|
90
|
+
seconds: match[4] ?? '',
|
|
91
|
+
offset: match[5] ?? '',
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* 将分钟级草稿转换为带 UTC 偏移的 ISO 日期时间。
|
|
96
|
+
* 缺失的夏令时分钟会返回 undefined。重叠分钟默认取较早的一次,回填值可指定实际偏移。
|
|
97
|
+
*
|
|
98
|
+
* @param draft 日期时间编辑草稿。
|
|
99
|
+
* @param timezone IANA 时区,默认 `Asia/Shanghai`。
|
|
100
|
+
* @param offset 回填值已有的偏移,传入时核对该偏移与时区、日期和分钟一致。
|
|
101
|
+
* @returns ISO 日期时间;草稿、时区或偏移不合法时返回 undefined。
|
|
102
|
+
*
|
|
103
|
+
* @example 模块内部上下文
|
|
104
|
+
* ```ts
|
|
105
|
+
* const value = serializeScheduleDateTime({ date: '2030-01-22', hour: '10', minute: '05' }, 'America/Los_Angeles')
|
|
106
|
+
* // '2030-01-22T10:05:00-08:00'
|
|
107
|
+
* ```
|
|
108
|
+
*/
|
|
109
|
+
export function serializeScheduleDateTime(draft, timezone = SCHEDULE_INPUT_TIMEZONE, offset) {
|
|
110
|
+
if (!isStructurallyValidDraft(draft) || !isIanaTimezone(timezone))
|
|
111
|
+
return undefined;
|
|
112
|
+
const local = `${draft.date}T${padTwoDigits(Number.parseInt(draft.hour, 10))}:${padTwoDigits(Number.parseInt(draft.minute, 10))}:00`;
|
|
113
|
+
try {
|
|
114
|
+
if (offset !== undefined) {
|
|
115
|
+
const resolved = isoPart(parseAbsolute(`${local}${offset}`, timezone).toString());
|
|
116
|
+
const normalizedOffset = offset === 'Z'
|
|
117
|
+
? '+00:00'
|
|
118
|
+
: offset;
|
|
119
|
+
return resolved === `${local}${normalizedOffset}`
|
|
120
|
+
? `${local}${offset}`
|
|
121
|
+
: undefined;
|
|
122
|
+
}
|
|
123
|
+
const resolved = isoPart(parseZonedDateTime(`${local}[${timezone}]`, 'earlier').toString());
|
|
124
|
+
// 春季跳时可能把不存在的分钟挪到上一小时,比较本地字段可识别这种情况。
|
|
125
|
+
return resolved.startsWith(local)
|
|
126
|
+
? resolved
|
|
127
|
+
: undefined;
|
|
128
|
+
}
|
|
129
|
+
catch {
|
|
130
|
+
return undefined;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
function isoPart(zoned) {
|
|
134
|
+
return zoned.slice(0, zoned.indexOf('['));
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* 校验 canonical 日期时间值,当前时刻比较使用绝对时间戳而非浏览器本地时区。
|
|
138
|
+
*
|
|
139
|
+
* @param value 待校验的 canonical 值。
|
|
140
|
+
* @param now 用于未来时间比较的当前时间。
|
|
141
|
+
* @param timezone IANA 时区,默认北京时间。
|
|
142
|
+
* @returns 日期时间的结构和未来性状态。
|
|
143
|
+
*
|
|
144
|
+
* @example 模块内部上下文
|
|
145
|
+
* ```ts
|
|
146
|
+
* const status = inspectScheduleDateTimeValue('2026-11-22T10:05:00+08:00')
|
|
147
|
+
* ```
|
|
148
|
+
*/
|
|
149
|
+
export function inspectScheduleDateTimeValue(value, now = new Date(), timezone = SCHEDULE_INPUT_TIMEZONE) {
|
|
150
|
+
if (value === undefined || value === null || value === '') {
|
|
151
|
+
return 'empty';
|
|
152
|
+
}
|
|
153
|
+
if (typeof value !== 'string') {
|
|
154
|
+
return 'invalid';
|
|
155
|
+
}
|
|
156
|
+
const parsed = parseScheduleDateTimeValue(value);
|
|
157
|
+
if (!parsed) {
|
|
158
|
+
return 'invalid';
|
|
159
|
+
}
|
|
160
|
+
if (parsed.seconds !== '00') {
|
|
161
|
+
return 'invalid';
|
|
162
|
+
}
|
|
163
|
+
return inspectScheduleDateTimeDraft(parsed, now, timezone, parsed.offset);
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* 校验可编辑草稿;空草稿只在 required 层决定是否报错。
|
|
167
|
+
*
|
|
168
|
+
* @param draft 日期时间编辑草稿。
|
|
169
|
+
* @param now 用于未来时间比较的当前时间。
|
|
170
|
+
* @param timezone IANA 时区,默认北京时间。
|
|
171
|
+
* @param offset 回填的显式偏移。
|
|
172
|
+
* @returns 草稿的结构和未来性状态。
|
|
173
|
+
*
|
|
174
|
+
* @example 模块内部上下文
|
|
175
|
+
* ```ts
|
|
176
|
+
* const status = inspectScheduleDateTimeDraft({ date: '2026-11-22', hour: '10', minute: '05' })
|
|
177
|
+
* ```
|
|
178
|
+
*/
|
|
179
|
+
export function inspectScheduleDateTimeDraft(draft, now = new Date(), timezone = SCHEDULE_INPUT_TIMEZONE, offset) {
|
|
180
|
+
const { date, hour, minute } = draft;
|
|
181
|
+
if (!date && !hour && !minute) {
|
|
182
|
+
return 'empty';
|
|
183
|
+
}
|
|
184
|
+
if (!date || !hour || !minute) {
|
|
185
|
+
return 'partial';
|
|
186
|
+
}
|
|
187
|
+
const value = serializeScheduleDateTime(draft, timezone, offset);
|
|
188
|
+
if (!value || !Number.isFinite(now.getTime()))
|
|
189
|
+
return 'invalid';
|
|
190
|
+
const scheduledAt = Date.parse(value);
|
|
191
|
+
return scheduledAt <= now.getTime()
|
|
192
|
+
? 'past'
|
|
193
|
+
: 'valid';
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* 判断日期时间值是否满足可选/必填字段的有效性。
|
|
197
|
+
*
|
|
198
|
+
* @param value 待校验的 canonical 值。
|
|
199
|
+
* @param required 是否要求非空值。
|
|
200
|
+
* @param now 用于未来时间比较的当前时间。
|
|
201
|
+
* @param timezone IANA 时区,默认北京时间。
|
|
202
|
+
* @returns 值满足字段约束时为 true。
|
|
203
|
+
*
|
|
204
|
+
* @example 模块内部上下文
|
|
205
|
+
* ```ts
|
|
206
|
+
* const valid = isScheduleDateTimeValid('2026-11-22T10:05:00+08:00')
|
|
207
|
+
* ```
|
|
208
|
+
*/
|
|
209
|
+
export function isScheduleDateTimeValid(value, required = false, now = new Date(), timezone = SCHEDULE_INPUT_TIMEZONE) {
|
|
210
|
+
const status = inspectScheduleDateTimeValue(value, now, timezone);
|
|
211
|
+
return status === 'valid' || (status === 'empty' && !required);
|
|
212
|
+
}
|
|
213
|
+
function isIanaTimezone(value) {
|
|
214
|
+
if (typeof value !== 'string' || !/^[a-z][\w+-]*(?:\/[\w+-]+)*$/i.test(value))
|
|
215
|
+
return false;
|
|
216
|
+
try {
|
|
217
|
+
// 排除不受当前运行时支持的时区名称,固定偏移不能代替 IANA 名称。
|
|
218
|
+
return new Intl.DateTimeFormat('en', { timeZone: value }).resolvedOptions().timeZone.length > 0;
|
|
219
|
+
}
|
|
220
|
+
catch {
|
|
221
|
+
return false;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
function isRecord(value) {
|
|
225
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
226
|
+
}
|
|
227
|
+
function isStructurallyValidDraft(draft) {
|
|
228
|
+
const dateMatch = DATE_RE.exec(draft.date);
|
|
229
|
+
return dateMatch !== null
|
|
230
|
+
&& isValidCalendarDate(dateMatch)
|
|
231
|
+
&& isTwoDigitInteger(draft.hour, 0, 23)
|
|
232
|
+
&& isTwoDigitInteger(draft.minute, 0, 59);
|
|
233
|
+
}
|
|
234
|
+
function isValidCalendarDate(match) {
|
|
235
|
+
const year = Number.parseInt(match[1] ?? '', 10);
|
|
236
|
+
const month = Number.parseInt(match[2] ?? '', 10);
|
|
237
|
+
const day = Number.parseInt(match[3] ?? '', 10);
|
|
238
|
+
if (year < 1 || year > 9999 || month < 1 || month > 12 || day < 1) {
|
|
239
|
+
return false;
|
|
240
|
+
}
|
|
241
|
+
const daysInMonth = month === 2
|
|
242
|
+
? (isLeapYear(year)
|
|
243
|
+
? 29
|
|
244
|
+
: 28)
|
|
245
|
+
: [4, 6, 9, 11].includes(month)
|
|
246
|
+
? 30
|
|
247
|
+
: 31;
|
|
248
|
+
return day <= daysInMonth;
|
|
249
|
+
}
|
|
250
|
+
function isTwoDigitInteger(value, min, max) {
|
|
251
|
+
if (!HOUR_OR_MINUTE_RE.test(value)) {
|
|
252
|
+
return false;
|
|
253
|
+
}
|
|
254
|
+
const parsed = Number.parseInt(value, 10);
|
|
255
|
+
return parsed >= min && parsed <= max;
|
|
256
|
+
}
|
|
257
|
+
function isLeapYear(year) {
|
|
258
|
+
return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
|
|
259
|
+
}
|
|
260
|
+
function padTwoDigits(value) {
|
|
261
|
+
return String(value).padStart(2, '0');
|
|
262
|
+
}
|
|
@@ -50,6 +50,7 @@
|
|
|
50
50
|
import { resolveDocumentMarkdownContent } from './document-download.js'
|
|
51
51
|
import { renderMarkdownDocument } from './document-parse.js'
|
|
52
52
|
import { documentRenderPool, useDocumentRenderWorker } from './document-render-pool.js'
|
|
53
|
+
import { resolveMarkdownSourceRange } from './document-source-range.js'
|
|
53
54
|
import { parseMarkdown } from './markdown-parse.js'
|
|
54
55
|
import {
|
|
55
56
|
createMermaidSourceSignature,
|
|
@@ -353,6 +354,7 @@
|
|
|
353
354
|
allowUnsafeCodePreview = false,
|
|
354
355
|
// 是否按安全白名单解析原始 HTML 标签。
|
|
355
356
|
allowHtmlTags = false,
|
|
357
|
+
remoteImages = true,
|
|
356
358
|
// 代码预览切换模式下展示在语言标签旁的提示文案。
|
|
357
359
|
codePreviewHint = '',
|
|
358
360
|
// 是否启用语法高亮。
|
|
@@ -484,6 +486,7 @@
|
|
|
484
486
|
let savedSelectionRange = $state<Range | null>(null)
|
|
485
487
|
// 纯文本快照用于 DOM 被局部重建后的兜底恢复,避免只靠 Range 引用失效。
|
|
486
488
|
let savedSelectionSnapshot = $state<MarkdownSelectionSnapshot | null>(null)
|
|
489
|
+
let savedSelectionContent = ''
|
|
487
490
|
// 真实尺寸修正只需要排队一帧,避免反复触发 handleSelectionChange 形成抖动。
|
|
488
491
|
let selectionToolbarMeasurePending = false
|
|
489
492
|
// 选区刷新统一合并到同一帧,避免 selectionchange / mouseup / blur 连续触发时抖动。
|
|
@@ -522,12 +525,13 @@
|
|
|
522
525
|
codePreviewHint: normalizedCodePreviewHint,
|
|
523
526
|
breaks,
|
|
524
527
|
allowHtmlTags,
|
|
528
|
+
remoteImages,
|
|
525
529
|
},
|
|
526
530
|
} satisfies DocumentRenderJob)
|
|
527
531
|
let useBackgroundRender = $state(false)
|
|
528
532
|
let lastRender = $state.raw<{ job: DocumentRenderJob, result: MarkdownRenderResult }>()
|
|
529
533
|
const renderInWorker = $derived(useBackgroundRender && useDocumentRenderWorker(renderJob.content))
|
|
530
|
-
const renderResult = $derived(renderInWorker
|
|
534
|
+
const renderResult = $derived(renderInWorker && lastRender?.job.options?.remoteImages === remoteImages
|
|
531
535
|
? lastRender?.result ?? { outline: [], codeBlocks: [], blocks: [] }
|
|
532
536
|
: renderMarkdownDocument(renderJob.content, renderJob.options))
|
|
533
537
|
const renderPending = $derived(renderInWorker && lastRender?.job !== renderJob)
|
|
@@ -1124,7 +1128,7 @@
|
|
|
1124
1128
|
? `<p class="hai-md-preview-desc">${escapePreviewText(result.description)}</p>`
|
|
1125
1129
|
: ''
|
|
1126
1130
|
|
|
1127
|
-
if (result.kind === 'mermaid') {
|
|
1131
|
+
if (result.kind === 'mermaid' && remoteImages) {
|
|
1128
1132
|
host.innerHTML = `<div class="hai-md-preview-card hai-md-preview-mermaid"><div class="hai-md-preview-head">${previewTitle}</div>${previewDesc}<div class="hai-md-mermaid hai-md-mermaid-preview" contenteditable="false"></div></div>`
|
|
1129
1133
|
const mermaidEl = host.querySelector<HTMLElement>('.hai-md-mermaid-preview')
|
|
1130
1134
|
if (mermaidEl) {
|
|
@@ -1139,7 +1143,7 @@
|
|
|
1139
1143
|
return
|
|
1140
1144
|
}
|
|
1141
1145
|
|
|
1142
|
-
if (result.kind === 'html') {
|
|
1146
|
+
if (result.kind === 'html' && remoteImages) {
|
|
1143
1147
|
const previewSandbox = escapePreviewAttribute(
|
|
1144
1148
|
resolvePreviewSandbox(result.allowScripts),
|
|
1145
1149
|
)
|
|
@@ -1153,6 +1157,7 @@
|
|
|
1153
1157
|
showCopyButton: false,
|
|
1154
1158
|
breaks,
|
|
1155
1159
|
allowHtmlTags,
|
|
1160
|
+
remoteImages,
|
|
1156
1161
|
})
|
|
1157
1162
|
|
|
1158
1163
|
host.innerHTML = `<div class="hai-md-preview-card"><div class="hai-md-preview-head">${previewTitle}</div>${previewDesc}<div class="hai-md-preview-rendered">${markdownHtml}</div></div>`
|
|
@@ -1848,6 +1853,7 @@
|
|
|
1848
1853
|
function rememberPreviewSelection(range: Range): void {
|
|
1849
1854
|
savedSelectionRange = range.cloneRange()
|
|
1850
1855
|
savedSelectionSnapshot = capturePreviewSelectionSnapshot(range)
|
|
1856
|
+
savedSelectionContent = content
|
|
1851
1857
|
}
|
|
1852
1858
|
|
|
1853
1859
|
/**
|
|
@@ -2076,6 +2082,7 @@
|
|
|
2076
2082
|
linkDraft = ''
|
|
2077
2083
|
savedSelectionRange = null
|
|
2078
2084
|
savedSelectionSnapshot = null
|
|
2085
|
+
savedSelectionContent = ''
|
|
2079
2086
|
selectionFormatState = { ...DEFAULT_SELECTION_FORMAT_STATE }
|
|
2080
2087
|
}
|
|
2081
2088
|
|
|
@@ -2514,12 +2521,17 @@
|
|
|
2514
2521
|
|
|
2515
2522
|
activeSelectionMenu = null
|
|
2516
2523
|
activeSelectionMenuTrigger = null
|
|
2524
|
+
const sourceRange = savedSelectionSnapshot && previewHost && !renderPending
|
|
2525
|
+
&& sourceKind !== 'code' && savedSelectionContent === content
|
|
2526
|
+
? resolveMarkdownSourceRange(content, previewHost.textContent ?? '', savedSelectionSnapshot)
|
|
2527
|
+
: undefined
|
|
2517
2528
|
await onrewrite({
|
|
2518
2529
|
actionId,
|
|
2519
2530
|
selectedText,
|
|
2520
2531
|
selectionSnapshot: savedSelectionSnapshot
|
|
2521
2532
|
? { ...savedSelectionSnapshot }
|
|
2522
2533
|
: undefined,
|
|
2534
|
+
...(sourceRange && { sourceRange }),
|
|
2523
2535
|
content,
|
|
2524
2536
|
title: title || undefined,
|
|
2525
2537
|
})
|
|
@@ -8,7 +8,7 @@ import { uiM } from '../../../messages.js';
|
|
|
8
8
|
import { createEditorMarkdownExtensions, extractPlainTextFromTokens, } from './editor-markdown-extensions.js';
|
|
9
9
|
import { highlightCode, isLanguageSupported } from './highlight.js';
|
|
10
10
|
import { isMermaidLanguage } from './mermaid-render.js';
|
|
11
|
-
import { escapeHtml, isExternalLinkHref, sanitizeImageSrc, sanitizeLinkHref, sanitizeMarkdownHtml, } from './safe-html.js';
|
|
11
|
+
import { escapeHtml, isExternalLinkHref, renderImagePlaceholder, sanitizeImageSrc, sanitizeLinkHref, sanitizeMarkdownHtml, } from './safe-html.js';
|
|
12
12
|
/** 文档模式的默认解析选项。 */
|
|
13
13
|
const DEFAULT_OPTIONS = {
|
|
14
14
|
enableHighlight: true,
|
|
@@ -20,6 +20,7 @@ const DEFAULT_OPTIONS = {
|
|
|
20
20
|
codePreviewHint: '',
|
|
21
21
|
breaks: true,
|
|
22
22
|
allowHtmlTags: false,
|
|
23
|
+
remoteImages: true,
|
|
23
24
|
};
|
|
24
25
|
function readHtmlTokenSource(token) {
|
|
25
26
|
if ('raw' in token && typeof token.raw === 'string') {
|
|
@@ -143,7 +144,8 @@ function createRendererObject(options, state) {
|
|
|
143
144
|
// rawLanguage is the original info string from the fence.
|
|
144
145
|
const rawLanguage = lang?.trim() || '';
|
|
145
146
|
// mermaid 块在阅读态自动渲染为图表;只有 code 模式的代码/预览切换才保留源码视图。
|
|
146
|
-
if (
|
|
147
|
+
if (options.remoteImages
|
|
148
|
+
&& isMermaidLanguage(rawLanguage)
|
|
147
149
|
&& !options.showCodePreviewToggle
|
|
148
150
|
&& isClosedFencedCodeBlock(token)) {
|
|
149
151
|
const mermaidBlockId = `hai-md-code-${state.codeBlocks.length + 1}`;
|
|
@@ -210,7 +212,7 @@ function createRendererObject(options, state) {
|
|
|
210
212
|
html(token) {
|
|
211
213
|
const source = readHtmlTokenSource(token);
|
|
212
214
|
return options.allowHtmlTags
|
|
213
|
-
? sanitizeMarkdownHtml(source)
|
|
215
|
+
? sanitizeMarkdownHtml(source, options.remoteImages)
|
|
214
216
|
: escapeHtml(source);
|
|
215
217
|
},
|
|
216
218
|
link({ href, title, tokens }) {
|
|
@@ -232,7 +234,9 @@ function createRendererObject(options, state) {
|
|
|
232
234
|
},
|
|
233
235
|
image({ href, title, text }) {
|
|
234
236
|
// safeSrc prevents dangerous image protocols.
|
|
235
|
-
const safeSrc = sanitizeImageSrc(href);
|
|
237
|
+
const safeSrc = sanitizeImageSrc(href, options.remoteImages);
|
|
238
|
+
if (!options.remoteImages && !safeSrc)
|
|
239
|
+
return renderImagePlaceholder(text ?? '');
|
|
236
240
|
// attrs is the flattened HTML attribute string.
|
|
237
241
|
const attrs = [
|
|
238
242
|
`src="${escapeHtml(safeSrc)}"`,
|
|
@@ -339,7 +343,7 @@ function renderMarkdownDocumentBlocks(content, options, state) {
|
|
|
339
343
|
htmlTokens = [];
|
|
340
344
|
}
|
|
341
345
|
for (const token of tokens) {
|
|
342
|
-
if (!isClosedMermaidToken(token, options)) {
|
|
346
|
+
if (!options.remoteImages || !isClosedMermaidToken(token, options)) {
|
|
343
347
|
htmlTokens.push(token);
|
|
344
348
|
continue;
|
|
345
349
|
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { MarkdownSelectionSnapshot, MarkdownSourceRange } from './document-types.js';
|
|
2
|
+
/**
|
|
3
|
+
* 对照实际 DOM 文本和 Markdown 字元顺序,只返回与选中文本完全相同的连续原文。
|
|
4
|
+
* 不支持的语法、插入的显示文字与无法还原的 Markdown 均没有可用位置。
|
|
5
|
+
* @example 模块内部上下文
|
|
6
|
+
* ```ts
|
|
7
|
+
* const range = resolveMarkdownSourceRange('**重点**', '重点', { start: 0, end: 2, text: '重点' })
|
|
8
|
+
* ```
|
|
9
|
+
*/
|
|
10
|
+
export declare function resolveMarkdownSourceRange(markdown: string, plainText: string, selection: MarkdownSelectionSnapshot): MarkdownSourceRange | undefined;
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { marked } from 'marked';
|
|
2
|
+
function findTextRuns(tokens, parent, base, runs) {
|
|
3
|
+
let cursor = 0;
|
|
4
|
+
for (const token of tokens) {
|
|
5
|
+
const start = parent.indexOf(token.raw, cursor);
|
|
6
|
+
if (start < 0)
|
|
7
|
+
return false;
|
|
8
|
+
const raw = token.raw;
|
|
9
|
+
cursor = start + raw.length;
|
|
10
|
+
const absoluteStart = base + start;
|
|
11
|
+
if (token.type === 'space' || token.type === 'br' || token.type === 'hr' || token.type === 'def')
|
|
12
|
+
continue;
|
|
13
|
+
if (token.type === 'list') {
|
|
14
|
+
if (!findTextRuns(token.items, raw, absoluteStart, runs))
|
|
15
|
+
return false;
|
|
16
|
+
continue;
|
|
17
|
+
}
|
|
18
|
+
if (![
|
|
19
|
+
'list_item',
|
|
20
|
+
'heading',
|
|
21
|
+
'paragraph',
|
|
22
|
+
'strong',
|
|
23
|
+
'em',
|
|
24
|
+
'del',
|
|
25
|
+
'link',
|
|
26
|
+
'text',
|
|
27
|
+
'codespan',
|
|
28
|
+
].includes(token.type)) {
|
|
29
|
+
return false;
|
|
30
|
+
}
|
|
31
|
+
const text = 'text' in token && typeof token.text === 'string'
|
|
32
|
+
? token.text
|
|
33
|
+
: undefined;
|
|
34
|
+
const children = 'tokens' in token
|
|
35
|
+
? token.tokens
|
|
36
|
+
: undefined;
|
|
37
|
+
if (Array.isArray(children) && children.length > 0) {
|
|
38
|
+
const childStart = token.type === 'list_item' || text === undefined
|
|
39
|
+
? 0
|
|
40
|
+
: raw.indexOf(text);
|
|
41
|
+
if (childStart < 0 || !findTextRuns(children, text !== undefined && token.type !== 'list_item'
|
|
42
|
+
? text
|
|
43
|
+
: raw, absoluteStart + childStart, runs)) {
|
|
44
|
+
return false;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
else if (text) {
|
|
48
|
+
const textStart = raw.indexOf(text);
|
|
49
|
+
if (textStart < 0)
|
|
50
|
+
return false;
|
|
51
|
+
runs.push({ text, start: absoluteStart + textStart });
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return true;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* 对照实际 DOM 文本和 Markdown 字元顺序,只返回与选中文本完全相同的连续原文。
|
|
58
|
+
* 不支持的语法、插入的显示文字与无法还原的 Markdown 均没有可用位置。
|
|
59
|
+
* @example 模块内部上下文
|
|
60
|
+
* ```ts
|
|
61
|
+
* const range = resolveMarkdownSourceRange('**重点**', '重点', { start: 0, end: 2, text: '重点' })
|
|
62
|
+
* ```
|
|
63
|
+
*/
|
|
64
|
+
export function resolveMarkdownSourceRange(markdown, plainText, selection) {
|
|
65
|
+
if (plainText.slice(selection.start, selection.end).trim() !== selection.text.trim())
|
|
66
|
+
return undefined;
|
|
67
|
+
const runs = [];
|
|
68
|
+
if (!findTextRuns(marked.lexer(markdown), markdown, 0, runs))
|
|
69
|
+
return undefined;
|
|
70
|
+
const positions = [];
|
|
71
|
+
let rendered = '';
|
|
72
|
+
for (const run of runs) {
|
|
73
|
+
for (const match of run.text.matchAll(/\S/g)) {
|
|
74
|
+
rendered += match[0];
|
|
75
|
+
positions.push(run.start + match.index);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
if (rendered !== plainText.replace(/\s/g, ''))
|
|
79
|
+
return undefined;
|
|
80
|
+
const first = plainText.slice(0, selection.start).replace(/\s/g, '').length;
|
|
81
|
+
const size = selection.text.replace(/\s/g, '').length;
|
|
82
|
+
if (!size || first + size > positions.length)
|
|
83
|
+
return undefined;
|
|
84
|
+
const start = positions[first];
|
|
85
|
+
const end = positions[first + size - 1] + 1;
|
|
86
|
+
const text = markdown.slice(start, end);
|
|
87
|
+
return text === selection.text.trim()
|
|
88
|
+
? { start, end, text }
|
|
89
|
+
: undefined;
|
|
90
|
+
}
|
|
@@ -122,6 +122,8 @@ export interface MarkdownRewriteRequest {
|
|
|
122
122
|
selectedText: string;
|
|
123
123
|
/** 可视正文中的精确纯文本偏移;宿主可据此映射原始 Markdown,不以纯文本猜测源码位置。 */
|
|
124
124
|
selectionSnapshot?: MarkdownSelectionSnapshot;
|
|
125
|
+
/** 仅在选区可与当前 Markdown 源文核对时提供,位置相对于 content。 */
|
|
126
|
+
sourceRange?: MarkdownSourceRange;
|
|
125
127
|
/** 触发请求时的完整文档内容。 */
|
|
126
128
|
content: string;
|
|
127
129
|
/** 当前文档标题。 */
|
|
@@ -174,6 +176,22 @@ export interface MarkdownSelectionSnapshot {
|
|
|
174
176
|
/** 选中纯文本,用于结构变化后的回退定位。 */
|
|
175
177
|
text: string;
|
|
176
178
|
}
|
|
179
|
+
/**
|
|
180
|
+
* Markdown 源文件中可核对的选区。
|
|
181
|
+
* @example
|
|
182
|
+
* ```ts
|
|
183
|
+
* import type { MarkdownSourceRange } from '@h-ai/ui'
|
|
184
|
+
* const range: MarkdownSourceRange = { start: 2, end: 4, text: '强调' }
|
|
185
|
+
* ```
|
|
186
|
+
*/
|
|
187
|
+
export interface MarkdownSourceRange {
|
|
188
|
+
/** 源文件中的 UTF-16 起始偏移。 */
|
|
189
|
+
start: number;
|
|
190
|
+
/** 源文件中的 UTF-16 结束偏移,末尾不含。 */
|
|
191
|
+
end: number;
|
|
192
|
+
/** source.slice(start, end) 对应的原文。 */
|
|
193
|
+
text: string;
|
|
194
|
+
}
|
|
177
195
|
/**
|
|
178
196
|
* 颜色面板一次只会修改前景色或背景色中的一个维度。
|
|
179
197
|
*
|
|
@@ -274,6 +292,8 @@ export interface AiDocumentEditorProps extends DataAttributes {
|
|
|
274
292
|
showCodePreviewToggle?: boolean;
|
|
275
293
|
/** 是否按安全白名单解析原始 HTML。 */
|
|
276
294
|
allowHtmlTags?: boolean;
|
|
295
|
+
/** 默认允许网络图片。设为 false 时 Markdown 图片使用替代文本,HTML 运行预览显示源码。 */
|
|
296
|
+
remoteImages?: boolean;
|
|
277
297
|
/**
|
|
278
298
|
* 是否启用内置的高风险代码预览。
|
|
279
299
|
*
|
|
@@ -11,7 +11,7 @@ export { downloadAiDocument, resolveDocumentDownloadActions, resolveDocumentMark
|
|
|
11
11
|
export type { AiDocumentDownloadFormat, AiDocumentDownloadRequest, AiDocumentResolvedDownloadAction, } from './document-download.js';
|
|
12
12
|
export { renderMarkdownDocument } from './document-parse.js';
|
|
13
13
|
export type { MarkdownDocumentBlock, MarkdownDocumentHtmlBlock, MarkdownDocumentMermaidBlock, MarkdownDocumentParseOptions, MarkdownRenderResult, } from './document-parse.js';
|
|
14
|
-
export type { AiDocumentEditorProps, MarkdownBlockStyleKind, MarkdownCodeBlockItem, MarkdownCodeRunRequest, MarkdownCodeRunResult, MarkdownColorFormatRequest, MarkdownInlineFormatKind, MarkdownOutlineItem, MarkdownRewriteAction, MarkdownRewriteRequest, MarkdownTextAlignKind, MarkdownToolbarDownloadAction, } from './document-types.js';
|
|
14
|
+
export type { AiDocumentEditorProps, MarkdownBlockStyleKind, MarkdownCodeBlockItem, MarkdownCodeRunRequest, MarkdownCodeRunResult, MarkdownColorFormatRequest, MarkdownInlineFormatKind, MarkdownOutlineItem, MarkdownRewriteAction, MarkdownRewriteRequest, MarkdownSourceRange, MarkdownTextAlignKind, MarkdownToolbarDownloadAction, } from './document-types.js';
|
|
15
15
|
export { highlightCode, isLanguageSupported } from './highlight.js';
|
|
16
16
|
export { parseMarkdown } from './markdown-parse.js';
|
|
17
17
|
export type { MarkdownParseOptions } from './markdown-parse.js';
|
|
@@ -23,6 +23,8 @@ export interface MarkdownParseOptions {
|
|
|
23
23
|
breaks?: boolean;
|
|
24
24
|
/** 是否按安全白名单解析原始 HTML(默认 false);img可保留1–99999正整数width/height以预留空间 */
|
|
25
25
|
allowHtmlTags?: boolean;
|
|
26
|
+
/** 默认允许网络图片。禁用时网络图片显示替代文本,只保留内联数据图片。 */
|
|
27
|
+
remoteImages?: boolean;
|
|
26
28
|
}
|
|
27
29
|
/**
|
|
28
30
|
* 将 Markdown 文本解析为 HTML
|
|
@@ -9,7 +9,7 @@ import { Marked } from 'marked';
|
|
|
9
9
|
import { uiM } from '../../../messages.js';
|
|
10
10
|
import { createEditorMarkdownExtensions } from './editor-markdown-extensions.js';
|
|
11
11
|
import { highlightCode, isLanguageSupported } from './highlight.js';
|
|
12
|
-
import { escapeHtml, isExternalLinkHref, sanitizeImageSrc, sanitizeLinkHref, sanitizeMarkdownHtml, } from './safe-html.js';
|
|
12
|
+
import { escapeHtml, isExternalLinkHref, renderImagePlaceholder, sanitizeImageSrc, sanitizeLinkHref, sanitizeMarkdownHtml, } from './safe-html.js';
|
|
13
13
|
function readHtmlTokenSource(token) {
|
|
14
14
|
if ('raw' in token && typeof token.raw === 'string') {
|
|
15
15
|
return token.raw;
|
|
@@ -85,13 +85,13 @@ function renderHtmlWithCode(source, options) {
|
|
|
85
85
|
let html = '';
|
|
86
86
|
let offset = 0;
|
|
87
87
|
for (const match of source.matchAll(/<pre\b[^>]*>\s*<code\b([^>]*)>([\s\S]*?)<\/code>\s*<\/pre>/gi)) {
|
|
88
|
-
html += sanitizeMarkdownHtml(source.slice(offset, match.index));
|
|
88
|
+
html += sanitizeMarkdownHtml(source.slice(offset, match.index), options.remoteImages);
|
|
89
89
|
const classes = /\bclass\s*=\s*(?:"([^"]*)"|'([^']*)')/i.exec(match[1]);
|
|
90
90
|
const language = /(?:^|\s)language-([a-z\d#+.-]+)(?:\s|$)/i.exec(classes?.[1] ?? classes?.[2] ?? '')?.[1];
|
|
91
91
|
html += renderCodeBlock(decodeCodeText(match[2]), language, options);
|
|
92
92
|
offset = match.index + match[0].length;
|
|
93
93
|
}
|
|
94
|
-
return html + sanitizeMarkdownHtml(source.slice(offset));
|
|
94
|
+
return html + sanitizeMarkdownHtml(source.slice(offset), options.remoteImages);
|
|
95
95
|
}
|
|
96
96
|
/**
|
|
97
97
|
* 创建自定义渲染器对象
|
|
@@ -130,7 +130,9 @@ function createRendererObject(options) {
|
|
|
130
130
|
// 图片:添加 loading="lazy",验证 src 协议
|
|
131
131
|
image({ href, title, text }) {
|
|
132
132
|
// 安全检查:仅允许安全协议
|
|
133
|
-
const safeSrc = sanitizeImageSrc(href);
|
|
133
|
+
const safeSrc = sanitizeImageSrc(href, options.remoteImages);
|
|
134
|
+
if (!options.remoteImages && !safeSrc)
|
|
135
|
+
return renderImagePlaceholder(text ?? '');
|
|
134
136
|
const attrs = [
|
|
135
137
|
`src="${escapeHtml(safeSrc)}"`,
|
|
136
138
|
`alt="${escapeHtml(text || '')}"`,
|
|
@@ -182,6 +184,7 @@ const DEFAULT_OPTIONS = {
|
|
|
182
184
|
showCopyButton: true,
|
|
183
185
|
breaks: true,
|
|
184
186
|
allowHtmlTags: false,
|
|
187
|
+
remoteImages: true,
|
|
185
188
|
};
|
|
186
189
|
/** 缓存 Marked 实例,避免重复创建 */
|
|
187
190
|
let cachedInstance = null;
|
|
@@ -190,7 +193,7 @@ let cachedOptionsKey = '';
|
|
|
190
193
|
* 获取配置签名,用于实例缓存比较
|
|
191
194
|
*/
|
|
192
195
|
function getOptionsKey(options) {
|
|
193
|
-
return `${options.enableHighlight}-${options.showCopyButton}-${options.breaks}-${options.allowHtmlTags}`;
|
|
196
|
+
return `${options.enableHighlight}-${options.showCopyButton}-${options.breaks}-${options.allowHtmlTags}-${options.remoteImages}`;
|
|
194
197
|
}
|
|
195
198
|
/**
|
|
196
199
|
* 将 Markdown 文本解析为 HTML
|
|
@@ -42,6 +42,7 @@ export declare function isExternalLinkHref(href: string): boolean;
|
|
|
42
42
|
/**
|
|
43
43
|
* 拒绝危险图片来源,保留允许的远程、相对或受控数据地址。
|
|
44
44
|
* @param src - 待验证的图片候选地址。
|
|
45
|
+
* @param remoteImages - 是否允许需要网络请求的图片地址。
|
|
45
46
|
* @returns 允许的图片地址,不安全或空输入返回空字符串。
|
|
46
47
|
*
|
|
47
48
|
* @example 模块内部上下文
|
|
@@ -49,11 +50,20 @@ export declare function isExternalLinkHref(href: string): boolean;
|
|
|
49
50
|
* const safe = sanitizeImageSrc('https://example.com/image.png')
|
|
50
51
|
* ```
|
|
51
52
|
*/
|
|
52
|
-
export declare function sanitizeImageSrc(src: string | null | undefined): string;
|
|
53
|
+
export declare function sanitizeImageSrc(src: string | null | undefined, remoteImages?: boolean): string;
|
|
54
|
+
/**
|
|
55
|
+
* 为被阻止的图片渲染已转义的替代文字。
|
|
56
|
+
* @example 模块内部上下文
|
|
57
|
+
* ```ts
|
|
58
|
+
* const placeholder = renderImagePlaceholder('图示')
|
|
59
|
+
* ```
|
|
60
|
+
*/
|
|
61
|
+
export declare function renderImagePlaceholder(text: string): string;
|
|
53
62
|
/**
|
|
54
63
|
* 消毒 Markdown 中嵌入的原始 HTML 片段。
|
|
55
64
|
* 只重建白名单标签,其余内容保持转义。
|
|
56
65
|
* @param fragment - 待消毒的 HTML 片段。
|
|
66
|
+
* @param remoteImages - 是否保留需要网络请求的图片地址。
|
|
57
67
|
* @returns 仅保留白名单标签和安全属性的 HTML。
|
|
58
68
|
*
|
|
59
69
|
* @example 模块内部上下文
|
|
@@ -61,4 +71,4 @@ export declare function sanitizeImageSrc(src: string | null | undefined): string
|
|
|
61
71
|
* const safe = sanitizeMarkdownHtml('<p onclick="alert(1)">正文</p>')
|
|
62
72
|
* ```
|
|
63
73
|
*/
|
|
64
|
-
export declare function sanitizeMarkdownHtml(fragment: string): string;
|
|
74
|
+
export declare function sanitizeMarkdownHtml(fragment: string, remoteImages?: boolean): string;
|