1/*
2 * Copyright (c) 2022-2023 Shenzhen Kaihong Digital Industry Development Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16const { MockMessage } = require('./mock');
17const { NapiLog } = require('./../hcs/NapiLog');
18
19class XMessage {
20  constructor() {
21    this.messageType = XMessage.TYPE_NONE;
22    try {
23      this.vscode = acquireVsCodeApi();
24      window.addEventListener('message', this.onRecv);
25      this.messageType = XMessage.TYPE_VSCODE;
26    } catch (err) {
27      NapiLog.logError('Error:' + err);
28    }
29    this.callbackFunc = null;
30    NapiLog.logInfo('Init XMessage : ' + this.messageType);
31  }
32  registRecvCallback(func) {
33    this.callbackFunc = func;
34  }
35  onRecv(event) {
36    if (XMessage.gi().callbackFunc !== null) {
37      XMessage.gi().callbackFunc(event.data.type, event.data.data);
38    }
39  }
40  send(msgtype, msgdata) {
41    if (this.messageType === XMessage.TYPE_VSCODE) {
42      this.vscode.postMessage({
43        type: msgtype,
44        data: msgdata,
45      });
46    } else if (this.messageType === XMessage.TYPE_NONE) {
47      MockMessage.gi().processMessage({
48        type: msgtype,
49        data: msgdata,
50      });
51    }
52  }
53}
54
55XMessage.TYPE_NONE = 0;
56XMessage.TYPE_VSCODE = 1;
57
58XMessage.pinstance_ = null;
59XMessage.gi = function () {
60  if (XMessage.pinstance_ === null) {
61    XMessage.pinstance_ = new XMessage();
62  }
63  return XMessage.pinstance_;
64};
65
66module.exports = {
67  XMessage,
68};
69