index.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var latestNodeId = 1;
  4. function TextNode (text) {
  5. this.instanceId = '';
  6. this.nodeId = latestNodeId++;
  7. this.parentNode = null;
  8. this.nodeType = 3;
  9. this.text = text;
  10. }
  11. // this will be preserved during build
  12. var VueFactory = require('./factory');
  13. var instances = {};
  14. var modules = {};
  15. var components = {};
  16. var renderer = {
  17. TextNode: TextNode,
  18. instances: instances,
  19. modules: modules,
  20. components: components
  21. };
  22. /**
  23. * Prepare framework config, basically about the virtual-DOM and JS bridge.
  24. * @param {object} cfg
  25. */
  26. function init (cfg) {
  27. renderer.Document = cfg.Document;
  28. renderer.Element = cfg.Element;
  29. renderer.Comment = cfg.Comment;
  30. renderer.sendTasks = cfg.sendTasks;
  31. }
  32. /**
  33. * Reset framework config and clear all registrations.
  34. */
  35. function reset () {
  36. clear(instances);
  37. clear(modules);
  38. clear(components);
  39. delete renderer.Document;
  40. delete renderer.Element;
  41. delete renderer.Comment;
  42. delete renderer.sendTasks;
  43. }
  44. /**
  45. * Delete all keys of an object.
  46. * @param {object} obj
  47. */
  48. function clear (obj) {
  49. for (var key in obj) {
  50. delete obj[key];
  51. }
  52. }
  53. /**
  54. * Create an instance with id, code, config and external data.
  55. * @param {string} instanceId
  56. * @param {string} appCode
  57. * @param {object} config
  58. * @param {object} data
  59. * @param {object} env { info, config, services }
  60. */
  61. function createInstance (
  62. instanceId,
  63. appCode,
  64. config,
  65. data,
  66. env
  67. ) {
  68. if ( appCode === void 0 ) appCode = '';
  69. if ( config === void 0 ) config = {};
  70. if ( env === void 0 ) env = {};
  71. // Virtual-DOM object.
  72. var document = new renderer.Document(instanceId, config.bundleUrl);
  73. // All function/callback of parameters before sent to native
  74. // will be converted as an id. So `callbacks` is used to store
  75. // these real functions. When a callback invoked and won't be
  76. // called again, it should be removed from here automatically.
  77. var callbacks = [];
  78. // The latest callback id, incremental.
  79. var callbackId = 1;
  80. var instance = instances[instanceId] = {
  81. instanceId: instanceId, config: config, data: data,
  82. document: document, callbacks: callbacks, callbackId: callbackId
  83. };
  84. // Prepare native module getter and HTML5 Timer APIs.
  85. var moduleGetter = genModuleGetter(instanceId);
  86. var timerAPIs = getInstanceTimer(instanceId, moduleGetter);
  87. // Prepare `weex` instance variable.
  88. var weexInstanceVar = {
  89. config: config,
  90. document: document,
  91. requireModule: moduleGetter
  92. };
  93. Object.freeze(weexInstanceVar);
  94. // Each instance has a independent `Vue` module instance
  95. var Vue = instance.Vue = createVueModuleInstance(instanceId, moduleGetter);
  96. // The function which create a closure the JS Bundle will run in.
  97. // It will declare some instance variables like `Vue`, HTML5 Timer APIs etc.
  98. var instanceVars = Object.assign({
  99. Vue: Vue,
  100. weex: weexInstanceVar,
  101. // deprecated
  102. __weex_require_module__: weexInstanceVar.requireModule // eslint-disable-line
  103. }, timerAPIs);
  104. callFunction(instanceVars, appCode);
  105. // Send `createFinish` signal to native.
  106. renderer.sendTasks(instanceId + '', [{ module: 'dom', method: 'createFinish', args: [] }], -1);
  107. }
  108. /**
  109. * Destroy an instance with id. It will make sure all memory of
  110. * this instance released and no more leaks.
  111. * @param {string} instanceId
  112. */
  113. function destroyInstance (instanceId) {
  114. var instance = instances[instanceId];
  115. if (instance && instance.app instanceof instance.Vue) {
  116. instance.app.$destroy();
  117. }
  118. delete instances[instanceId];
  119. }
  120. /**
  121. * Refresh an instance with id and new top-level component data.
  122. * It will use `Vue.set` on all keys of the new data. So it's better
  123. * define all possible meaningful keys when instance created.
  124. * @param {string} instanceId
  125. * @param {object} data
  126. */
  127. function refreshInstance (instanceId, data) {
  128. var instance = instances[instanceId];
  129. if (!instance || !(instance.app instanceof instance.Vue)) {
  130. return new Error(("refreshInstance: instance " + instanceId + " not found!"))
  131. }
  132. for (var key in data) {
  133. instance.Vue.set(instance.app, key, data[key]);
  134. }
  135. // Finally `refreshFinish` signal needed.
  136. renderer.sendTasks(instanceId + '', [{ module: 'dom', method: 'refreshFinish', args: [] }], -1);
  137. }
  138. /**
  139. * Get the JSON object of the root element.
  140. * @param {string} instanceId
  141. */
  142. function getRoot (instanceId) {
  143. var instance = instances[instanceId];
  144. if (!instance || !(instance.app instanceof instance.Vue)) {
  145. return new Error(("getRoot: instance " + instanceId + " not found!"))
  146. }
  147. return instance.app.$el.toJSON()
  148. }
  149. /**
  150. * Receive tasks from native. Generally there are two types of tasks:
  151. * 1. `fireEvent`: an device actions or user actions from native.
  152. * 2. `callback`: invoke function which sent to native as a parameter before.
  153. * @param {string} instanceId
  154. * @param {array} tasks
  155. */
  156. function receiveTasks (instanceId, tasks) {
  157. var instance = instances[instanceId];
  158. if (!instance || !(instance.app instanceof instance.Vue)) {
  159. return new Error(("receiveTasks: instance " + instanceId + " not found!"))
  160. }
  161. var callbacks = instance.callbacks;
  162. var document = instance.document;
  163. tasks.forEach(function (task) {
  164. // `fireEvent` case: find the event target and fire.
  165. if (task.method === 'fireEvent') {
  166. var ref = task.args;
  167. var nodeId = ref[0];
  168. var type = ref[1];
  169. var e = ref[2];
  170. var domChanges = ref[3];
  171. var el = document.getRef(nodeId);
  172. document.fireEvent(el, type, e, domChanges);
  173. }
  174. // `callback` case: find the callback by id and call it.
  175. if (task.method === 'callback') {
  176. var ref$1 = task.args;
  177. var callbackId = ref$1[0];
  178. var data = ref$1[1];
  179. var ifKeepAlive = ref$1[2];
  180. var callback = callbacks[callbackId];
  181. if (typeof callback === 'function') {
  182. callback(data);
  183. // Remove the callback from `callbacks` if it won't called again.
  184. if (typeof ifKeepAlive === 'undefined' || ifKeepAlive === false) {
  185. callbacks[callbackId] = undefined;
  186. }
  187. }
  188. }
  189. });
  190. // Finally `updateFinish` signal needed.
  191. renderer.sendTasks(instanceId + '', [{ module: 'dom', method: 'updateFinish', args: [] }], -1);
  192. }
  193. /**
  194. * Register native modules information.
  195. * @param {object} newModules
  196. */
  197. function registerModules (newModules) {
  198. var loop = function ( name ) {
  199. if (!modules[name]) {
  200. modules[name] = {};
  201. }
  202. newModules[name].forEach(function (method) {
  203. if (typeof method === 'string') {
  204. modules[name][method] = true;
  205. } else {
  206. modules[name][method.name] = method.args;
  207. }
  208. });
  209. };
  210. for (var name in newModules) loop( name );
  211. }
  212. /**
  213. * Register native components information.
  214. * @param {array} newComponents
  215. */
  216. function registerComponents (newComponents) {
  217. if (Array.isArray(newComponents)) {
  218. newComponents.forEach(function (component) {
  219. if (!component) {
  220. return
  221. }
  222. if (typeof component === 'string') {
  223. components[component] = true;
  224. } else if (typeof component === 'object' && typeof component.type === 'string') {
  225. components[component.type] = component;
  226. }
  227. });
  228. }
  229. }
  230. /**
  231. * Create a fresh instance of Vue for each Weex instance.
  232. */
  233. function createVueModuleInstance (instanceId, moduleGetter) {
  234. var exports = {};
  235. VueFactory(exports, renderer);
  236. var Vue = exports.Vue;
  237. var instance = instances[instanceId];
  238. // patch reserved tag detection to account for dynamically registered
  239. // components
  240. var isReservedTag = Vue.config.isReservedTag || (function () { return false; });
  241. Vue.config.isReservedTag = function (name) {
  242. return components[name] || isReservedTag(name)
  243. };
  244. // expose weex-specific info
  245. Vue.prototype.$instanceId = instanceId;
  246. Vue.prototype.$document = instance.document;
  247. // expose weex native module getter on subVue prototype so that
  248. // vdom runtime modules can access native modules via vnode.context
  249. Vue.prototype.$requireWeexModule = moduleGetter;
  250. // Hack `Vue` behavior to handle instance information and data
  251. // before root component created.
  252. Vue.mixin({
  253. beforeCreate: function beforeCreate () {
  254. var options = this.$options;
  255. // root component (vm)
  256. if (options.el) {
  257. // set external data of instance
  258. var dataOption = options.data;
  259. var internalData = (typeof dataOption === 'function' ? dataOption() : dataOption) || {};
  260. options.data = Object.assign(internalData, instance.data);
  261. // record instance by id
  262. instance.app = this;
  263. }
  264. }
  265. });
  266. /**
  267. * @deprecated Just instance variable `weex.config`
  268. * Get instance config.
  269. * @return {object}
  270. */
  271. Vue.prototype.$getConfig = function () {
  272. if (instance.app instanceof Vue) {
  273. return instance.config
  274. }
  275. };
  276. return Vue
  277. }
  278. /**
  279. * Generate native module getter. Each native module has several
  280. * methods to call. And all the behaviors is instance-related. So
  281. * this getter will return a set of methods which additionally
  282. * send current instance id to native when called. Also the args
  283. * will be normalized into "safe" value. For example function arg
  284. * will be converted into a callback id.
  285. * @param {string} instanceId
  286. * @return {function}
  287. */
  288. function genModuleGetter (instanceId) {
  289. var instance = instances[instanceId];
  290. return function (name) {
  291. var nativeModule = modules[name] || [];
  292. var output = {};
  293. var loop = function ( methodName ) {
  294. output[methodName] = function () {
  295. var args = [], len = arguments.length;
  296. while ( len-- ) args[ len ] = arguments[ len ];
  297. var finalArgs = args.map(function (value) {
  298. return normalize(value, instance)
  299. });
  300. renderer.sendTasks(instanceId + '', [{ module: name, method: methodName, args: finalArgs }], -1);
  301. };
  302. };
  303. for (var methodName in nativeModule) loop( methodName );
  304. return output
  305. }
  306. }
  307. /**
  308. * Generate HTML5 Timer APIs. An important point is that the callback
  309. * will be converted into callback id when sent to native. So the
  310. * framework can make sure no side effect of the callback happened after
  311. * an instance destroyed.
  312. * @param {[type]} instanceId [description]
  313. * @param {[type]} moduleGetter [description]
  314. * @return {[type]} [description]
  315. */
  316. function getInstanceTimer (instanceId, moduleGetter) {
  317. var instance = instances[instanceId];
  318. var timer = moduleGetter('timer');
  319. var timerAPIs = {
  320. setTimeout: function () {
  321. var args = [], len = arguments.length;
  322. while ( len-- ) args[ len ] = arguments[ len ];
  323. var handler = function () {
  324. args[0].apply(args, args.slice(2));
  325. };
  326. timer.setTimeout(handler, args[1]);
  327. return instance.callbackId.toString()
  328. },
  329. setInterval: function () {
  330. var args = [], len = arguments.length;
  331. while ( len-- ) args[ len ] = arguments[ len ];
  332. var handler = function () {
  333. args[0].apply(args, args.slice(2));
  334. };
  335. timer.setInterval(handler, args[1]);
  336. return instance.callbackId.toString()
  337. },
  338. clearTimeout: function (n) {
  339. timer.clearTimeout(n);
  340. },
  341. clearInterval: function (n) {
  342. timer.clearInterval(n);
  343. }
  344. };
  345. return timerAPIs
  346. }
  347. /**
  348. * Call a new function body with some global objects.
  349. * @param {object} globalObjects
  350. * @param {string} code
  351. * @return {any}
  352. */
  353. function callFunction (globalObjects, body) {
  354. var globalKeys = [];
  355. var globalValues = [];
  356. for (var key in globalObjects) {
  357. globalKeys.push(key);
  358. globalValues.push(globalObjects[key]);
  359. }
  360. globalKeys.push(body);
  361. var result = new (Function.prototype.bind.apply( Function, [ null ].concat( globalKeys) ));
  362. return result.apply(void 0, globalValues)
  363. }
  364. /**
  365. * Convert all type of values into "safe" format to send to native.
  366. * 1. A `function` will be converted into callback id.
  367. * 2. An `Element` object will be converted into `ref`.
  368. * The `instance` param is used to generate callback id and store
  369. * function if necessary.
  370. * @param {any} v
  371. * @param {object} instance
  372. * @return {any}
  373. */
  374. function normalize (v, instance) {
  375. var type = typof(v);
  376. switch (type) {
  377. case 'undefined':
  378. case 'null':
  379. return ''
  380. case 'regexp':
  381. return v.toString()
  382. case 'date':
  383. return v.toISOString()
  384. case 'number':
  385. case 'string':
  386. case 'boolean':
  387. case 'array':
  388. case 'object':
  389. if (v instanceof renderer.Element) {
  390. return v.ref
  391. }
  392. return v
  393. case 'function':
  394. instance.callbacks[++instance.callbackId] = v;
  395. return instance.callbackId.toString()
  396. default:
  397. return JSON.stringify(v)
  398. }
  399. }
  400. /**
  401. * Get the exact type of an object by `toString()`. For example call
  402. * `toString()` on an array will be returned `[object Array]`.
  403. * @param {any} v
  404. * @return {string}
  405. */
  406. function typof (v) {
  407. var s = Object.prototype.toString.call(v);
  408. return s.substring(8, s.length - 1).toLowerCase()
  409. }
  410. exports.init = init;
  411. exports.reset = reset;
  412. exports.createInstance = createInstance;
  413. exports.destroyInstance = destroyInstance;
  414. exports.refreshInstance = refreshInstance;
  415. exports.getRoot = getRoot;
  416. exports.receiveTasks = receiveTasks;
  417. exports.registerModules = registerModules;
  418. exports.registerComponents = registerComponents;