刘光辉
13 小时以前 0dfe84494048ce27ba8449831782128412d3eb13
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
import { describe, expect, it } from 'vitest';
 
import { disableTrackRevisionsCommand, insertTypedControlCommand, listContentControlsCommand, writeTextDefaultCommand } from '../../src/onlyoffice/commands';
import { installOnlyOfficeGlobals, makeApiFixture, makeInsertSpec, type FixtureApi, type InsertSpec, type TextDefaultSpec } from '../fixtures/onlyoffice';
 
interface CommandResult {
  controlType?: string;
  controls?: Array<{ Alias: string; ControlType: string; InternalId: string; Tag: string }>;
  error?: string;
  ok: boolean;
}
 
function parseResult(value: string): CommandResult {
  return JSON.parse(value) as CommandResult;
}
 
function setFixtureInsertScope(Api: FixtureApi, overrides: Partial<InsertSpec> & Pick<InsertSpec, 'controlType'>): void {
  installOnlyOfficeGlobals(Api, {
    elnTemplateInsert: makeInsertSpec(overrides),
  });
}
 
function setTextDefaultScope(Api: FixtureApi, spec: TextDefaultSpec): void {
  installOnlyOfficeGlobals(Api, { elnTemplateTextDefault: spec });
}
 
describe('insertTypedControlCommand', () => {
  it('使用显示值、业务值和默认项创建下拉控件', () => {
    const fixture = makeApiFixture();
    const options = [
      { display: '合格', value: 'pass' },
      { display: '不合格', value: 'fail' },
    ];
    setFixtureInsertScope(fixture.Api, { controlType: 'dropdown', options, selectedIndex: 0 });
 
    const result = parseResult(insertTypedControlCommand());
 
    expect(result).toEqual({ ok: true, controlType: 'dropdown' });
    expect(fixture.calls.combo).toEqual([[options, 0]]);
    expect(fixture.calls.inserted[0]).toMatchObject({ block: false, replaceSelection: true });
    expect(fixture.calls.inserted[0]?.control.tag).toBe('eln.field.result');
    expect(fixture.calls.inserted[0]?.control.lock).toBe('unlocked');
  });
 
  it('使用配置的默认状态创建复选框且不写占位文本', () => {
    const fixture = makeApiFixture();
    setFixtureInsertScope(fixture.Api, { controlType: 'checkbox', defaultChecked: true });
 
    const result = parseResult(insertTypedControlCommand());
 
    expect(result.ok).toBe(true);
    expect(fixture.calls.checkbox).toEqual([{ checked: true, checkedSymbol: 0x2611, uncheckedSymbol: 0x2610 }]);
    expect(fixture.calls.inserted[0]?.control.placeholder).toBeUndefined();
  });
 
  it('使用本地年月日创建日期默认值', () => {
    const fixture = makeApiFixture();
    setFixtureInsertScope(fixture.Api, { controlType: 'date', defaultValue: '2026-08-01' });
 
    const result = parseResult(insertTypedControlCommand());
 
    expect(result.ok).toBe(true);
    expect(fixture.calls.dateProperties).toEqual({ format: 'yyyy-MM-dd', lang: 'zh-CN' });
    expect(fixture.calls.date[0]?.getFullYear()).toBe(2026);
    expect(fixture.calls.date[0]?.getMonth()).toBe(7);
    expect(fixture.calls.date[0]?.getDate()).toBe(1);
  });
 
  it('把多行默认值拆成独立段落并作为块级内容插入', () => {
    const fixture = makeApiFixture();
    setFixtureInsertScope(fixture.Api, {
      controlType: 'multiline',
      tag: 'eln.field.note',
      alias: '备注',
      defaultValue: '第一行\n第二行',
      placeholder: '请输入备注',
    });
 
    const result = parseResult(insertTypedControlCommand());
 
    expect(result.ok).toBe(true);
    expect(fixture.calls.paragraphTexts).toEqual(['第一行', '第二行']);
    expect(fixture.calls.inserted[0]).toMatchObject({ block: true, replaceSelection: false });
    expect(fixture.calls.inserted[0]?.control.elements).toHaveLength(2);
  });
 
  it('无默认值时设置占位文本', () => {
    const fixture = makeApiFixture();
    setFixtureInsertScope(fixture.Api, { controlType: 'date', defaultValue: '', placeholder: '请选择日期' });
 
    const result = parseResult(insertTypedControlCommand());
 
    expect(result.ok).toBe(true);
    expect(fixture.calls.inserted[0]?.control.placeholder).toBe('请选择日期');
  });
 
  it('构造器缺失时报告不支持且不插入', () => {
    const fixture = makeApiFixture();
    delete fixture.Api.CreateDatePickerContentControl;
    setFixtureInsertScope(fixture.Api, { controlType: 'date' });
 
    const result = parseResult(insertTypedControlCommand());
 
    expect(result.ok).toBe(false);
    expect(result.error).toMatch(/不支持日期控件/);
    expect(fixture.calls.inserted).toHaveLength(0);
  });
 
  it('关键控件 setter 返回 false 时拒绝插入', () => {
    const fixture = makeApiFixture();
    const control = fixture.makeControl('date');
    control.SetTag = () => false;
    fixture.Api.CreateDatePickerContentControl = () => control;
    setFixtureInsertScope(fixture.Api, { controlType: 'date' });
 
    const result = parseResult(insertTypedControlCommand());
 
    expect(result.ok).toBe(false);
    expect(result.error).toMatch(/Tag/);
    expect(fixture.calls.inserted).toHaveLength(0);
  });
 
  it.each([
    {
      type: 'date' as const,
      defaultValue: '2026-08-01',
      patch: (Api: FixtureApi, control: ReturnType<ReturnType<typeof makeApiFixture>['makeControl']>) => {
        control.SetDate = () => false;
        Api.CreateDatePickerContentControl = () => control;
      },
    },
    {
      type: 'multiline' as const,
      defaultValue: '第一行\n第二行',
      patch: (Api: FixtureApi, control: ReturnType<ReturnType<typeof makeApiFixture>['makeControl']>) => {
        control.RemoveAllElements = () => false;
        Api.CreateBlockLvlSdt = () => control;
      },
    },
    {
      type: 'multiline' as const,
      defaultValue: '第一行\n第二行',
      patch: (Api: FixtureApi, control: ReturnType<ReturnType<typeof makeApiFixture>['makeControl']>) => {
        control.AddElement = () => false;
        Api.CreateBlockLvlSdt = () => control;
      },
    },
  ])('$type 默认值写入返回 false 时拒绝插入', ({ type, defaultValue, patch }) => {
    const fixture = makeApiFixture();
    const control = fixture.makeControl(type);
    patch(fixture.Api, control);
    setFixtureInsertScope(fixture.Api, { controlType: type, defaultValue });
 
    const result = parseResult(insertTypedControlCommand());
 
    expect(result.ok).toBe(false);
    expect(result.error).toMatch(/失败/);
    expect(fixture.calls.inserted).toHaveLength(0);
  });
 
  it.each(['SetPlaceholderText', 'SetColor'] as const)('配置相应值时要求 %s API 存在', (missingMethod) => {
    const fixture = makeApiFixture();
    const control = fixture.makeControl('date');
    delete control[missingMethod];
    fixture.Api.CreateDatePickerContentControl = () => control;
    setFixtureInsertScope(fixture.Api, { controlType: 'date', defaultValue: '' });
 
    const result = parseResult(insertTypedControlCommand());
 
    expect(result.ok).toBe(false);
    expect(result.error).toMatch(/不支持/);
    expect(fixture.calls.inserted).toHaveLength(0);
  });
 
  it('文档 InsertContent 返回 false 时报告失败', () => {
    const fixture = makeApiFixture();
    fixture.document.InsertContent = () => false;
    setFixtureInsertScope(fixture.Api, { controlType: 'checkbox' });
 
    const result = parseResult(insertTypedControlCommand());
 
    expect(result.ok).toBe(false);
    expect(result.error).toMatch(/插入/);
  });
});
 
