刘光辉
8 小时以前 cf11e63b659afcc9792ab3e395f1b45d844431a8
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
import type { DocumentField, FieldApplyResult, FieldChange } from '../domain/types';
import { applyFieldsCommand, cloneRepeatRowCommand, inspectFieldsCommand, removeRepeatRowCommand } from './commands';
import type { ApplyResult, AscGlobal, InspectResult, RepeatCloneResult } from './types';
 
export interface EditorControlEvent {
  InternalId?: unknown;
  Tag?: unknown;
}
 
interface LifecycleCallbacks {
  onControlChanged: (control: EditorControlEvent) => void;
  onControlFocused: (control: EditorControlEvent) => void;
  onReady: () => void;
  onThemeChanged: (theme: unknown) => void;
}
 
export interface OnlyOfficeBridge {
  applyFields(changes: FieldChange[]): Promise<FieldApplyResult[]>;
  appendRepeatRow(groupCode: string, rowId: string, beforeRowId?: string): Promise<string[]>;
  bindLifecycle(callbacks: LifecycleCallbacks): () => void;
  getRuntimeOptions(): unknown;
  inspectFields(): Promise<DocumentField[]>;
  removeRepeatRow(groupCode: string, rowId: string): Promise<string[]>;
  selectControl(internalId: string): Promise<void>;
  setFillOnlyMode(enabled: boolean): Promise<void>;
}
 
function parseResult<T>(raw: unknown): T {
  const result: unknown = typeof raw === 'string' ? JSON.parse(raw) : raw;
  if (typeof result !== 'object' || result === null || Array.isArray(result) || !('ok' in result) || typeof result.ok !== 'boolean') {
    throw new Error('编辑器命令返回无效结果');
  }
  return result as T;
}
 
export function createOnlyOfficeBridge(asc: AscGlobal): OnlyOfficeBridge {
  let fillOnlyMode = false;
  let documentCommandQueue: Promise<void> = Promise.resolve();
 
  function executeMethod(name: string, args: unknown[] = []): Promise<unknown> {
    return new Promise((resolve, reject) => {
      try {
        asc.plugin.executeMethod(name, args, resolve);
      } catch (error) {
        reject(error);
      }
    });
  }
 
  function enqueueDocumentCommand<T>(operation: () => Promise<T>): Promise<T> {
    const result = documentCommandQueue.then(operation, operation);
    documentCommandQueue = result.then(() => undefined, () => undefined);
    return result;
  }
 
  async function applyFillOnlyRestriction(): Promise<void> {
    try {
      await executeMethod('SetEditingRestrictions', ['forms']);
    } catch (error) {
      try {
        await executeMethod('SetEditingRestrictions', ['readOnly']);
      } catch {
        // Preserve the first failure; read-only is a best-effort fail-closed fallback.
      }
      throw error;
    }
  }
 
  function callCommandRaw<T>(command: () => string, scopeKey: string, payload: unknown): Promise<T> {
    return new Promise((resolve, reject) => {
      asc.scope[scopeKey] = payload;
      try {
        asc.plugin.callCommand(command, false, true, (raw) => {
          try { resolve(parseResult<T>(raw)); } catch (error) { reject(error); }
          finally { delete asc.scope[scopeKey]; }
        });
      } catch (error) {
        delete asc.scope[scopeKey];
        reject(error);
      }
    });
  }
 
  function callCommand<T>(command: () => string, scopeKey: string, payload: unknown): Promise<T> {
    if (!fillOnlyMode) return callCommandRaw<T>(command, scopeKey, payload);
    return enqueueDocumentCommand(async () => {
      await executeMethod('SetEditingRestrictions', ['none']);
      try {
        return await callCommandRaw<T>(command, scopeKey, payload);
      } finally {
        await applyFillOnlyRestriction();
      }
    });
  }
 
  async function inspectFields(): Promise<DocumentField[]> {
    const result = await callCommand<InspectResult>(inspectFieldsCommand, 'elnRecordFillInspect', {});
    if (!result.ok) throw new Error(result.error || '读取内容控件失败');
    return result.fields;
  }
 
  async function applyFields(changes: FieldChange[]): Promise<FieldApplyResult[]> {
    const result = await callCommand<ApplyResult>(applyFieldsCommand, 'elnRecordFillChanges', changes);
    if (!result.ok) throw new Error(result.error || '应用字段失败');
    return result.results;
  }
 
  async function appendRepeatRow(groupCode: string, rowId: string, beforeRowId?: string): Promise<string[]> {
    const result = await callCommand<RepeatCloneResult>(cloneRepeatRowCommand, 'elnRecordFillRepeatRow', {
      ...(beforeRowId ? { beforeRowId } : {}), groupCode, rowId,
    });
    if (!result.ok || !Array.isArray(result.tags)) throw new Error(result.error || '新增文档重复行失败');
    return result.tags;
  }
 
  async function removeRepeatRow(groupCode: string, rowId: string): Promise<string[]> {
    const result = await callCommand<RepeatCloneResult>(removeRepeatRowCommand, 'elnRecordFillRepeatRow', { groupCode, rowId });
    if (!result.ok || !Array.isArray(result.tags)) throw new Error(result.error || '删除文档重复行失败');
    return result.tags;
  }
 
  async function selectControl(internalId: string): Promise<void> {
    if (!internalId) throw new Error('字段控件缺少内部 ID');
    if (await executeMethod('SelectContentControl', [internalId]) === false) {
      throw new Error('编辑器未能定位字段');
    }
  }
 
  function bindLifecycle(callbacks: LifecycleCallbacks): () => void {
    const originalInit = asc.plugin.init;
    const originalTheme = asc.plugin.onThemeChanged;
    const changeEvent = 'onChangeContentControl';
    const focusEvent = 'onFocusContentControl';
    const onControlChanged = (value: unknown) => callbacks.onControlChanged(
      typeof value === 'object' && value !== null ? value as EditorControlEvent : {},
    );
    const onControlFocused = (value: unknown) => callbacks.onControlFocused(
      typeof value === 'object' && value !== null ? value as EditorControlEvent : {},
    );
    let eventsAttached = false;
    const onReady = () => {
      if (!eventsAttached) {
        asc.plugin.attachEditorEvent?.(changeEvent, onControlChanged);
        asc.plugin.attachEditorEvent?.(focusEvent, onControlFocused);
        eventsAttached = true;
      }
      callbacks.onReady();
    };
    asc.plugin.init = onReady;
    asc.plugin.onThemeChanged = (theme) => { asc.plugin.onThemeChangedBase(theme); callbacks.onThemeChanged(theme); };
    return () => {
      if (asc.plugin.init === onReady) asc.plugin.init = originalInit;
      asc.plugin.onThemeChanged = originalTheme;
      if (eventsAttached) {
        asc.plugin.detachEditorEvent?.(changeEvent);
        asc.plugin.detachEditorEvent?.(focusEvent);
      }
    };
  }
 
  return {
    applyFields,
    appendRepeatRow,
    bindLifecycle,
    getRuntimeOptions: () => asc.plugin.info?.options,
    inspectFields,
    removeRepeatRow,
    selectControl,
    setFillOnlyMode: (enabled) => enqueueDocumentCommand(async () => {
      fillOnlyMode = enabled;
      if (enabled) await applyFillOnlyRestriction();
      else await executeMethod('SetEditingRestrictions', ['none']);
    }),
  };
}