framework.js 12 KB

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