describe('disableTrackRevisionsCommand', () => {
  it('关闭文档内部的修订跟踪', () => {
    const fixture = makeApiFixture();
    let enabled: boolean | undefined;
    fixture.document.SetTrackRevisions = (value) => {
      enabled = value;
      return true;
    };
    installOnlyOfficeGlobals(fixture.Api, { elnTemplateReview: {} });
 
    expect(parseResult(disableTrackRevisionsCommand())).toEqual({ ok: true });
    expect(enabled).toBe(false);
  });
});
 
describe('listContentControlsCommand', () => {
  it('回读内容控件属性并识别五种具体类型', () => {
    const fixture = makeApiFixture();
    const definitions = [
      { alias: '文本', id: 'text-1', tag: 'eln.field.text', type: 'text' },
      { alias: '下拉', id: 'dropdown-1', tag: 'eln.field.dropdown', type: 'dropdown' },
      { alias: '复选', id: 'checkbox-1', tag: 'eln.field.checkbox', type: 'checkbox' },
      { alias: '日期', id: 'date-1', tag: 'eln.field.date', type: 'date' },
      { alias: '多行', id: 'multiline-1', tag: 'eln.field.multiline', type: 'multiline' },
    ] as const;
 
    fixture.document.controls = definitions.map(({ alias, id, tag, type }) =>
      Object.assign(fixture.makeControl(type, tag), {
        GetAlias: () => alias,
        GetInternalId: () => id,
        IsBlockLevel: () => type === 'multiline',
        IsCheckBox: () => type === 'checkbox',
        IsComboBox: () => type === 'dropdown',
        IsDatePicker: () => type === 'date',
        IsDropDownList: () => false,
      }),
    );
    installOnlyOfficeGlobals(fixture.Api, { elnTemplateList: {} });
 
    expect(parseResult(listContentControlsCommand())).toEqual({
      ok: true,
      controls: [
        { Alias: '文本', ControlType: 'text', InternalId: 'text-1', Tag: 'eln.field.text' },
        { Alias: '下拉', ControlType: 'dropdown', InternalId: 'dropdown-1', Tag: 'eln.field.dropdown' },
        { Alias: '复选', ControlType: 'checkbox', InternalId: 'checkbox-1', Tag: 'eln.field.checkbox' },
        { Alias: '日期', ControlType: 'date', InternalId: 'date-1', Tag: 'eln.field.date' },
        { Alias: '多行', ControlType: 'multiline', InternalId: 'multiline-1', Tag: 'eln.field.multiline' },
      ],
    });
  });
 
  it('多个类型特征同时存在时按复选、下拉、日期、多行的顺序判定', () => {
    const fixture = makeApiFixture();
    fixture.document.controls = [
      Object.assign(fixture.makeControl('ambiguous', 'eln.field.ambiguous'), {
        GetAlias: () => '歧义字段',
        GetInternalId: () => 'ambiguous-1',
        IsBlockLevel: () => true,
        IsCheckBox: () => true,
        IsComboBox: () => true,
        IsDatePicker: () => true,
        IsDropDownList: () => true,
      }),
    ];
    installOnlyOfficeGlobals(fixture.Api, { elnTemplateList: {} });
 
    expect(parseResult(listContentControlsCommand()).controls?.[0]?.ControlType).toBe('checkbox');
  });
});
 
