WazeWrap Beta

A base library for WME script writers

当前为 2016-12-01 提交的版本,查看 最新版本

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.gf.qytechs.cn/scripts/24870/160961/WazeWrap%20Beta.js

  1. // ==UserScript==
  2. // @name WazeWrap Beta
  3. // @namespace https://gf.qytechs.cn/users/30701-justins83-waze
  4. // @version 0.1.8d
  5. // @description A base library for WME script writers
  6. // @author JustinS83/MapOMatic
  7. // @include https://beta.waze.com/*editor/*
  8. // @include https://www.waze.com/*editor/*
  9. // @exclude https://www.waze.com/*user/editor/*
  10. // @grant none
  11. // ==/UserScript==
  12.  
  13. /* global W */
  14. /* global WazeWrapBeta */
  15. var WazeWrapBeta = {};
  16.  
  17. (function() {
  18.  
  19. function bootstrap(tries) {
  20. tries = tries || 1;
  21. if (window.W &&
  22. window.W.map &&
  23. window.W.model &&
  24. window.W.loginManager &&
  25. $) {
  26. init();
  27. } else if (tries < 1000) {
  28. setTimeout(function () { bootstrap(tries++); }, 200);
  29. } else {
  30. console.log('WazeWrap failed to load');
  31. }
  32. }
  33.  
  34. bootstrap();
  35.  
  36. function init(){
  37. console.log("WazeWrapBeta initializing...");
  38. var oldLib = window.WazeWrap;
  39. var root = this;
  40.  
  41. WazeWrapBeta .Version = GM_info.script.version;
  42. WazeWrapBeta .isBetaEditor = /beta/.test(location.href);
  43.  
  44. SetUpRequire();
  45.  
  46. WazeWrapBeta .test = "test";
  47. WazeWrapBeta .Geometry = new Geometry;
  48. WazeWrapBeta .Model = new Model;
  49. WazeWrapBeta .Interface = new Interface;
  50. WazeWrapBeta .User = new User;
  51. WazeWrapBeta .Util = new Util;
  52. root.WazeWrapBeta = WazeWrapBeta ;
  53.  
  54. console.log('WazeWrapBeta Loaded');
  55. };
  56.  
  57.  
  58. function SetUpRequire(){
  59. if(this.isBetaEditor || typeof window.require !== "undefined")
  60. return;
  61.  
  62. console.log("Setting d2's require fix...");
  63.  
  64. // setup one global var and put all in
  65. var WMEAPI = {};
  66.  
  67. // detect URL of WME source code
  68. WMEAPI.scripts = document.getElementsByTagName('script');
  69. WMEAPI.url=null;
  70. for (i=0;i<WMEAPI.scripts.length;i++){
  71. if (WMEAPI.scripts[i].src.indexOf('/assets-editor/js/app')!=-1)
  72. {
  73. WMEAPI.url=WMEAPI.scripts[i].src;
  74. break;
  75. }
  76. }
  77. if (WMEAPI.url==null)
  78. throw new Error("WME Hack: can't detect WME main JS");
  79.  
  80.  
  81. // setup a fake require and require.define
  82. WMEAPI.require=function (e) {
  83. if (WMEAPI.require.define.modules.hasOwnProperty(e))
  84. return WMEAPI.require.define.modules[e];
  85. else
  86. console.error('Require failed on ' + e, WMEAPI.require.define.modules);
  87. return null;
  88. };
  89.  
  90. WMEAPI.require.define=function (m) {
  91. if (WMEAPI.require.define.hasOwnProperty('modules')==false)
  92. WMEAPI.require.define.modules={};
  93. for (var p in m){
  94. WMEAPI.require.define.modules[p]=m[p];
  95. }
  96. };
  97.  
  98. // save the original webpackJsonp function
  99. WMEAPI.tmp = window.webpackJsonp;
  100.  
  101. // taken from WME code: this function is a wrapper that setup the API and may call recursively other functions
  102. WMEAPI.t = function (n) {
  103. if (WMEAPI.s[n]) return WMEAPI.s[n].exports;
  104. var r = WMEAPI.s[n] = {
  105. exports: {},
  106. id: n,
  107. loaded: !1
  108. };
  109. return WMEAPI.e[n].call(r.exports, r, r.exports, WMEAPI.t), r.loaded = !0, r.exports;
  110. };
  111.  
  112. // e is a copy of all WME funcs because function t need to access to this list
  113. WMEAPI.e=[];
  114.  
  115. // the patch
  116. window.webpackJsonp = function(a, i) {
  117. // our API but we will use it only to build the require stuffs
  118. var api={};
  119. // taken from WME code. a is [1], so...
  120. for (var o, d, u = 0, l = []; u < a.length; u++) d = a[u], WMEAPI.r[d] && l.push.apply(l, WMEAPI.r[d]), WMEAPI.r[d] = 0;
  121. var unknownCount=0;
  122. var classname, funcStr;
  123. // copy i in e and keep a link from classname to index in e
  124. for (o in i){
  125. WMEAPI.e[o] = i[o];
  126. funcStr = i[o].toString();
  127. classname = funcStr.match(/CLASS_NAME:\"([^\"]*)\"/);
  128. if (classname){
  129. // keep the link.
  130. api[classname[1].replace(/\./g,'/').replace(/^W\//, 'Waze/')]={index: o, func: WMEAPI.e[o]};
  131. }
  132. else{
  133. api['Waze/Unknown/' + unknownCount]={index: o, func: WMEAPI.e[o]};
  134. unknownCount++;
  135. }
  136. }
  137. // taken from WME code: it calls the original webpackJsonp and do something else, but I don't really know what.
  138. // removed the call to the original webpackJsonp: still works...
  139. //for (tmp && tmp(a, i); l.length;) l.shift().call(null, t);
  140. for (; l.length;) l.shift().call(null, WMEAPI.t);
  141. WMEAPI.s[0] = 0;
  142. // run the first func of WME. This first func will call recusrsively all funcs needed to setup the API.
  143. // After this call, s will contain all instanciables classes.
  144. //var ret = WMEAPI.t(0);
  145. // now, build the requires thanks to the link we've built in var api.
  146. var module={};
  147. var apiFuncName;
  148. unknownCount=0;
  149. for (o in i){
  150. funcStr = i[o].toString();
  151. classname = funcStr.match(/CLASS_NAME:\"([^\"]*)\"/);
  152. if (classname){
  153. module={};
  154. apiFuncName = classname[1].replace(/\./g,'/').replace(/^W\//, 'Waze/');
  155. module[apiFuncName]=WMEAPI.t(api[apiFuncName].index);
  156. WMEAPI.require.define(module);
  157. }
  158. else{
  159. var matches = funcStr.match(/SEGMENT:"segment",/);
  160. if (matches){
  161. module={};
  162. apiFuncName='Waze/Model/ObjectType';
  163. module[apiFuncName]=WMEAPI.t(api['Waze/Unknown/' + unknownCount].index);
  164. WMEAPI.require.define(module);
  165. }
  166. unknownCount++;
  167. }
  168. }
  169.  
  170. // restore the original func
  171. window.webpackJsonp=WMEAPI.tmp;
  172.  
  173. // set the require public if needed
  174. // if so: others scripts must wait for the window.require to be available before using it.
  175. window.require = WMEAPI.require;
  176. // all available functions are in WMEAPI.require.define.modules
  177. // console.debug this variable to read it:
  178. // console.debug('Modules: ', WMEAPI.require.define.modules);
  179. // run your script here:
  180. // setTimeout(yourscript);
  181. // again taken from WME code. Not sure about what it does.
  182. //if (i[0]) return ret;
  183. };
  184.  
  185. // some kind of global vars and init
  186. WMEAPI.s = {};
  187. WMEAPI.r = {
  188. 0: 0
  189. };
  190.  
  191. // hacking finished
  192.  
  193. // load again WME through our patched func
  194. WMEAPI.WMEHACK_Injected_script = document.createElement("script");
  195. WMEAPI.WMEHACK_Injected_script.setAttribute("type", "application/javascript");
  196. WMEAPI.WMEHACK_Injected_script.src = WMEAPI.url;
  197. document.body.appendChild(WMEAPI.WMEHACK_Injected_script);
  198. console.log("d2 fix complete");
  199. }
  200.  
  201. function Geometry(){
  202. //var geometry = WazeWrap.Geometry;
  203.  
  204. //Converts to "normal" GPS coordinates
  205. this.ConvertTo4326 = function (long, lat){
  206. var projI=new OpenLayers.Projection("EPSG:900913");
  207. var projE=new OpenLayers.Projection("EPSG:4326");
  208. return (new OpenLayers.LonLat(long, lat)).transform(projI,projE);
  209. };
  210. this.ConvertTo900913 = function (long, lat){
  211. var projI=new OpenLayers.Projection("EPSG:900913");
  212. var projE=new OpenLayers.Projection("EPSG:4326");
  213. return (new OpenLayers.LonLat(long, lat)).transform(projE,projI);
  214. };
  215.  
  216. //Converts the Longitudinal offset to an offset in 4326 gps coordinates
  217. this.CalculateLongOffsetGPS = function(longMetersOffset, long, lat)
  218. {
  219. var R= 6378137; //Earth's radius
  220. var dLon = longMetersOffset / (R * Math.cos(Math.PI * lat / 180)); //offset in radians
  221. var lon0 = dLon * (180 / Math.PI); //offset degrees
  222.  
  223. return lon0;
  224. };
  225.  
  226. //Converts the Latitudinal offset to an offset in 4326 gps coordinates
  227. this.CalculateLatOffsetGPS = function(latMetersOffset, lat)
  228. {
  229. var R= 6378137; //Earth's radius
  230. var dLat = latMetersOffset/R;
  231. var lat0 = dLat * (180 /Math.PI); //offset degrees
  232.  
  233. return lat0;
  234. };
  235. /**
  236. * Checks if the given geometry is on screen
  237. * @function WazeWrap.Model.isGeometryInMapExtent
  238. * @param {OpenLayers.Geometry} Geometry to check if any part of is in the current viewport
  239. */
  240. this.isLonLatInMapExtent = function (lonLat) {
  241. 'use strict';
  242. return lonLat && W.map.getExtent().containsLonLat(lonLat);
  243. };
  244. /**
  245. * Checks if the given geometry is on screen
  246. * @function WazeWrap.Model.isGeometryInMapExtent
  247. * @param {OpenLayers.Geometry} Geometry to check if any part of is in the current viewport
  248. */
  249. this.isGeometryInMapExtent = function (geometry) {
  250. 'use strict';
  251. return geometry && geometry.getBounds &&
  252. W.map.getExtent().intersectsBounds(geometry.getBounds());
  253. };
  254. /**
  255. * Calculates the distance between two given points
  256. * @function WazeWrap.Model.calculateDistance
  257. * @param {OpenLayers.Geometry.Point} An array of OL.Geometry.Point with which to measure the total distance. A minimum of 2 points is needed.
  258. */
  259. this.calculateDistance = function(pointArray) {
  260. if(pointArray.length < 2)
  261. return 0;
  262.  
  263. var line = new OpenLayers.Geometry.LineString(pointArray);
  264. length = line.getGeodesicLength(W.map.getProjectionObject());
  265. return length; //multiply by 3.28084 to convert to feet
  266. };
  267. };
  268.  
  269. function Model(){
  270.  
  271. this.getPrimaryStreetID = function(segmentID){
  272. return W.model.segments.get(segmentID).attributes.primaryStreetID;
  273. };
  274.  
  275. this.getStreetName = function(primaryStreetID){
  276. return W.model.streets.get(PrimaryStreetID).name;
  277. };
  278.  
  279. this.getCityID = function(primaryStreetID){
  280. return W.model.streets.get(primaryStreetID).cityID;
  281. };
  282.  
  283. this.getCityName = function(primaryStreetID){
  284. return W.model.cities.get(this.getCityID(primaryStreetID)).attributes.Name;
  285. };
  286.  
  287. this.getStateName = function(primaryStreetID){
  288. return W.model.states.get(getStateID(primaryStreetID)).Name;
  289. };
  290.  
  291. this.getStateID = function(primaryStreetID){
  292. return W.model.cities.get(primaryStreetID).attributes.stateID;
  293. };
  294.  
  295. this.getCountryID = function(primaryStreetID){
  296. return W.model.cities.get(this.getCityID(primaryStreetID)).attributes.CountryID;
  297. };
  298.  
  299. this.getCountryName = function(primaryStreetID){
  300. return W.model.countries.get(getCountryID(primaryStreetID)).name;
  301. };
  302.  
  303. this.getCityNameFromSegmentObj = function(segObj){
  304. return this.getCityName(segObj.attributes.primaryStreetID);
  305. };
  306.  
  307. this.getStateNameFromSegmentObj = function(segObj){
  308. return this.getStateName(segObj.attributes.primaryStreetID);
  309. };
  310.  
  311. //returns an array of segmentIDs for all segments that are part of the same roundabout as the passed segment
  312. this.getAllRoundaboutSegmentsFromObj = function(segObj){
  313. if(segObj.model.attributes.junctionID === null)
  314. return null;
  315.  
  316. return W.model.junctions.objects[segObj.model.attributes.junctionID].segIDs;
  317. };
  318.  
  319. this.getAllRoundaboutJunctionNodesFromObj = function(segObj){
  320. var RASegs = this.getAllRoundaboutSegmentsFromObj(segObj);
  321. var RAJunctionNodes = [];
  322. for(i=0; i< RASegs.length; i++){
  323. RAJunctionNodes.push(W.model.nodes.objects[W.model.segments.get(RASegs[i]).attributes.toNodeID]);
  324.  
  325. }
  326. return RAJunctionNodes;
  327. };
  328.  
  329. this.isRoundaboutSegmentID = function(segmentID){
  330. if(W.model.segments.get(segmentID).attributes.junctionID === null)
  331. return false;
  332. else
  333. return true;
  334. };
  335.  
  336. this.isRoundaboutSegmentObj = function(segObj){
  337. if(segObj.model.attributes.junctionID === null)
  338. return false;
  339. else
  340. return true;
  341. };
  342.  
  343. /**
  344. * Defers execution of a callback function until the WME map and data
  345. * model are ready. Call this function before calling a function that
  346. * causes a map and model reload, such as W.map.moveTo(). After the
  347. * move is completed the callback function will be executed.
  348. * @function WazeWrap.Model.onModelReady
  349. * @param {Function} callback The callback function to be executed.
  350. * @param {Boolean} now Whether or not to call the callback now if the
  351. * model is currently ready.
  352. * @param {Object} context The context in which to call the callback.
  353. */
  354. this.onModelReady = function (callback, now, context) {
  355. var deferModelReady = function () {
  356. return $.Deferred(function (dfd) {
  357. var resolve = function () {
  358. dfd.resolve();
  359. W.model.events.unregister('mergeend', null, resolve);
  360. };
  361. W.model.events.register('mergeend', null, resolve);
  362. }).promise();
  363. };
  364. var deferMapReady = function () {
  365. return $.Deferred(function (dfd) {
  366. var resolve = function () {
  367. dfd.resolve();
  368. W.vent.off('operationDone', resolve);
  369. };
  370. W.vent.on('operationDone', resolve);
  371. }).promise();
  372. };
  373.  
  374. if (typeof callback === 'function') {
  375. context = context || callback;
  376. if (now && WazeWrapBeta.Util.mapReady() && WazeWrapBeta.Util.modelReady()) {
  377. callback.call(context);
  378. } else {
  379. $.when(deferMapReady() && deferModelReady()).
  380. then(function () {
  381. callback.call(context);
  382. });
  383. }
  384. }
  385. };
  386. };
  387. function User(){
  388. this.Rank = function(){
  389. return W.loginManager.user.normalizedLevel;
  390. };
  391.  
  392. this.Username = function(){
  393. return W.loginManager.user.userName;
  394. };
  395.  
  396. this.isCM = function(){
  397. if(W.loginManager.user.editableCountryIDs.length > 0)
  398. return true;
  399. else
  400. return false;
  401. };
  402. this.isAM = function(){
  403. return W.loginManager.user.isAreaManager;
  404. };
  405. };
  406. function Util(){
  407. /**
  408. * Function to defer function execution until an element is present on
  409. * the page.
  410. * @function WazeWrap.Util.waitForElement
  411. * @param {String} selector The CSS selector string or a jQuery object
  412. * to find before executing the callback.
  413. * @param {Function} callback The function to call when the page
  414. * element is detected.
  415. * @param {Object} [context] The context in which to call the callback.
  416. */
  417. this.waitForElement = function (selector, callback, context) {
  418. var jqObj;
  419.  
  420. if (!selector || typeof callback !== 'function') {
  421. return;
  422. }
  423.  
  424. jqObj = typeof selector === 'string' ?
  425. $(selector) : selector instanceof $ ? selector : null;
  426.  
  427. if (!jqObj.size()) {
  428. window.requestAnimationFrame(function () {
  429. WazeWrapBeta.Util.waitForElement(selector, callback, context);
  430. });
  431. } else {
  432. callback.call(context || callback);
  433. }
  434. };
  435.  
  436. /**
  437. * Function to track the ready state of the map.
  438. * @function WazeWrap.Util.mapReady
  439. * @return {Boolean} Whether or not a map operation is pending or
  440. * undefined if the function has not yet seen a map ready event fired.
  441. */
  442. this.mapReady = function () {
  443. var mapReady = true;
  444. W.vent.on('operationPending', function () {
  445. mapReady = false;
  446. });
  447. W.vent.on('operationDone', function () {
  448. mapReady = true;
  449. });
  450. return function () {
  451. return mapReady;
  452. };
  453. } ();
  454.  
  455. /**
  456. * Function to track the ready state of the model.
  457. * @function WazeWrap.Util.modelReady
  458. * @return {Boolean} Whether or not the model has loaded objects or
  459. * undefined if the function has not yet seen a model ready event fired.
  460. */
  461. this.modelReady = function () {
  462. var modelReady = true;
  463. W.model.events.register('mergestart', null, function () {
  464. modelReady = false;
  465. });
  466. W.model.events.register('mergeend', null, function () {
  467. modelReady = true;
  468. });
  469. return function () {
  470. return modelReady;
  471. };
  472. } ();
  473. };
  474.  
  475. function Interface() {
  476. /**
  477. * Generates id for message bars.
  478. * @private
  479. */
  480. var getNextID = function () {
  481. var id = 1;
  482. return function () {
  483. return id++;
  484. };
  485. } ();
  486. this.Shortcut = OL.Class(this, /** @lends WazeWrap.Interface.Shortcut.prototype */ {
  487. name: null,
  488. group: null,
  489. shortcut: {},
  490. callback: null,
  491. scope: null,
  492. groupExists: false,
  493. actionExists: false,
  494. eventExists: false,
  495. defaults: {
  496. group: 'default'
  497. },
  498. /**
  499. * Creates a new {WazeWrap.Interface.Shortcut}.
  500. * @class
  501. * @name WazeWrap.Interface.Shortcut
  502. * @param name {String} The name of the shortcut.
  503. * @param group {String} The name of the shortcut group.
  504. * @param shortcut {String} The shortcut key(s). The shortcut
  505. * should be of the form 'i' where i is the keyboard shortuct or
  506. * include modifier keys such as 'CSA+i', where C = the control
  507. * key, S = the shift key, A = the alt key, and i = the desired
  508. * keyboard shortcut. The modifier keys are optional.
  509. * @param callback {Function} The function to be called by the
  510. * shortcut.
  511. * @param scope {Object} The object to be used as this by the
  512. * callback.
  513. * @return {WazeWrap.Interface.Shortcut} The new shortcut object.
  514. * @example //Creates new shortcut and adds it to the map.
  515. * shortcut = new WazeWrap.Interface.Shortcut('myName', 'myGroup', 'C+p', callbackFunc, null).add();
  516. */
  517. initialize: function (name, group, shortcut, callback, scope) {
  518. if ('string' === typeof name && name.length > 0 &&
  519. 'string' === typeof shortcut && shortcut.length > 0 &&
  520. 'function' === typeof callback) {
  521. this.name = name;
  522. this.group = group || this.defaults.group;
  523. this.callback = callback;
  524. this.shortcut[shortcut] = name;
  525. if ('object' !== typeof scope) {
  526. this.scope = null;
  527. } else {
  528. this.scope = scope;
  529. }
  530. return this;
  531. }
  532. },
  533. /**
  534. * Determines if the shortcut's group already exists.
  535. * @private
  536. */
  537. doesGroupExist: function () {
  538. this.groupExists = 'undefined' !== typeof W.accelerators.Groups[this.group] &&
  539. undefined !== typeof W.accelerators.Groups[this.group].members &&
  540. W.accelerators.Groups[this.group].length > 0;
  541. return this.groupExists;
  542. },
  543. /**
  544. * Determines if the shortcut's action already exists.
  545. * @private
  546. */
  547. doesActionExist: function () {
  548. this.actionExists = 'undefined' !== typeof W.accelerators.Actions[this.name];
  549. return this.actionExists;
  550. },
  551. /**
  552. * Determines if the shortcut's event already exists.
  553. * @private
  554. */
  555. doesEventExist: function () {
  556. this.eventExists = 'undefined' !== typeof W.accelerators.events.listeners[this.name] &&
  557. W.accelerators.events.listeners[this.name].length > 0 &&
  558. this.callback === W.accelerators.events.listeners[this.name][0].func &&
  559. this.scope === W.accelerators.events.listeners[this.name][0].obj;
  560. return this.eventExists;
  561. },
  562. /**
  563. * Creates the shortcut's group.
  564. * @private
  565. */
  566. createGroup: function () {
  567. W.accelerators.Groups[this.group] = [];
  568. W.accelerators.Groups[this.group].members = [];
  569. },
  570. /**
  571. * Registers the shortcut's action.
  572. * @private
  573. */
  574. addAction: function () {
  575. W.accelerators.addAction(this.name, { group: this.group });
  576. },
  577. /**
  578. * Registers the shortcut's event.
  579. * @private
  580. */
  581. addEvent: function () {
  582. W.accelerators.events.register(this.name, this.scope, this.callback);
  583. },
  584. /**
  585. * Registers the shortcut's keyboard shortcut.
  586. * @private
  587. */
  588. registerShortcut: function () {
  589. W.accelerators._registerShortcuts(this.shortcut);
  590. },
  591. /**
  592. * Adds the keyboard shortcut to the map.
  593. * @return {WazeWrap.Interface.Shortcut} The keyboard shortcut.
  594. */
  595. add: function () {
  596. /* If the group is not already defined, initialize the group. */
  597. if (!this.doesGroupExist()) {
  598. this.createGroup();
  599. }
  600.  
  601. /* Clear existing actions with same name */
  602. if (this.doesActionExist()) {
  603. W.accelerators.Actions[this.name] = null;
  604. }
  605. this.addAction();
  606.  
  607. /* Register event only if it's not already registered */
  608. if (!this.doesEventExist()) {
  609. this.addEvent();
  610. }
  611.  
  612. /* Finally, register the shortcut. */
  613. this.registerShortcut();
  614. return this;
  615. },
  616. /**
  617. * Removes the keyboard shortcut from the map.
  618. * @return {WazeWrap.Interface.Shortcut} The keyboard shortcut.
  619. */
  620. remove: function () {
  621. if (this.doesEventExist()) {
  622. W.accelerators.events.unregister(this.name, this.scope, this.callback);
  623. }
  624. if (this.doesActionExist()) {
  625. delete W.accelerators.Actions[this.name];
  626. }
  627. //remove shortcut?
  628. return this;
  629. },
  630. /**
  631. * Changes the keyboard shortcut and applies changes to the map.
  632. * @return {WazeWrap.Interface.Shortcut} The keyboard shortcut.
  633. */
  634. change: function (shortcut) {
  635. if (shortcut) {
  636. this.shortcut = {};
  637. this.shortcut[shortcut] = this.name;
  638. this.registerShortcut();
  639. }
  640. return this;
  641. }
  642. }),
  643.  
  644. this.Tab = OL.Class(this, {
  645. /** @lends WazeWrap.Interface.Tab */
  646. TAB_SELECTOR: '#user-tabs ul.nav-tabs',
  647. CONTENT_SELECTOR: '#user-info div.tab-content',
  648. callback: null,
  649. $content: null,
  650. context: null,
  651. $tab: null,
  652. /**
  653. * Creates a new WazeWrap.Interface.Tab. The tab is appended to the WME
  654. * editor sidebar and contains the passed HTML content.
  655. * @class
  656. * @name WazeWrap.Interface.Tab
  657. * @param {String} name The name of the tab. Should not contain any
  658. * special characters.
  659. * @param {String} content The HTML content of the tab.
  660. * @param {Function} [callback] A function to call upon successfully
  661. * appending the tab.
  662. * @param {Object} [context] The context in which to call the callback
  663. * function.
  664. * @return {WazeWrap.Interface.Tab} The new tab object.
  665. * @example //Creates new tab and adds it to the page.
  666. * new WazeWrap.Interface.Tab('thebestscriptever', '<div>Hello World!</div>');
  667. */
  668. initialize: function (name, content, callback, context) {
  669. var idName, i = 0;
  670. if (name && 'string' === typeof name &&
  671. content && 'string' === typeof content) {
  672. if (callback && 'function' === typeof callback) {
  673. this.callback = callback;
  674. this.context = context || callback;
  675. }
  676. /* Sanitize name for html id attribute */
  677. idName = name.toLowerCase().replace(/[^a-z-_]/g, '');
  678. /* Make sure id will be unique on page */
  679. while (
  680. $('#sidepanel-' + (i ? idName + i : idName)).length > 0) {
  681. i++;
  682. }
  683. if (i) {
  684. idName = idName + i;
  685. }
  686. /* Create tab and content */
  687. this.$tab = $('<li/>')
  688. .append($('<a/>')
  689. .attr({
  690. 'href': '#sidepanel-' + idName,
  691. 'data-toggle': 'tab',
  692. })
  693. .text(name));
  694. this.$content = $('<div/>')
  695. .addClass('tab-pane')
  696. .attr('id', 'sidepanel-' + idName)
  697. .html(content);
  698.  
  699. this.appendTab();
  700. }
  701. },
  702.  
  703. append: function (content) {
  704. this.$content.append(content);
  705. },
  706.  
  707. appendTab: function () {
  708. WazeWrapBeta.Util.waitForElement(
  709. this.TAB_SELECTOR + ',' + this.CONTENT_SELECTOR,
  710. function () {
  711. $(this.TAB_SELECTOR).append(this.$tab);
  712. $(this.CONTENT_SELECTOR).first().append(this.$content);
  713. if (this.callback) {
  714. this.callback.call(this.context);
  715. }
  716. }, this);
  717. },
  718.  
  719. clearContent: function () {
  720. this.$content.empty();
  721. },
  722.  
  723. destroy: function () {
  724. this.$tab.remove();
  725. this.$content.remove();
  726. }
  727. });
  728. };
  729.  
  730. }.call(this));

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址