WazeWrap

A base library for WME script writers

当前为 2017-01-04 提交的版本,查看 最新版本

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

  1. // ==UserScript==
  2. // @name WazeWrap
  3. // @namespace https://gf.qytechs.cn/users/30701-justins83-waze
  4. // @version 0.2
  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 WazeWrap */
  15.  
  16. var WazeWrap = {};
  17.  
  18. (function() {
  19.  
  20. function bootstrap(tries) {
  21. tries = tries || 1;
  22. if (window.W &&
  23. window.W.map &&
  24. window.W.model &&
  25. window.W.loginManager &&
  26. $) {
  27. init();
  28. } else if (tries < 1000) {
  29. setTimeout(function () { bootstrap(tries++); }, 200);
  30. } else {
  31. console.log('WazeWrap failed to load');
  32. }
  33. }
  34.  
  35. bootstrap();
  36.  
  37. function init(){
  38. console.log("WazeWrap initializing...");
  39. var oldLib = window.WazeWrap;
  40. var root = this;
  41.  
  42. WazeWrap.Version = GM_info.script.version;
  43. WazeWrap.isBetaEditor = /beta/.test(location.href);
  44.  
  45. SetUpRequire();
  46.  
  47. WazeWrap.test = "test";
  48. WazeWrap.Geometry = new Geometry;
  49. WazeWrap.Model = new Model;
  50. WazeWrap.Interface = new Interface;
  51. WazeWrap.User = new User;
  52. WazeWrap.Util = new Util;
  53. WazeWrap.Require = new Require;
  54. root.WazeWrap = WazeWrap;
  55.  
  56. console.log('WazeWrap Loaded');
  57. };
  58.  
  59.  
  60. function SetUpRequire(){
  61. if(this.isBetaEditor || typeof window.require !== "undefined")
  62. return;
  63.  
  64. console.log("Setting d2's require fix...");
  65.  
  66. // setup one global var and put all in
  67. var WMEAPI = {};
  68.  
  69. // detect URL of WME source code
  70. WMEAPI.scripts = document.getElementsByTagName('script');
  71. WMEAPI.url=null;
  72. for (i=0;i<WMEAPI.scripts.length;i++){
  73. if (WMEAPI.scripts[i].src.indexOf('/assets-editor/js/app')!=-1)
  74. {
  75. WMEAPI.url=WMEAPI.scripts[i].src;
  76. break;
  77. }
  78. }
  79. if (WMEAPI.url==null)
  80. throw new Error("WME Hack: can't detect WME main JS");
  81.  
  82.  
  83. // setup a fake require and require.define
  84. WMEAPI.require=function (e) {
  85. if (WMEAPI.require.define.modules.hasOwnProperty(e))
  86. return WMEAPI.require.define.modules[e];
  87. else
  88. console.error('Require failed on ' + e, WMEAPI.require.define.modules);
  89. return null;
  90. };
  91.  
  92. WMEAPI.require.define=function (m) {
  93. if (WMEAPI.require.define.hasOwnProperty('modules')==false)
  94. WMEAPI.require.define.modules={};
  95. for (var p in m){
  96. WMEAPI.require.define.modules[p]=m[p];
  97. }
  98. };
  99.  
  100. // save the original webpackJsonp function
  101. WMEAPI.tmp = window.webpackJsonp;
  102.  
  103. // taken from WME code: this function is a wrapper that setup the API and may call recursively other functions
  104. WMEAPI.t = function (n) {
  105. if (WMEAPI.s[n]) return WMEAPI.s[n].exports;
  106. var r = WMEAPI.s[n] = {
  107. exports: {},
  108. id: n,
  109. loaded: !1
  110. };
  111. return WMEAPI.e[n].call(r.exports, r, r.exports, WMEAPI.t), r.loaded = !0, r.exports;
  112. };
  113.  
  114. // e is a copy of all WME funcs because function t need to access to this list
  115. WMEAPI.e=[];
  116.  
  117. // the patch
  118. window.webpackJsonp = function(a, i) {
  119. // our API but we will use it only to build the require stuffs
  120. var api={};
  121. // taken from WME code. a is [1], so...
  122. 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;
  123. var unknownCount=0;
  124. var classname, funcStr;
  125. // copy i in e and keep a link from classname to index in e
  126. for (o in i){
  127. WMEAPI.e[o] = i[o];
  128. funcStr = i[o].toString();
  129. classname = funcStr.match(/CLASS_NAME:\"([^\"]*)\"/);
  130. if (classname){
  131. // keep the link.
  132. api[classname[1].replace(/\./g,'/').replace(/^W\//, 'Waze/')]={index: o, func: WMEAPI.e[o]};
  133. }
  134. else{
  135. api['Waze/Unknown/' + unknownCount]={index: o, func: WMEAPI.e[o]};
  136. unknownCount++;
  137. }
  138. }
  139. // taken from WME code: it calls the original webpackJsonp and do something else, but I don't really know what.
  140. // removed the call to the original webpackJsonp: still works...
  141. //for (tmp && tmp(a, i); l.length;) l.shift().call(null, t);
  142. for (; l.length;) l.shift().call(null, WMEAPI.t);
  143. WMEAPI.s[0] = 0;
  144. // run the first func of WME. This first func will call recusrsively all funcs needed to setup the API.
  145. // After this call, s will contain all instanciables classes.
  146. //var ret = WMEAPI.t(0);
  147. // now, build the requires thanks to the link we've built in var api.
  148. var module={};
  149. var apiFuncName;
  150. unknownCount=0;
  151. for (o in i){
  152. funcStr = i[o].toString();
  153. classname = funcStr.match(/CLASS_NAME:\"([^\"]*)\"/);
  154. if (classname){
  155. module={};
  156. apiFuncName = classname[1].replace(/\./g,'/').replace(/^W\//, 'Waze/');
  157. module[apiFuncName]=WMEAPI.t(api[apiFuncName].index);
  158. WMEAPI.require.define(module);
  159. }
  160. else{
  161. var matches = funcStr.match(/SEGMENT:"segment",/);
  162. if (matches){
  163. module={};
  164. apiFuncName='Waze/Model/ObjectType';
  165. module[apiFuncName]=WMEAPI.t(api['Waze/Unknown/' + unknownCount].index);
  166. WMEAPI.require.define(module);
  167. }
  168. unknownCount++;
  169. }
  170. }
  171.  
  172. // restore the original func
  173. window.webpackJsonp=WMEAPI.tmp;
  174.  
  175. // set the require public if needed
  176. // if so: others scripts must wait for the window.require to be available before using it.
  177. window.require = WMEAPI.require;
  178. // all available functions are in WMEAPI.require.define.modules
  179. // console.debug this variable to read it:
  180. // console.debug('Modules: ', WMEAPI.require.define.modules);
  181. // run your script here:
  182. // setTimeout(yourscript);
  183. // again taken from WME code. Not sure about what it does.
  184. //if (i[0]) return ret;
  185. };
  186.  
  187. // some kind of global vars and init
  188. WMEAPI.s = {};
  189. WMEAPI.r = {
  190. 0: 0
  191. };
  192.  
  193. // hacking finished
  194.  
  195. // load again WME through our patched func
  196. WMEAPI.WMEHACK_Injected_script = document.createElement("script");
  197. WMEAPI.WMEHACK_Injected_script.setAttribute("type", "application/javascript");
  198. WMEAPI.WMEHACK_Injected_script.src = WMEAPI.url;
  199. document.body.appendChild(WMEAPI.WMEHACK_Injected_script);
  200. console.log("d2 fix complete");
  201. }
  202.  
  203. function Geometry(){
  204. //var geometry = WazeWrap.Geometry;
  205.  
  206. //Converts to "normal" GPS coordinates
  207. this.ConvertTo4326 = function (long, lat){
  208. var projI=new OpenLayers.Projection("EPSG:900913");
  209. var projE=new OpenLayers.Projection("EPSG:4326");
  210. return (new OpenLayers.LonLat(long, lat)).transform(projI,projE);
  211. };
  212. this.ConvertTo900913 = function (long, lat){
  213. var projI=new OpenLayers.Projection("EPSG:900913");
  214. var projE=new OpenLayers.Projection("EPSG:4326");
  215. return (new OpenLayers.LonLat(long, lat)).transform(projE,projI);
  216. };
  217.  
  218. //Converts the Longitudinal offset to an offset in 4326 gps coordinates
  219. this.CalculateLongOffsetGPS = function(longMetersOffset, long, lat)
  220. {
  221. var R= 6378137; //Earth's radius
  222. var dLon = longMetersOffset / (R * Math.cos(Math.PI * lat / 180)); //offset in radians
  223. var lon0 = dLon * (180 / Math.PI); //offset degrees
  224.  
  225. return lon0;
  226. };
  227.  
  228. //Converts the Latitudinal offset to an offset in 4326 gps coordinates
  229. this.CalculateLatOffsetGPS = function(latMetersOffset, lat)
  230. {
  231. var R= 6378137; //Earth's radius
  232. var dLat = latMetersOffset/R;
  233. var lat0 = dLat * (180 /Math.PI); //offset degrees
  234.  
  235. return lat0;
  236. };
  237. /**
  238. * Checks if the given geometry is on screen
  239. * @function WazeWrap.Geometry.isGeometryInMapExtent
  240. * @param {OpenLayers.Geometry} Geometry to check if any part of is in the current viewport
  241. */
  242. this.isLonLatInMapExtent = function (lonLat) {
  243. 'use strict';
  244. return lonLat && W.map.getExtent().containsLonLat(lonLat);
  245. };
  246. /**
  247. * Checks if the given geometry is on screen
  248. * @function WazeWrap.Geometry.isGeometryInMapExtent
  249. * @param {OpenLayers.Geometry} Geometry to check if any part of is in the current viewport
  250. */
  251. this.isGeometryInMapExtent = function (geometry) {
  252. 'use strict';
  253. return geometry && geometry.getBounds &&
  254. W.map.getExtent().intersectsBounds(geometry.getBounds());
  255. };
  256. /**
  257. * Calculates the distance between two given points, returned in meters
  258. * @function WazeWrap.Geometry.calculateDistance
  259. * @param {OpenLayers.Geometry.Point} An array of OL.Geometry.Point with which to measure the total distance. A minimum of 2 points is needed.
  260. */
  261. this.calculateDistance = function(pointArray) {
  262. if(pointArray.length < 2)
  263. return 0;
  264.  
  265. var line = new OpenLayers.Geometry.LineString(pointArray);
  266. length = line.getGeodesicLength(W.map.getProjectionObject());
  267. return length; //multiply by 3.28084 to convert to feet
  268. };
  269. this.findClosestSegment = function(mygeometry){
  270. var onscreenSegments = WazeWrap.Model.getOnscreenSegments();
  271. var minDistance = Infinity;
  272. var closestSegment;
  273. for (s in onscreenSegments) {
  274. if (!onscreenSegments.hasOwnProperty(s))
  275. continue;
  276.  
  277. segmentType = onscreenSegments[s].attributes.roadType;
  278. if (segmentType === 10 || segmentType === 3 || segmentType === 16 || segmentType === 18 || segmentType === 19) //10 ped boardwalk, 16 stairway, 18 railroad, 19 runway, 3 freeway
  279. continue;
  280.  
  281. distanceToSegment = mygeometry.distanceTo(onscreenSegments[s].geometry, {details: true});
  282.  
  283. if (distanceToSegment.distance < minDistance) {
  284. minDistance = distanceToSegment.distance;
  285. closestSegment = onscreenSegments[s];
  286. }
  287. }
  288. return closestSegment;
  289. };
  290. };
  291.  
  292. function Model(){
  293.  
  294. this.getPrimaryStreetID = function(segmentID){
  295. return W.model.segments.get(segmentID).attributes.primaryStreetID;
  296. };
  297.  
  298. this.getStreetName = function(primaryStreetID){
  299. return W.model.streets.get(primaryStreetID).name;
  300. };
  301.  
  302. this.getCityID = function(primaryStreetID){
  303. return W.model.streets.get(primaryStreetID).cityID;
  304. };
  305.  
  306. this.getCityName = function(primaryStreetID){
  307. return W.model.cities.get(this.getCityID(primaryStreetID)).attributes.Name;
  308. };
  309.  
  310. this.getStateName = function(primaryStreetID){
  311. return W.model.states.get(getStateID(primaryStreetID)).Name;
  312. };
  313.  
  314. this.getStateID = function(primaryStreetID){
  315. return W.model.cities.get(primaryStreetID).attributes.stateID;
  316. };
  317.  
  318. this.getCountryID = function(primaryStreetID){
  319. return W.model.cities.get(this.getCityID(primaryStreetID)).attributes.CountryID;
  320. };
  321.  
  322. this.getCountryName = function(primaryStreetID){
  323. return W.model.countries.get(getCountryID(primaryStreetID)).name;
  324. };
  325.  
  326. this.getCityNameFromSegmentObj = function(segObj){
  327. return this.getCityName(segObj.attributes.primaryStreetID);
  328. };
  329.  
  330. this.getStateNameFromSegmentObj = function(segObj){
  331. return this.getStateName(segObj.attributes.primaryStreetID);
  332. };
  333.  
  334. //returns an array of segmentIDs for all segments that are part of the same roundabout as the passed segment
  335. this.getAllRoundaboutSegmentsFromObj = function(segObj){
  336. if(segObj.model.attributes.junctionID === null)
  337. return null;
  338.  
  339. return W.model.junctions.objects[segObj.model.attributes.junctionID].segIDs;
  340. };
  341.  
  342. this.getAllRoundaboutJunctionNodesFromObj = function(segObj){
  343. var RASegs = this.getAllRoundaboutSegmentsFromObj(segObj);
  344. var RAJunctionNodes = [];
  345. for(i=0; i< RASegs.length; i++){
  346. RAJunctionNodes.push(W.model.nodes.objects[W.model.segments.get(RASegs[i]).attributes.toNodeID]);
  347.  
  348. }
  349. return RAJunctionNodes;
  350. };
  351.  
  352. this.isRoundaboutSegmentID = function(segmentID){
  353. if(W.model.segments.get(segmentID).attributes.junctionID === null)
  354. return false;
  355. else
  356. return true;
  357. };
  358.  
  359. this.isRoundaboutSegmentObj = function(segObj){
  360. if(segObj.model.attributes.junctionID === null)
  361. return false;
  362. else
  363. return true;
  364. };
  365. this.getOnscreenSegments = function(){
  366. var segments = W.model.segments.objects;
  367. var mapExtent = W.map.getExtent();
  368. var onScreenSegments = [];
  369. var seg;
  370.  
  371. for (s in segments) {
  372. if (!segments.hasOwnProperty(s))
  373. continue;
  374.  
  375. seg = W.model.segments.get(s);
  376. if (mapExtent.intersectsBounds(seg.geometry.getBounds()))
  377. onScreenSegments.push(seg);
  378. }
  379. return onScreenSegments;
  380. };
  381.  
  382. /**
  383. * Defers execution of a callback function until the WME map and data
  384. * model are ready. Call this function before calling a function that
  385. * causes a map and model reload, such as W.map.moveTo(). After the
  386. * move is completed the callback function will be executed.
  387. * @function WazeWrap.Model.onModelReady
  388. * @param {Function} callback The callback function to be executed.
  389. * @param {Boolean} now Whether or not to call the callback now if the
  390. * model is currently ready.
  391. * @param {Object} context The context in which to call the callback.
  392. */
  393. this.onModelReady = function (callback, now, context) {
  394. var deferModelReady = function () {
  395. return $.Deferred(function (dfd) {
  396. var resolve = function () {
  397. dfd.resolve();
  398. W.model.events.unregister('mergeend', null, resolve);
  399. };
  400. W.model.events.register('mergeend', null, resolve);
  401. }).promise();
  402. };
  403. var deferMapReady = function () {
  404. return $.Deferred(function (dfd) {
  405. var resolve = function () {
  406. dfd.resolve();
  407. W.vent.off('operationDone', resolve);
  408. };
  409. W.vent.on('operationDone', resolve);
  410. }).promise();
  411. };
  412.  
  413. if (typeof callback === 'function') {
  414. context = context || callback;
  415. if (now && WazeWrap.Util.mapReady() && WazeWrap.Util.modelReady()) {
  416. callback.call(context);
  417. } else {
  418. $.when(deferMapReady() && deferModelReady()).
  419. then(function () {
  420. callback.call(context);
  421. });
  422. }
  423. }
  424. };
  425. };
  426. function User(){
  427. this.Rank = function(){
  428. return W.loginManager.user.normalizedLevel;
  429. };
  430.  
  431. this.Username = function(){
  432. return W.loginManager.user.userName;
  433. };
  434.  
  435. this.isCM = function(){
  436. if(W.loginManager.user.editableCountryIDs.length > 0)
  437. return true;
  438. else
  439. return false;
  440. };
  441. this.isAM = function(){
  442. return W.loginManager.user.isAreaManager;
  443. };
  444. };
  445. function Require(){
  446. this.DragElement = function(){
  447. var myDragElement = OL.Class({
  448. started: !1,
  449. stopDown: !0,
  450. dragging: !1,
  451. touch: !1,
  452. last: null ,
  453. start: null ,
  454. lastMoveEvt: null ,
  455. oldOnselectstart: null ,
  456. interval: 0,
  457. timeoutId: null ,
  458. forced: !1,
  459. active: !1,
  460. initialize: function(e) {
  461. this.map = e,
  462. this.uniqueID = myDragElement.baseID--
  463. },
  464. callback: function(e, t) {
  465. if (this[e])
  466. return this[e].apply(this, t)
  467. },
  468. dragstart: function(e) {
  469. e.xy = new OL.Pixel(e.clientX - this.map.viewPortDiv.offsets[0],e.clientY - this.map.viewPortDiv.offsets[1]);
  470. var t = !0;
  471. return this.dragging = !1,
  472. (OL.Event.isLeftClick(e) || OL.Event.isSingleTouch(e)) && (this.started = !0,
  473. this.start = e.xy,
  474. this.last = e.xy,
  475. OL.Element.addClass(this.map.viewPortDiv, "olDragDown"),
  476. this.down(e),
  477. this.callback("down", [e.xy]),
  478. OL.Event.stop(e),
  479. this.oldOnselectstart || (this.oldOnselectstart = document.onselectstart ? document.onselectstart : OL.Function.True),
  480. document.onselectstart = OL.Function.False,
  481. t = !this.stopDown),
  482. t
  483. },
  484. forceStart: function() {
  485. var e = arguments.length > 0 && void 0 !== arguments[0] && arguments[0];
  486. return this.started = !0,
  487. this.endOnMouseUp = e,
  488. this.forced = !0,
  489. this.last = {
  490. x: 0,
  491. y: 0
  492. },
  493. this.callback("force")
  494. },
  495. forceEnd: function() {
  496. if (this.forced)
  497. return this.endDrag()
  498. },
  499. dragmove: function(e) {
  500. return this.map.viewPortDiv.offsets && (e.xy = new OL.Pixel(e.clientX - this.map.viewPortDiv.offsets[0],e.clientY - this.map.viewPortDiv.offsets[1])),
  501. this.lastMoveEvt = e,
  502. !this.started || this.timeoutId || e.xy.x === this.last.x && e.xy.y === this.last.y || (this.interval > 0 && (this.timeoutId = window.setTimeout(OL.Function.bind(this.removeTimeout, this), this.interval)),
  503. this.dragging = !0,
  504. this.move(e),
  505. this.oldOnselectstart || (this.oldOnselectstart = document.onselectstart,
  506. document.onselectstart = OL.Function.False),
  507. this.last = e.xy),
  508. !0
  509. },
  510. dragend: function(e) {
  511. if (e.xy = new OL.Pixel(e.clientX - this.map.viewPortDiv.offsets[0],e.clientY - this.map.viewPortDiv.offsets[1]),
  512. this.started) {
  513. var t = this.start !== this.last;
  514. this.endDrag(),
  515. this.up(e),
  516. this.callback("up", [e.xy]),
  517. t && this.callback("done", [e.xy])
  518. }
  519. return !0
  520. },
  521. endDrag: function() {
  522. this.started = !1,
  523. this.dragging = !1,
  524. this.forced = !1,
  525. OL.Element.removeClass(this.map.viewPortDiv, "olDragDown"),
  526. document.onselectstart = this.oldOnselectstart
  527. },
  528. down: function(e) {},
  529. move: function(e) {},
  530. up: function(e) {},
  531. out: function(e) {},
  532. mousedown: function(e) {
  533. return this.dragstart(e)
  534. },
  535. touchstart: function(e) {
  536. return this.touch || (this.touch = !0,
  537. this.map.events.un({
  538. mousedown: this.mousedown,
  539. mouseup: this.mouseup,
  540. mousemove: this.mousemove,
  541. click: this.click,
  542. scope: this
  543. })),
  544. this.dragstart(e)
  545. },
  546. mousemove: function(e) {
  547. return this.dragmove(e)
  548. },
  549. touchmove: function(e) {
  550. return this.dragmove(e)
  551. },
  552. removeTimeout: function() {
  553. if (this.timeoutId = null ,
  554. this.dragging)
  555. return this.mousemove(this.lastMoveEvt)
  556. },
  557. mouseup: function(e) {
  558. if (!this.forced || this.endOnMouseUp)
  559. return this.started ? this.dragend(e) : void 0
  560. },
  561. touchend: function(e) {
  562. if (e.xy = this.last,
  563. !this.forced)
  564. return this.dragend(e)
  565. },
  566. click: function(e) {
  567. return this.start === this.last
  568. },
  569. activate: function(e) {
  570. this.$el = e,
  571. this.active = !0;
  572. var t = $(this.map.viewPortDiv);
  573. return this.$el.on("mousedown.drag-" + this.uniqueID, $.proxy(this.mousedown, this)),
  574. this.$el.on("touchstart.drag-" + this.uniqueID, $.proxy(this.touchstart, this)),
  575. $(document).on("mouseup.drag-" + this.uniqueID, $.proxy(this.mouseup, this)),
  576. t.on("mousemove.drag-" + this.uniqueID, $.proxy(this.mousemove, this)),
  577. t.on("touchmove.drag-" + this.uniqueID, $.proxy(this.touchmove, this)),
  578. t.on("touchend.drag-" + this.uniqueID, $.proxy(this.touchend, this))
  579. },
  580. deactivate: function() {
  581. return this.active = !1,
  582. this.$el.off(".drag-" + this.uniqueID),
  583. $(this.map.viewPortDiv).off(".drag-" + this.uniqueID),
  584. $(document).off(".drag-" + this.uniqueID),
  585. this.touch = !1,
  586. this.started = !1,
  587. this.forced = !1,
  588. this.dragging = !1,
  589. this.start = null ,
  590. this.last = null ,
  591. OL.Element.removeClass(this.map.viewPortDiv, "olDragDown")
  592. },
  593. adjustXY: function(e) {
  594. var t = OL.Util.pagePosition(this.map.viewPortDiv);
  595. return e.xy.x -= t[0],
  596. e.xy.y -= t[1]
  597. },
  598. CLASS_NAME: "W.Handler.DragElement"
  599. });
  600. myDragElement.baseID = 0;
  601. return myDragElement;
  602. };
  603. this.DivIcon = OpenLayers.Class({
  604. className: null ,
  605. $div: null ,
  606. events: null ,
  607. initialize: function(e, t) {
  608. this.className = e,
  609. this.moveWithTransform = !!t,
  610. this.$div = $("<div />").addClass(e),
  611. this.div = this.$div.get(0),
  612. this.imageDiv = this.$div.get(0);
  613. },
  614. destroy: function() {
  615. this.erase(),
  616. this.$div = null;
  617. },
  618. clone: function() {
  619. return new i(this.className);
  620. },
  621. draw: function(e) {
  622. return this.moveWithTransform ? (this.$div.css({
  623. transform: "translate(" + e.x + "px, " + e.y + "px)"
  624. }),
  625. this.$div.css({
  626. position: "absolute"
  627. })) : this.$div.css({
  628. position: "absolute",
  629. left: e.x,
  630. top: e.y
  631. }),
  632. this.$div.get(0);
  633. },
  634. moveTo: function(e) {
  635. null !== e && (this.px = e),
  636. null === this.px ? this.display(!1) : this.moveWithTransform ? this.$div.css({
  637. transform: "translate(" + this.px.x + "px, " + this.px.y + "px)"
  638. }) : this.$div.css({
  639. left: this.px.x,
  640. top: this.px.y
  641. });
  642. },
  643. erase: function() {
  644. this.$div.remove();
  645. },
  646. display: function(e) {
  647. this.$div.toggle(e);
  648. },
  649. isDrawn: function() {
  650. return !!this.$div.parent().length;
  651. },
  652. bringToFront: function() {
  653. if (this.isDrawn()) {
  654. var e = this.$div.parent();
  655. this.$div.detach().appendTo(e);
  656. }
  657. },
  658. forceReflow: function() {
  659. return this.$div.get(0).offsetWidth;
  660. },
  661. CLASS_NAME: "Waze.DivIcon"
  662. });
  663. };
  664. function Util(){
  665. /**
  666. * Function to defer function execution until an element is present on
  667. * the page.
  668. * @function WazeWrap.Util.waitForElement
  669. * @param {String} selector The CSS selector string or a jQuery object
  670. * to find before executing the callback.
  671. * @param {Function} callback The function to call when the page
  672. * element is detected.
  673. * @param {Object} [context] The context in which to call the callback.
  674. */
  675. this.waitForElement = function (selector, callback, context) {
  676. var jqObj;
  677.  
  678. if (!selector || typeof callback !== 'function') {
  679. return;
  680. }
  681.  
  682. jqObj = typeof selector === 'string' ?
  683. $(selector) : selector instanceof $ ? selector : null;
  684.  
  685. if (!jqObj.size()) {
  686. window.requestAnimationFrame(function () {
  687. WazeWrap.Util.waitForElement(selector, callback, context);
  688. });
  689. } else {
  690. callback.call(context || callback);
  691. }
  692. };
  693.  
  694. /**
  695. * Function to track the ready state of the map.
  696. * @function WazeWrap.Util.mapReady
  697. * @return {Boolean} Whether or not a map operation is pending or
  698. * undefined if the function has not yet seen a map ready event fired.
  699. */
  700. this.mapReady = function () {
  701. var mapReady = true;
  702. W.vent.on('operationPending', function () {
  703. mapReady = false;
  704. });
  705. W.vent.on('operationDone', function () {
  706. mapReady = true;
  707. });
  708. return function () {
  709. return mapReady;
  710. };
  711. } ();
  712.  
  713. /**
  714. * Function to track the ready state of the model.
  715. * @function WazeWrap.Util.modelReady
  716. * @return {Boolean} Whether or not the model has loaded objects or
  717. * undefined if the function has not yet seen a model ready event fired.
  718. */
  719. this.modelReady = function () {
  720. var modelReady = true;
  721. W.model.events.register('mergestart', null, function () {
  722. modelReady = false;
  723. });
  724. W.model.events.register('mergeend', null, function () {
  725. modelReady = true;
  726. });
  727. return function () {
  728. return modelReady;
  729. };
  730. } ();
  731. };
  732.  
  733. function Interface() {
  734. /**
  735. * Generates id for message bars.
  736. * @private
  737. */
  738. var getNextID = function () {
  739. var id = 1;
  740. return function () {
  741. return id++;
  742. };
  743. } ();
  744. this.Shortcut = OL.Class(this, /** @lends WazeWrap.Interface.Shortcut.prototype */ {
  745. name: null,
  746. group: null,
  747. shortcut: {},
  748. callback: null,
  749. scope: null,
  750. groupExists: false,
  751. actionExists: false,
  752. eventExists: false,
  753. defaults: {
  754. group: 'default'
  755. },
  756. /**
  757. * Creates a new {WazeWrap.Interface.Shortcut}.
  758. * @class
  759. * @name WazeWrap.Interface.Shortcut
  760. * @param name {String} The name of the shortcut.
  761. * @param group {String} The name of the shortcut group.
  762. * @param shortcut {String} The shortcut key(s). The shortcut
  763. * should be of the form 'i' where i is the keyboard shortuct or
  764. * include modifier keys such as 'CSA+i', where C = the control
  765. * key, S = the shift key, A = the alt key, and i = the desired
  766. * keyboard shortcut. The modifier keys are optional.
  767. * @param callback {Function} The function to be called by the
  768. * shortcut.
  769. * @param scope {Object} The object to be used as this by the
  770. * callback.
  771. * @return {WazeWrap.Interface.Shortcut} The new shortcut object.
  772. * @example //Creates new shortcut and adds it to the map.
  773. * shortcut = new WazeWrap.Interface.Shortcut('myName', 'myGroup', 'C+p', callbackFunc, null).add();
  774. */
  775. initialize: function (name, group, shortcut, callback, scope) {
  776. if ('string' === typeof name && name.length > 0 &&
  777. 'string' === typeof shortcut && shortcut.length > 0 &&
  778. 'function' === typeof callback) {
  779. this.name = name;
  780. this.group = group || this.defaults.group;
  781. this.callback = callback;
  782. this.shortcut[shortcut] = name;
  783. if ('object' !== typeof scope) {
  784. this.scope = null;
  785. } else {
  786. this.scope = scope;
  787. }
  788. return this;
  789. }
  790. },
  791. /**
  792. * Determines if the shortcut's group already exists.
  793. * @private
  794. */
  795. doesGroupExist: function () {
  796. this.groupExists = 'undefined' !== typeof W.accelerators.Groups[this.group] &&
  797. undefined !== typeof W.accelerators.Groups[this.group].members &&
  798. W.accelerators.Groups[this.group].length > 0;
  799. return this.groupExists;
  800. },
  801. /**
  802. * Determines if the shortcut's action already exists.
  803. * @private
  804. */
  805. doesActionExist: function () {
  806. this.actionExists = 'undefined' !== typeof W.accelerators.Actions[this.name];
  807. return this.actionExists;
  808. },
  809. /**
  810. * Determines if the shortcut's event already exists.
  811. * @private
  812. */
  813. doesEventExist: function () {
  814. this.eventExists = 'undefined' !== typeof W.accelerators.events.listeners[this.name] &&
  815. W.accelerators.events.listeners[this.name].length > 0 &&
  816. this.callback === W.accelerators.events.listeners[this.name][0].func &&
  817. this.scope === W.accelerators.events.listeners[this.name][0].obj;
  818. return this.eventExists;
  819. },
  820. /**
  821. * Creates the shortcut's group.
  822. * @private
  823. */
  824. createGroup: function () {
  825. W.accelerators.Groups[this.group] = [];
  826. W.accelerators.Groups[this.group].members = [];
  827. },
  828. /**
  829. * Registers the shortcut's action.
  830. * @private
  831. */
  832. addAction: function () {
  833. W.accelerators.addAction(this.name, { group: this.group });
  834. },
  835. /**
  836. * Registers the shortcut's event.
  837. * @private
  838. */
  839. addEvent: function () {
  840. W.accelerators.events.register(this.name, this.scope, this.callback);
  841. },
  842. /**
  843. * Registers the shortcut's keyboard shortcut.
  844. * @private
  845. */
  846. registerShortcut: function () {
  847. W.accelerators._registerShortcuts(this.shortcut);
  848. },
  849. /**
  850. * Adds the keyboard shortcut to the map.
  851. * @return {WazeWrap.Interface.Shortcut} The keyboard shortcut.
  852. */
  853. add: function () {
  854. /* If the group is not already defined, initialize the group. */
  855. if (!this.doesGroupExist()) {
  856. this.createGroup();
  857. }
  858.  
  859. /* Clear existing actions with same name */
  860. if (this.doesActionExist()) {
  861. W.accelerators.Actions[this.name] = null;
  862. }
  863. this.addAction();
  864.  
  865. /* Register event only if it's not already registered */
  866. if (!this.doesEventExist()) {
  867. this.addEvent();
  868. }
  869.  
  870. /* Finally, register the shortcut. */
  871. this.registerShortcut();
  872. return this;
  873. },
  874. /**
  875. * Removes the keyboard shortcut from the map.
  876. * @return {WazeWrap.Interface.Shortcut} The keyboard shortcut.
  877. */
  878. remove: function () {
  879. if (this.doesEventExist()) {
  880. W.accelerators.events.unregister(this.name, this.scope, this.callback);
  881. }
  882. if (this.doesActionExist()) {
  883. delete W.accelerators.Actions[this.name];
  884. }
  885. //remove shortcut?
  886. return this;
  887. },
  888. /**
  889. * Changes the keyboard shortcut and applies changes to the map.
  890. * @return {WazeWrap.Interface.Shortcut} The keyboard shortcut.
  891. */
  892. change: function (shortcut) {
  893. if (shortcut) {
  894. this.shortcut = {};
  895. this.shortcut[shortcut] = this.name;
  896. this.registerShortcut();
  897. }
  898. return this;
  899. }
  900. }),
  901.  
  902. this.Tab = OL.Class(this, {
  903. /** @lends WazeWrap.Interface.Tab */
  904. TAB_SELECTOR: '#user-tabs ul.nav-tabs',
  905. CONTENT_SELECTOR: '#user-info div.tab-content',
  906. callback: null,
  907. $content: null,
  908. context: null,
  909. $tab: null,
  910. /**
  911. * Creates a new WazeWrap.Interface.Tab. The tab is appended to the WME
  912. * editor sidebar and contains the passed HTML content.
  913. * @class
  914. * @name WazeWrap.Interface.Tab
  915. * @param {String} name The name of the tab. Should not contain any
  916. * special characters.
  917. * @param {String} content The HTML content of the tab.
  918. * @param {Function} [callback] A function to call upon successfully
  919. * appending the tab.
  920. * @param {Object} [context] The context in which to call the callback
  921. * function.
  922. * @return {WazeWrap.Interface.Tab} The new tab object.
  923. * @example //Creates new tab and adds it to the page.
  924. * new WazeWrap.Interface.Tab('thebestscriptever', '<div>Hello World!</div>');
  925. */
  926. initialize: function (name, content, callback, context) {
  927. var idName, i = 0;
  928. if (name && 'string' === typeof name &&
  929. content && 'string' === typeof content) {
  930. if (callback && 'function' === typeof callback) {
  931. this.callback = callback;
  932. this.context = context || callback;
  933. }
  934. /* Sanitize name for html id attribute */
  935. idName = name.toLowerCase().replace(/[^a-z-_]/g, '');
  936. /* Make sure id will be unique on page */
  937. while (
  938. $('#sidepanel-' + (i ? idName + i : idName)).length > 0) {
  939. i++;
  940. }
  941. if (i) {
  942. idName = idName + i;
  943. }
  944. /* Create tab and content */
  945. this.$tab = $('<li/>')
  946. .append($('<a/>')
  947. .attr({
  948. 'href': '#sidepanel-' + idName,
  949. 'data-toggle': 'tab',
  950. })
  951. .text(name));
  952. this.$content = $('<div/>')
  953. .addClass('tab-pane')
  954. .attr('id', 'sidepanel-' + idName)
  955. .html(content);
  956.  
  957. this.appendTab();
  958. }
  959. },
  960.  
  961. append: function (content) {
  962. this.$content.append(content);
  963. },
  964.  
  965. appendTab: function () {
  966. WazeWrap.Util.waitForElement(
  967. this.TAB_SELECTOR + ',' + this.CONTENT_SELECTOR,
  968. function () {
  969. $(this.TAB_SELECTOR).append(this.$tab);
  970. $(this.CONTENT_SELECTOR).first().append(this.$content);
  971. if (this.callback) {
  972. this.callback.call(this.context);
  973. }
  974. }, this);
  975. },
  976.  
  977. clearContent: function () {
  978. this.$content.empty();
  979. },
  980.  
  981. destroy: function () {
  982. this.$tab.remove();
  983. this.$content.remove();
  984. }
  985. });
  986. };
  987.  
  988. }.call(this));

QingJ © 2025

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