describe('writeTextDefaultCommand', () => {
  it('按唯一 Tag 成功写入文本默认值', () => {
    const fixture = makeApiFixture();
    const target = fixture.makeControl('text', 'eln.field.sample_id');
    fixture.document.controls.push(target);
    setTextDefaultScope(fixture.Api, { tag: 'eln.field.sample_id', value: 'S-001' });
 
    const result = parseResult(writeTextDefaultCommand());
 
    expect(result.ok).toBe(true);
    expect(target.elements).toHaveLength(1);
    expect(target.elements[0]?.text).toBe('S-001');
  });
 
  it.each(['AddText', 'AddElement'] as const)('%s 返回 false 时拒绝文本默认值写入', (failedStep) => {
    const fixture = makeApiFixture();
    const target = fixture.makeControl('text', 'eln.field.sample_id');
    fixture.document.controls.push(target);
 
    if (failedStep === 'AddText') {
      fixture.Api.CreateRun = () => ({ text: '', AddText: () => false });
    } else {
      target.AddElement = () => false;
    }
    setTextDefaultScope(fixture.Api, { tag: 'eln.field.sample_id', value: 'S-001' });
 
    const result = parseResult(writeTextDefaultCommand());
 
    expect(result.ok).toBe(false);
    expect(result.error).toMatch(/失败/);
  });
 
  it('清空返回 false 但最终回读一致时仍接受写入', () => {
    const fixture = makeApiFixture();
    const target = fixture.makeControl('text', 'eln.field.sample_id');
    target.RemoveAllElements = () => false;
    fixture.document.controls.push(target);
    setTextDefaultScope(fixture.Api, { tag: 'eln.field.sample_id', value: 'S-001' });
 
    const result = parseResult(writeTextDefaultCommand());
 
    expect(result.ok).toBe(true);
    expect(target.GetRange?.().GetText?.()).toBe('S-001');
  });
 
  it('文本默认值回读不一致时拒绝写入', () => {
    const fixture = makeApiFixture();
    const target = fixture.makeControl('text', 'eln.field.sample_id');
    target.GetRange = () => ({ GetText: () => '旧值' });
    fixture.document.controls.push(target);
    setTextDefaultScope(fixture.Api, { tag: 'eln.field.sample_id', value: 'S-001' });
 
    const result = parseResult(writeTextDefaultCommand());
 
    expect(result.ok).toBe(false);
    expect(result.error).toMatch(/回读/);
  });
 
  it.each([0, 2])('目标 Tag 匹配数量为 %i 时拒绝写入', (targetCount) => {
    const fixture = makeApiFixture();
    for (let index = 0; index < targetCount; index += 1) {
      fixture.document.controls.push(fixture.makeControl('text', 'eln.field.sample_id'));
    }
    setTextDefaultScope(fixture.Api, { tag: 'eln.field.sample_id', value: 'S-001' });
 
    const result = parseResult(writeTextDefaultCommand());
 
    expect(result.ok).toBe(false);
    expect(result.error).toMatch(/唯一控件/);
  });
});
 
describe('command 自包含契约', () => {
  it.each([
    ['disableTrackRevisionsCommand', disableTrackRevisionsCommand],
    ['insertTypedControlCommand', insertTypedControlCommand],
    ['listContentControlsCommand', listContentControlsCommand],
    ['writeTextDefaultCommand', writeTextDefaultCommand],
  ] as const)('%s 源码只依赖 Asc、Api 和标准全局', (_name, command) => {
    const source = command.toString();
 
    expect(source).not.toMatch(/\b(?:import|require|window|document)\b/);
    expect(source).toContain('Asc.scope');
    expect(source).toContain('Api');
  });
 
  it('insertTypedControlCommand 的源码可在隔离函数中执行', () => {
    const fixture = makeApiFixture();
    const execute = new Function('Asc', 'Api', `return (${insertTypedControlCommand.toString()})()`) as (
      Asc: { scope: { elnTemplateInsert: InsertSpec } },
      Api: FixtureApi,
    ) => string;
 
    const result = parseResult(execute({ scope: { elnTemplateInsert: makeInsertSpec({ controlType: 'checkbox', defaultChecked: true }) } }, fixture.Api));
 
    expect(result).toEqual({ ok: true, controlType: 'checkbox' });
    expect(fixture.calls.inserted).toHaveLength(1);
  });
 
  it('listContentControlsCommand 的源码可在隔离函数中执行', () => {
    const fixture = makeApiFixture();
    fixture.document.controls = [
      Object.assign(fixture.makeControl('date', 'eln.field.date'), {
        GetAlias: () => '日期',
        GetInternalId: () => 'date-1',
        IsDatePicker: () => true,
      }),
    ];
    const execute = new Function('Asc', 'Api', `return (${listContentControlsCommand.toString()})()`) as (
      Asc: { scope: { elnTemplateList: Record<string, never> } },
      Api: FixtureApi,
    ) => string;
 
    expect(parseResult(execute({ scope: { elnTemplateList: {} } }, fixture.Api))).toEqual({
      ok: true,
      controls: [{ Alias: '日期', ControlType: 'date', InternalId: 'date-1', Tag: 'eln.field.date' }],
    });
  });
 
  it('writeTextDefaultCommand 的源码可在隔离函数中执行', () => {
    const fixture = makeApiFixture();
    fixture.document.controls.push(fixture.makeControl('text', 'eln.field.sample_id'));
    const execute = new Function('Asc', 'Api', `return (${writeTextDefaultCommand.toString()})()`) as (
      Asc: { scope: { elnTemplateTextDefault: TextDefaultSpec } },
      Api: FixtureApi,
    ) => string;
 
    const result = parseResult(execute({ scope: { elnTemplateTextDefault: { tag: 'eln.field.sample_id', value: 'S-001' } } }, fixture.Api));
 
    expect(result).toEqual({ ok: true });
  });
});