🏠 Home 

WME ClickSaver

Various UI changes to make editing faster and easier.

  1. // ==UserScript==
  2. // @name WME ClickSaver
  3. // @namespace https://greasyfork.org/users/45389
  4. // @version 2025.03.14.002
  5. // @description Various UI changes to make editing faster and easier.
  6. // @author MapOMatic
  7. // @include /^https:\/\/(www|beta)\.waze\.com\/(?!user\/)(.{2,6}\/)?editor\/?.*$/
  8. // @license GNU GPLv3
  9. // @connect sheets.googleapis.com
  10. // @connect greasyfork.org
  11. // @contributionURL https://github.com/WazeDev/Thank-The-Authors
  12. // @grant GM_xmlhttpRequest
  13. // @grant GM_addElement
  14. // @require https://greasyfork.org/scripts/24851-wazewrap/code/WazeWrap.js
  15. // @require https://update.greasyfork.org/scripts/509664/WME%20Utils%20-%20Bootstrap.js
  16. // ==/UserScript==
  17. /* global I18n */
  18. /* global WazeWrap */
  19. /* global bootstrap */
  20. /* eslint-disable max-classes-per-file */
  21. (function main() {
  22. 'use strict';
  23. const updateMessage = 'New: Option to hide road type buttons in Compact mode (thanks to LihtsaltMats!)';
  24. const scriptName = GM_info.script.name;
  25. const scriptVersion = GM_info.script.version;
  26. const downloadUrl = 'https://greasyfork.org/scripts/369629-wme-clicksaver/code/WME%20ClickSaver.user.js';
  27. const forumUrl = 'https://www.waze.com/forum/viewtopic.php?f=819&t=199894';
  28. const translationsUrl = 'https://sheets.googleapis.com/v4/spreadsheets/1ZlE9yhNncP9iZrPzFFa-FCtYuK58wNOEcmKqng4sH1M/values/ClickSaver';
  29. const apiKey = 'YTJWNVBVRkplbUZUZVVGMFl6aFVjMjVOTW0wNU5GaG5kVE40TUZoNWJVZEhWbU5rUjNacVdtdFlWUT09';
  30. const DEC = s => atob(atob(s));
  31. let sdk;
  32. // This function is injected into the page.
  33. async function clicksaver(argsObject) {
  34. /* eslint-disable object-curly-newline */
  35. const roadTypeDropdownSelector = 'wz-select[name="roadType"]';
  36. const roadTypeChipSelector = 'wz-chip-select[class="road-type-chip-select"]';
  37. // const PARKING_SPACES_DROPDOWN_SELECTOR = 'select[name="estimatedNumberOfSpots"]';
  38. // const PARKING_COST_DROPDOWN_SELECTOR = 'select[name="costType"]';
  39. const settingsStoreName = 'clicksaver_settings';
  40. const defaultTranslation = {
  41. roadTypeButtons: {
  42. St: { text: 'St' },
  43. PS: { text: 'PS' },
  44. mH: { text: 'mH' },
  45. MH: { text: 'MH' },
  46. Fw: { text: 'Fw' },
  47. Rmp: { text: 'Rmp' },
  48. OR: { text: 'OR' },
  49. PLR: { text: 'PLR' },
  50. PR: { text: 'PR' },
  51. Fer: { text: 'Fer' },
  52. WT: { text: 'WT' },
  53. PB: { text: 'PB' },
  54. Sw: { text: 'Sw' },
  55. RR: { text: 'RR' },
  56. RT: { text: 'RT' },
  57. Pw: { text: 'Pw' }
  58. },
  59. prefs: {
  60. dropdownHelperGroup: 'DROPDOWN HELPERS',
  61. roadTypeButtons: 'Add road type buttons',
  62. useOldRoadColors: 'Use old road colors (requires refresh)',
  63. setStreetCityToNone: 'Set Street/City to None (new seg\'s only)',
  64. // eslint-disable-next-line camelcase
  65. setStreetCityToNone_Title: 'NOTE: Only works if connected directly or indirectly'
  66. + ' to a segment with State / Country already set.',
  67. setCityToConnectedSegCity: 'Set City to connected segment\'s City',
  68. parkingCostButtons: 'Add PLA cost buttons',
  69. parkingSpacesButtons: 'Add PLA estimated spaces buttons',
  70. timeSaversGroup: 'TIME SAVERS',
  71. discussionForumLinkText: 'Discussion Forum',
  72. showAddAltCityButton: 'Show "Add alt city" button',
  73. showSwapDrivingWalkingButton: 'Show "Swap driving<->walking segment type" button',
  74. // eslint-disable-next-line camelcase
  75. showSwapDrivingWalkingButton_Title: 'Swap between driving-type and walking-type segments. WARNING! This will DELETE and recreate the segment. Nodes may need to be reconnected.',
  76. showSwitchStreetNamesButton: 'Show swap primary and alternative street name button',
  77. addCompactColors: 'Add colors to compact mode road type buttons',
  78. hideUncheckedRoadTypeButtons: 'Hide unchecked road type buttons in compact mode'
  79. },
  80. swapSegmentTypeWarning: 'This will DELETE the segment and recreate it. Any speed data will be lost, and nodes will need to be reconnected. This message will only be displayed once. Continue?',
  81. // eslint-disable-next-line camelcase
  82. swapSegmentTypeError_Paths: 'Paths must be removed from segment before changing between driving and pedestrian road type.',
  83. addAltCityButtonText: 'Add alt city'
  84. };
  85. // Road types defined in the WME SDK documentation
  86. const wmeRoadType = {
  87. ALLEY: 22,
  88. FERRY: 15,
  89. FREEWAY: 3,
  90. MAJOR_HIGHWAY: 6,
  91. MINOR_HIGHWAY: 7,
  92. OFF_ROAD: 8,
  93. PARKING_LOT_ROAD: 20,
  94. PEDESTRIAN_BOARDWALK: 10,
  95. PRIMARY_STREET: 2,
  96. PRIVATE_ROAD: 17,
  97. RAILROAD: 18,
  98. RAMP: 4,
  99. RUNWAY_TAXIWAY: 19,
  100. STAIRWAY: 16,
  101. STREET: 1,
  102. WALKING_TRAIL: 5,
  103. WALKWAY: 9
  104. };
  105. const roadTypeSettings = {
  106. St: { id: wmeRoadType.STREET, wmeColor: '#ffffeb', svColor: '#ffffff', category: 'streets', visible: true },
  107. PS: { id: wmeRoadType.PRIMARY_STREET, wmeColor: '#f0ea58', svColor: '#cba12e', category: 'streets', visible: true },
  108. Pw: { id: wmeRoadType.ALLEY, wmeColor: '#64799a', svColor: '#64799a', category: 'streets', visible: false },
  109. mH: { id: wmeRoadType.MINOR_HIGHWAY, wmeColor: '#69bf88', svColor: '#ece589', category: 'highways', visible: true },
  110. MH: { id: wmeRoadType.MAJOR_HIGHWAY, wmeColor: '#45b8d1', svColor: '#c13040', category: 'highways', visible: true },
  111. Fw: { id: wmeRoadType.FREEWAY, wmeColor: '#c577d2', svColor: '#387fb8', category: 'highways', visible: false },
  112. Rmp: { id: wmeRoadType.RAMP, wmeColor: '#b3bfb3', svColor: '#58c53b', category: 'highways', visible: false },
  113. OR: { id: wmeRoadType.OFF_ROAD, wmeColor: '#867342', svColor: '#82614a', category: 'otherDrivable', visible: false },
  114. PLR: { id: wmeRoadType.PARKING_LOT_ROAD, wmeColor: '#ababab', svColor: '#2282ab', category: 'otherDrivable', visible: true },
  115. PR: { id: wmeRoadType.PRIVATE_ROAD, wmeColor: '#beba6c', svColor: '#00ffb3', category: 'otherDrivable', visible: true },
  116. Fer: { id: wmeRoadType.FERRY, wmeColor: '#d7d8f8', svColor: '#ff8000', category: 'otherDrivable', visible: false },
  117. RR: { id: wmeRoadType.RAILROAD, wmeColor: '#c62925', svColor: '#ffffff', category: 'nonDrivable', visible: false },
  118. RT: { id: wmeRoadType.RUNWAY_TAXIWAY, wmeColor: '#ffffff', svColor: '#00ff00', category: 'nonDrivable', visible: false },
  119. WT: { id: wmeRoadType.WALKING_TRAIL, wmeColor: '#b0a790', svColor: '#00ff00', category: 'pedestrian', visible: false },
  120. PB: { id: wmeRoadType.PEDESTRIAN_BOARDWALK, wmeColor: '#9a9a9a', svColor: '#0000ff', category: 'pedestrian', visible: false },
  121. Sw: { id: wmeRoadType.STAIRWAY, wmeColor: '#999999', svColor: '#b700ff', category: 'pedestrian', visible: false }
  122. };
  123. /* eslint-enable object-curly-newline */
  124. let _settings = {};
  125. let trans; // Translation object
  126. // function log(message) {
  127. // console.log('ClickSaver:', message);
  128. // }
  129. function logDebug(message) {
  130. console.debug('ClickSaver:', message);
  131. }
  132. // function logWarning(message) {
  133. // console.warn('ClickSaver:', message);
  134. // }
  135. // function logError(message) {
  136. // console.error('ClickSaver:', message);
  137. // }
  138. function isChecked(checkboxId) {
  139. return $(`#${checkboxId}`).is(':checked');
  140. }
  141. function isSwapPedestrianPermitted() {
  142. const userInfo = sdk.State.getUserInfo();
  143. const rank = userInfo.rank + 1;
  144. return rank >= 4 || (rank === 3 && userInfo.isAreaManager);
  145. }
  146. function setChecked(checkboxId, checked) {
  147. $(`#${checkboxId}`).prop('checked', checked);
  148. }
  149. function loadSettingsFromStorage() {
  150. const loadedSettings = $.parseJSON(localStorage.getItem(settingsStoreName));
  151. const defaultSettings = {
  152. lastVersion: null,
  153. roadButtons: true,
  154. roadTypeButtons: ['St', 'PS', 'mH', 'MH', 'Fw', 'Rmp', 'PLR', 'PR', 'PB'],
  155. parkingCostButtons: true,
  156. parkingSpacesButtons: true,
  157. setNewPLRStreetToNone: true,
  158. setNewPLRCity: true,
  159. setNewPRStreetToNone: false,
  160. setNewPRCity: false,
  161. setNewRRStreetToNone: true, // added by jm6087
  162. setNewRRCity: false, // added by jm6087
  163. setNewPBStreetToNone: true, // added by jm6087
  164. setNewPBCity: true, // added by jm6087
  165. setNewORStreetToNone: false,
  166. setNewORCity: false,
  167. addAltCityButton: true,
  168. addSwapPedestrianButton: false,
  169. useOldRoadColors: false,
  170. warnOnPedestrianTypeSwap: true,
  171. addCompactColors: true,
  172. addSwitchPrimaryNameButton: false,
  173. shortcuts: {}
  174. };
  175. _settings = { ...defaultSettings, ...loadedSettings };
  176. setChecked('csRoadTypeButtonsCheckBox', _settings.roadButtons);
  177. if (_settings.roadTypeButtons) {
  178. Object.keys(roadTypeSettings).forEach(roadTypeAbbr1 => {
  179. setChecked(`cs${roadTypeAbbr1}CheckBox`, _settings.roadTypeButtons.indexOf(roadTypeAbbr1) !== -1);
  180. });
  181. }
  182. if (_settings.roadButtons) {
  183. $('.csRoadTypeButtonsCheckBoxContainer').show();
  184. } else {
  185. $('.csRoadTypeButtonsCheckBoxContainer').hide();
  186. }
  187. // setChecked('csParkingSpacesButtonsCheckBox', _settings.parkingSpacesButtons);
  188. // setChecked('csParkingCostButtonsCheckBox', _settings.parkingCostButtons);
  189. setChecked('csSetNewPLRCityCheckBox', _settings.setNewPLRCity);
  190. setChecked('csClearNewPLRCheckBox', _settings.setNewPLRStreetToNone);
  191. setChecked('csSetNewPRCityCheckBox', _settings.setNewPRCity);
  192. setChecked('csClearNewPRCheckBox', _settings.setNewPRStreetToNone);
  193. setChecked('csSetNewRRCityCheckBox', _settings.setNewRRCity);
  194. setChecked('csClearNewRRCheckBox', _settings.setNewRRStreetToNone); // added by jm6087
  195. setChecked('csSetNewPBCityCheckBox', _settings.setNewPBCity);
  196. setChecked('csClearNewPBCheckBox', _settings.setNewPBStreetToNone); // added by jm6087
  197. setChecked('csSetNewORCityCheckBox', _settings.setNewORCity);
  198. setChecked('csClearNewORCheckBox', _settings.setNewORStreetToNone);
  199. setChecked('csUseOldRoadColorsCheckBox', _settings.useOldRoadColors);
  200. setChecked('csAddAltCityButtonCheckBox', _settings.addAltCityButton);
  201. setChecked('csAddSwapPedestrianButtonCheckBox', _settings.addSwapPedestrianButton);
  202. setChecked('csAddCompactColorsCheckBox', _settings.addCompactColors);
  203. setChecked('csAddSwitchPrimaryNameCheckBox', _settings.addSwitchPrimaryNameButton);
  204. setChecked('csHideUncheckedRoadTypeButtonsCheckBox', _settings.hideUncheckedRoadTypeButtons);
  205. }
  206. function saveSettingsToStorage() {
  207. const settings = {
  208. lastVersion: argsObject.scriptVersion,
  209. roadButtons: _settings.roadButtons,
  210. parkingCostButtons: _settings.parkingCostButtons,
  211. parkingSpacesButtons: _settings.parkingSpacesButtons,
  212. setNewPLRCity: _settings.setNewPLRCity,
  213. setNewPLRStreetToNone: _settings.setNewPLRStreetToNone,
  214. setNewPRCity: _settings.setNewPRCity,
  215. setNewPRStreetToNone: _settings.setNewPRStreetToNone,
  216. setNewRRCity: _settings.setNewRRCity,
  217. setNewRRStreetToNone: _settings.setNewRRStreetToNone,
  218. setNewPBCity: _settings.setNewPBCity,
  219. setNewPBStreetToNone: _settings.setNewPBStreetToNone,
  220. setNewORCity: _settings.setNewORCity,
  221. setNewORStreetToNone: _settings.setNewORStreetToNone,
  222. useOldRoadColors: _settings.useOldRoadColors,
  223. addAltCityButton: _settings.addAltCityButton,
  224. addSwapPedestrianButton: _settings.addSwapPedestrianButton,
  225. warnOnPedestrianTypeSwap: _settings.warnOnPedestrianTypeSwap,
  226. addCompactColors: _settings.addCompactColors,
  227. addSwitchPrimaryNameButton: _settings.addSwitchPrimaryNameButton,
  228. hideUncheckedRoadTypeButtons: _settings.hideUncheckedRoadTypeButtons,
  229. shortcuts: {}
  230. };
  231. sdk.Shortcuts.getAllShortcuts().forEach(shortcut => {
  232. settings.shortcuts[shortcut.shortcutId] = shortcut.shortcutKeys;
  233. });
  234. settings.roadTypeButtons = [];
  235. Object.keys(roadTypeSettings).forEach(roadTypeAbbr => {
  236. if (_settings.roadTypeButtons.indexOf(roadTypeAbbr) !== -1) {
  237. settings.roadTypeButtons.push(roadTypeAbbr);
  238. }
  239. });
  240. localStorage.setItem(settingsStoreName, JSON.stringify(settings));
  241. logDebug('Settings saved');
  242. }
  243. function isPedestrianTypeSegment(segment) {
  244. const pedRoadTypes = Object.values(roadTypeSettings)
  245. .filter(roadType => roadType.category === 'pedestrian')
  246. .map(roadType => roadType.id);
  247. return pedRoadTypes.includes(segment.roadType);
  248. }
  249. function getConnectedSegmentIDs(segmentId) {
  250. return [
  251. ...sdk.DataModel.Segments.getConnectedSegments({ segmentId, reverseDirection: false }),
  252. ...sdk.DataModel.Segments.getConnectedSegments({ segmentId, reverseDirection: true })
  253. ].map(segment => segment.id);
  254. }
  255. function getFirstConnectedSegmentAddress(segmentId) {
  256. const nonMatches = [];
  257. const segmentIDsToSearch = [segmentId];
  258. const hasAddress = id => !sdk.DataModel.Segments.getAddress({ segmentId: id }).isEmpty;
  259. while (segmentIDsToSearch.length > 0) {
  260. const startSegmentID = segmentIDsToSearch.pop();
  261. const connectedSegmentIDs = getConnectedSegmentIDs(startSegmentID);
  262. const hasAddrSegmentId = connectedSegmentIDs.find(hasAddress);
  263. if (hasAddrSegmentId) return sdk.DataModel.Segments.getAddress({ segmentId: hasAddrSegmentId });
  264. nonMatches.push(startSegmentID);
  265. connectedSegmentIDs.forEach(segmentID => {
  266. if (nonMatches.indexOf(segmentID) === -1 && segmentIDsToSearch.indexOf(segmentID) === -1) {
  267. segmentIDsToSearch.push(segmentID);
  268. }
  269. });
  270. }
  271. return null;
  272. }
  273. function setStreetAndCity(setCity) {
  274. const selection = sdk.Editing.getSelection();
  275. selection?.ids.forEach(segmentId => {
  276. if (sdk.DataModel.Segments.getAddress({ segmentId }).isEmpty) {
  277. const addr = getFirstConnectedSegmentAddress(segmentId);
  278. if (addr) {
  279. // Process the city
  280. const newCityProperties = {
  281. cityName: setCity && !addr.city?.isEmpty ? addr.city.name : '',
  282. countryId: addr.country.id,
  283. stateId: addr.state.id
  284. };
  285. let newCityId = sdk.DataModel.Cities.getCity(newCityProperties)?.id;
  286. if (newCityId == null) {
  287. newCityId = sdk.DataModel.Cities.addCity(newCityProperties);
  288. }
  289. // Process the street
  290. const newPrimaryStreetId = getOrCreateStreet('', newCityId).id;
  291. // Update the segment with the new street
  292. sdk.DataModel.Segments.updateAddress({ segmentId, primaryStreetId: newPrimaryStreetId });
  293. }
  294. }
  295. });
  296. }
  297. class WaitForElementError extends Error { }
  298. function waitForElem(selector) {
  299. return new Promise((resolve, reject) => {
  300. function checkIt(tries = 0) {
  301. if (tries < 150) { // try for about 3 seconds;
  302. const elem = document.querySelector(selector);
  303. setTimeout(() => {
  304. if (!elem) {
  305. checkIt(++tries);
  306. } else {
  307. resolve(elem);
  308. }
  309. }, 20);
  310. } else {
  311. reject(new WaitForElementError(`Element was not found within 3 seconds: ${selector}`));
  312. }
  313. }
  314. checkIt();
  315. });
  316. }
  317. async function waitForShadowElem(parentElemSelector, shadowElemSelectors) {
  318. const parentElem = await waitForElem(parentElemSelector);
  319. return new Promise((resolve, reject) => {
  320. shadowElemSelectors.forEach((shadowElemSelector, idx) => {
  321. function checkIt(parent, tries = 0) {
  322. if (tries < 150) { // try for about 3 seconds;
  323. const shadowElem = parent.shadowRoot.querySelector(shadowElemSelector);
  324. setTimeout(() => {
  325. if (!shadowElem) {
  326. checkIt(parent, ++tries);
  327. } else if (idx === shadowElemSelectors.length - 1) {
  328. resolve({ shadowElem, parentElem });
  329. } else {
  330. checkIt(shadowElem, 0);
  331. }
  332. }, 20);
  333. } else {
  334. reject(new WaitForElementError(`Shadow element was not found within 3 seconds: ${shadowElemSelector}`));
  335. }
  336. }
  337. checkIt(parentElem);
  338. });
  339. });
  340. }
  341. async function onAddAltCityButtonClick() {
  342. const segmentId = sdk.Editing.getSelection().ids[0];
  343. const addr = sdk.DataModel.Segments.getAddress({ segmentId });
  344. $('wz-button[class="add-alt-street-btn"]').click();
  345. await waitForElem('wz-autocomplete.alt-street-name');
  346. // Set the street name field
  347. let r###lt = await waitForShadowElem('wz-autocomplete.alt-street-name', ['wz-text-input']);
  348. r###lt.shadowElem.focus();
  349. r###lt.shadowElem.value = addr?.street?.name ?? '';
  350. // Clear the city name field
  351. r###lt = await waitForShadowElem('wz-autocomplete.alt-city-name', ['wz-text-input']);
  352. r###lt.shadowElem.focus();
  353. r###lt.shadowElem.value = null;
  354. }
  355. function onRoadTypeButtonClick(roadType) {
  356. const selection = sdk.Editing.getSelection();
  357. // Temporarily remove this while bugs are worked out.
  358. // WS.SDKMultiActionHack.groupActions(() => {
  359. selection?.ids.forEach(segmentId => {
  360. // Check for same roadType is necessary to prevent an error.
  361. if (sdk.DataModel.Segments.getById({ segmentId }).roadType !== roadType) {
  362. sdk.DataModel.Segments.updateSegment({ segmentId, roadType });
  363. }
  364. });
  365. if (roadType === roadTypeSettings.PLR.id && isChecked('csClearNewPLRCheckBox')) {
  366. setStreetAndCity(isChecked('csSetNewPLRCityCheckBox'));
  367. } else if (roadType === roadTypeSettings.PR.id && isChecked('csClearNewPRCheckBox')) {
  368. setStreetAndCity(isChecked('csSetNewPRCityCheckBox'));
  369. } else if (roadType === roadTypeSettings.RR.id && isChecked('csClearNewRRCheckBox')) {
  370. setStreetAndCity(isChecked('csSetNewRRCityCheckBox'));
  371. } else if (roadType === roadTypeSettings.PB && isChecked('csClearNewPBCheckBox')) {
  372. setStreetAndCity(isChecked('csSetNewPBCityCheckBox'));
  373. } else if (roadType === roadTypeSettings.OR.id && isChecked('csClearNewORCheckBox')) {
  374. setStreetAndCity(isChecked('csSetNewORCityCheckBox'));
  375. }
  376. // });
  377. }
  378. function addRoadTypeButtons() {
  379. const segmentId = sdk.Editing.getSelection()?.ids[0];
  380. if (segmentId == null) return;
  381. const sdkSeg = sdk.DataModel.Segments.getById({ segmentId });
  382. if (!sdkSeg) return;
  383. const isPed = isPedestrianTypeSegment(sdkSeg);
  384. const $dropDown = $(roadTypeDropdownSelector);
  385. $('#csRoadTypeButtonsContainer').remove();
  386. const $container = $('<div>', { id: 'csRoadTypeButtonsContainer', class: 'cs-rt-buttons-container', style: 'display: inline-table;' });
  387. const $street = $('<div>', { id: 'csStreetButtonContainer', class: 'cs-rt-buttons-group' });
  388. const $highway = $('<div>', { id: 'csHighwayButtonContainer', class: 'cs-rt-buttons-group' });
  389. const $otherDrivable = $('<div>', { id: 'csOtherDrivableButtonContainer', class: 'cs-rt-buttons-group' });
  390. const $nonDrivable = $('<div>', { id: 'csNonDrivableButtonContainer', class: 'cs-rt-buttons-group' });
  391. const $pedestrian = $('<div>', { id: 'csPedestrianButtonContainer', class: 'cs-rt-buttons-group' });
  392. const divs = {
  393. streets: $street,
  394. highways: $highway,
  395. otherDrivable: $otherDrivable,
  396. nonDrivable: $nonDrivable,
  397. pedestrian: $pedestrian
  398. };
  399. Object.keys(roadTypeSettings).forEach(roadTypeKey => {
  400. if (_settings.roadTypeButtons.includes(roadTypeKey)) {
  401. const roadTypeSetting = roadTypeSettings[roadTypeKey];
  402. const isDisabled = $dropDown[0].hasAttribute('disabled') && $dropDown[0].getAttribute('disabled') === 'true';
  403. if (!isDisabled && ((roadTypeSetting.category === 'pedestrian' && isPed) || (roadTypeSetting.category !== 'pedestrian' && !isPed))) {
  404. const $div = divs[roadTypeSetting.category];
  405. $div.append(
  406. $('<div>', {
  407. class: `btn cs-rt-button cs-rt-button-${roadTypeKey} btn-positive`,
  408. title: I18n.t('segment.road_types')[roadTypeSetting.id]
  409. })
  410. .text(trans.roadTypeButtons[roadTypeKey].text)
  411. .prop('checked', roadTypeSetting.visible)
  412. .data('rtId', roadTypeSetting.id)
  413. .click(function rtbClick() { onRoadTypeButtonClick($(this).data('rtId')); })
  414. );
  415. }
  416. }
  417. });
  418. if (isPed) {
  419. $container.append($pedestrian);
  420. } else {
  421. $container.append($street).append($highway).append($otherDrivable).append($nonDrivable);
  422. }
  423. $dropDown.before($container);
  424. }
  425. // Function to add an event listener to the chip select for the road type in compact mode
  426. function addCompactRoadTypeChangeEvents() {
  427. const chipSelect = document.getElementsByClassName('road-type-chip-select')[0];
  428. chipSelect.addEventListener('chipSelected', evt => {
  429. const rtValue = evt.detail.value;
  430. onRoadTypeButtonClick(rtValue);
  431. });
  432. }
  433. // Function to add road type colors to the chips in compact mode
  434. async function addCompactRoadTypeColors() {
  435. // TODO: Clean this up. Was combined from two functions.
  436. try {
  437. if (sdk.Settings.getUserSettings().isCompactMode
  438. && isChecked('csAddCompactColorsCheckBox')
  439. && sdk.Editing.getSelection()) {
  440. const useOldColors = _settings.useOldRoadColors;
  441. await waitForElem('.road-type-chip-select wz-checkable-chip');
  442. $('.road-type-chip-select wz-checkable-chip').addClass('cs-compact-button');
  443. Object.values(roadTypeSettings).forEach(roadType => {
  444. const bgColor = useOldColors ? roadType.svColor : roadType.wmeColor;
  445. const rtChip = $(`.road-type-chip-select wz-checkable-chip[value=${roadType.id}]`);
  446. if (rtChip.length !== 1) return;
  447. waitForShadowElem(`.road-type-chip-select wz-checkable-chip[value='${roadType.id}']`, ['div']).then(r###lt => {
  448. const $elem = $(r###lt.shadowElem);
  449. const padding = $elem.hasClass('checked') ? '0px 3px' : '0px 4px';
  450. $elem.css({ backgroundColor: bgColor, padding, color: 'black' });
  451. });
  452. });
  453. const r###lt = await waitForShadowElem('.road-type-chip-select wz-checkable-chip[checked=""]', ['div']);
  454. $(r###lt.shadowElem).css({ border: 'black 2px solid', padding: '0px 3px' });
  455. $('.road-type-chip-select wz-checkable-chip').each(function updateRoadTypeChip() {
  456. const style = {};
  457. if (this.getAttribute('checked') === 'false') {
  458. style.border = '';
  459. style.padding = '0px 4px';
  460. } else {
  461. style.border = 'black 2px solid';
  462. style.padding = '0px 3px';
  463. }
  464. $(this.shadowRoot.querySelector('div')).css(style);
  465. });
  466. }
  467. } catch (ex) {
  468. if (ex instanceof WaitForElementError) {
  469. // waitForElem will throw an error if Undo causes a deselection. Ignore it.
  470. } else {
  471. throw ex;
  472. }
  473. }
  474. }
  475. // function isPLA(item) {
  476. // return (item.model.type === 'venue') && item.model.attributes.categories.includes('PARKING_LOT');
  477. // }
  478. // function addParkingSpacesButtons() {
  479. // const $dropDown = $(PARKING_SPACES_DROPDOWN_SELECTOR);
  480. // const selItems = W.selectionManager.getSelectedFeatures();
  481. // const item = selItems[0];
  482. // // If it's not a PLA, exit.
  483. // if (!isPLA(item)) return;
  484. // $('#csParkingSpacesContainer').remove();
  485. // const $div = $('<div>', { id: 'csParkingSpacesContainer' });
  486. // const dropdownDisabled = $dropDown.attr('disabled') === 'disabled';
  487. // const optionNodes = $(`${PARKING_SPACES_DROPDOWN_SELECTOR} option`);
  488. // for (let i = 0; i < optionNodes.length; i++) {
  489. // const $option = $(optionNodes[i]);
  490. // const text = $option.text();
  491. // const selected = $option.val() === $dropDown.val();
  492. // $div.append(
  493. // // TODO css
  494. // $('<div>', {
  495. // class: `btn waze-btn waze-btn-white${selected ? ' waze-btn-blue' : ''}${dropdownDisabled ? ' disabled' : ''}`,
  496. // style: 'margin-bottom: 5px; height: 22px; padding: 2px 8px 0px 8px; margin-right: 3px;'
  497. // })
  498. // .text(text)
  499. // .data('val', $option.val())
  500. // // eslint-disable-next-line func-names
  501. // .hover(() => { })
  502. // .click(function onParkingSpacesButtonClick() {
  503. // if (!dropdownDisabled) {
  504. // $(PARKING_SPACES_DROPDOWN_SELECTOR).val($(this).data('val')).change();
  505. // addParkingSpacesButtons();
  506. // }
  507. // })
  508. // );
  509. // }
  510. // $dropDown.before($div);
  511. // $dropDown.hide();
  512. // }
  513. // function addParkingCostButtons() {
  514. // const $dropDown = $(PARKING_COST_DROPDOWN_SELECTOR);
  515. // const selItems = W.selectionManager.getSelectedFeatures();
  516. // const item = selItems[0];
  517. // // If it's not a PLA, exit.
  518. // if (!isPLA(item)) return;
  519. // $('#csParkingCostContainer').remove();
  520. // const $div = $('<div>', { id: 'csParkingCostContainer' });
  521. // const dropdownDisabled = $dropDown.attr('disabled') === 'disabled';
  522. // const optionNodes = $(`${PARKING_COST_DROPDOWN_SELECTOR} option`);
  523. // for (let i = 0; i < optionNodes.length; i++) {
  524. // const $option = $(optionNodes[i]);
  525. // const text = $option.text();
  526. // const selected = $option.val() === $dropDown.val();
  527. // $div.append(
  528. // $('<div>', {
  529. // class: `btn waze-btn waze-btn-white${selected ? ' waze-btn-blue' : ''}${dropdownDisabled ? ' disabled' : ''}`,
  530. // // TODO css
  531. // style: 'margin-bottom: 5px; height: 22px; padding: 2px 8px 0px 8px; margin-right: 4px;'
  532. // })
  533. // .text(text !== '' ? text : '?')
  534. // .data('val', $option.val())
  535. // // eslint-disable-next-line func-names
  536. // .hover(() => { })
  537. // .click(function onParkingCostButtonClick() {
  538. // if (!dropdownDisabled) {
  539. // $(PARKING_COST_DROPDOWN_SELECTOR).val($(this).data('val')).change();
  540. // addParkingCostButtons();
  541. // }
  542. // })
  543. // );
  544. // }
  545. // $dropDown.before($div);
  546. // $dropDown.hide();
  547. // }
  548. function addAddAltCityButton() {
  549. // Only show the button if every segment has the same primary city and street.
  550. if (!selectedPrimaryStreetsAreEqual()) {
  551. return;
  552. }
  553. const id = 'csAddAltCityButton';
  554. if ($(`#${id}`).length === 0) {
  555. $('div.address-edit').prev('wz-label').append(
  556. $('<a>', {
  557. href: '#',
  558. // TODO css
  559. style: 'float: right;text-transform: none;'
  560. + 'font-family: "Helvetica Neue", Helvetica, "Open Sans", sans-serif;color: #26bae8;'
  561. + 'font-weight: normal;'
  562. }).text(trans.addAltCityButtonText).click(onAddAltCityButtonClick)
  563. );
  564. }
  565. }
  566. async function addSwitchPrimaryNameButton() {
  567. if (!isChecked('csAddSwitchPrimaryNameCheckBox')) {
  568. return;
  569. }
  570. if (!selectedPrimaryStreetsAreEqual() || !selectedAltStreetsAreEqual()) {
  571. return;
  572. }
  573. await waitForElem('.alt-streets-control');
  574. // eslint-disable-next-line func-names
  575. $('span.alt-street-preview').each(function() {
  576. const id = 'csAddSwitchPrimaryName';
  577. const altStreetId = Number($(this).attr('data-id'));
  578. const switchingIconElement = $(this).find(`#${id}`);
  579. if (streetEqualsPrimaryStreetName(altStreetId)) {
  580. switchingIconElement.remove();
  581. return;
  582. }
  583. const switchingIconExists = switchingIconElement.length > 0;
  584. if (switchingIconExists) {
  585. return;
  586. }
  587. const switchStreetNameButton = $('<i>', {
  588. id,
  589. class: 'w-icon w-icon-arrow-up alt-edit-button'
  590. });
  591. $(this).append(switchStreetNameButton);
  592. switchStreetNameButton.click(onSwitchStreetNamesClick);
  593. });
  594. }
  595. function onSwitchStreetNamesClick() {
  596. const selectedSegments = getSelectedSegments();
  597. const currentPrimaryStreet = sdk.DataModel.Segments.getAddress({ segmentId: selectedSegments[0] });
  598. const currentAltStreets = currentPrimaryStreet.altStreets.map(street => street.street);
  599. const selectedStreetId = Number($(this).parent().attr('data-id'));
  600. const newPrimary = currentAltStreets
  601. .find(street => street.id === selectedStreetId);
  602. // WS.SDKMultiActionHack.groupActions(() => {
  603. const newPrimaryStreet = getOrCreateStreet(newPrimary.name, currentPrimaryStreet.city.id);
  604. const primaryToAltStreet = getOrCreateStreet(currentPrimaryStreet.street.name, newPrimary.cityId);
  605. const newAltStreetsIds = currentAltStreets
  606. .map(alt => alt.id)
  607. .filter(id => id !== selectedStreetId);
  608. newAltStreetsIds.push(primaryToAltStreet.id);
  609. selectedSegments.forEach(segmentId => sdk.DataModel.Segments.updateAddress({
  610. segmentId,
  611. primaryStreetId: newPrimaryStreet.id,
  612. alternateStreetIds: newAltStreetsIds
  613. }));
  614. // });
  615. }
  616. function addSwapPedestrianButton() { // Added displayMode argument to identify compact vs. regular mode.
  617. const id = 'csSwapPedestrianContainer';
  618. $(`#${id}`).remove();
  619. const selection = sdk.Editing.getSelection();
  620. if (selection?.ids.length === 1 && selection.objectType === 'segment') {
  621. // TODO css
  622. const $container = $('<div>', { id, style: 'white-space: nowrap;float: right;display: inline;' });
  623. const $button = $('<div>', {
  624. id: 'csBtnSwapPedestrianRoadType',
  625. title: '',
  626. // TODO css
  627. style: 'display:inline-block;cursor:pointer;'
  628. });
  629. $button.append('<i class="w-icon w-icon-streetview w-icon-lg"></i><i class="fa fa-arrows-h fa-lg" style="color: #e84545;vertical-align: top;"></i><i class="w-icon w-icon-car w-icon-lg"></i>')
  630. .attr({
  631. title: trans.prefs.showSwapDrivingWalkingButton_Title
  632. });
  633. $container.append($button);
  634. // Insert swap button in the correct location based on display mode.
  635. const $label = $('#segment-edit-general > form > div > div.road-type-control > wz-label');
  636. $label.css({ display: 'inline' }).append($container);
  637. $('#csBtnSwapPedestrianRoadType').click(onSwapPedestrianButtonClick);
  638. }
  639. }
  640. function onSwapPedestrianButtonClick() {
  641. if (_settings.warnOnPedestrianTypeSwap) {
  642. _settings.warnOnPedestrianTypeSwap = false;
  643. saveSettingsToStorage();
  644. if (!confirm(trans.swapSegmentTypeWarning)) {
  645. return;
  646. }
  647. }
  648. const originalSegment = sdk.DataModel.Segments.getById({ segmentId: sdk.Editing.getSelection().ids[0] });
  649. // Copy the selected segment geometry and attributes, then delete it.
  650. const oldPrimaryStreetId = originalSegment.primaryStreetId;
  651. const oldAltStreetIds = originalSegment.alternateStreetIds;
  652. // WS.SDKMultiActionHack.groupActions(() => {
  653. const newRoadType = isPedestrianTypeSegment(originalSegment) ? wmeRoadType.STREET : wmeRoadType.WALKING_TRAIL;
  654. try {
  655. sdk.DataModel.Segments.deleteSegment({ segmentId: originalSegment.id });
  656. } catch (ex) {
  657. if (ex instanceof sdk.Errors.InvalidStateError) {
  658. WazeWrap.Alerts.error(scriptName, 'Something prevents this segment from being deleted.');
  659. return;
  660. }
  661. }
  662. // create the replacement segment in the other segment type (pedestrian -> road & vice versa)
  663. const newSegmentId = sdk.DataModel.Segments.addSegment({ geometry: originalSegment.geometry, roadType: newRoadType });
  664. sdk.DataModel.Segments.updateAddress({
  665. segmentId: newSegmentId,
  666. primaryStreetId: oldPrimaryStreetId,
  667. alternateStreetIds: oldAltStreetIds
  668. });
  669. sdk.Editing.setSelection({ selection: { ids: [newSegmentId], objectType: 'segment' } });
  670. // });
  671. }
  672. function getSelectedSegments() {
  673. const selection = sdk.Editing.getSelection();
  674. if (selection?.objectType !== 'segment') {
  675. return null;
  676. }
  677. return selection.ids;
  678. }
  679. function selectedPrimaryStreetsAreEqual() {
  680. const selection = getSelectedSegments();
  681. if (!selection) {
  682. return false;
  683. }
  684. if (selection.length === 1) {
  685. return true;
  686. }
  687. const firstStreetId = sdk.DataModel.Segments.getAddress({ segmentId: selection[0] })?.street?.id;
  688. return selection
  689. .map(segmentId => sdk.DataModel.Segments.getAddress({ segmentId }))
  690. .every(addr => addr.street?.id === firstStreetId);
  691. }
  692. function selectedAltStreetsAreEqual() {
  693. const selection = getSelectedSegments();
  694. if (!selection) {
  695. return false;
  696. }
  697. const addresses = selection.map(segmentId => sdk.DataModel.Segments.getAddress({ segmentId }))
  698. .map(street => street.altStreets.map(altStreet => altStreet.street.id))
  699. .map(addr => new Set(addr));
  700. const firstAltAddresses = addresses[0];
  701. return addresses
  702. .every(address => address.size === firstAltAddresses.size && Array.from(address).every(value => firstAltAddresses.has(value)));
  703. }
  704. function getOrCreateStreet(streetName, cityId) {
  705. return sdk.DataModel.Streets.getStreet({ streetName, cityId })
  706. ?? sdk.DataModel.Streets.addStreet({ streetName, cityId });
  707. }
  708. function streetEqualsPrimaryStreetName(altStreetId) {
  709. const selection = getSelectedSegments();
  710. const primaryStreetName = selection
  711. .map(segmentId => sdk.DataModel.Segments.getAddress({ segmentId }))[0].street?.name;
  712. const selectedStreetName = sdk.DataModel.Streets.getById({ streetId: altStreetId })?.name;
  713. return primaryStreetName === selectedStreetName;
  714. }
  715. /* eslint-disable no-bitwise, no-mixed-operators */
  716. function shadeColor2(color, percent) {
  717. const f = parseInt(color.slice(1), 16);
  718. const t = percent < 0 ? 0 : 255;
  719. const p = percent < 0 ? percent * -1 : percent;
  720. const R = f >> 16;
  721. const G = f >> 8 & 0x00FF;
  722. const B = f & 0x0000FF;
  723. return `#${(0x1000000 + (Math.round((t - R) * p) + R) * 0x10000 + (Math.round((t - G) * p) + G)
  724. * 0x100 + (Math.round((t - B) * p) + B)).toString(16).slice(1)}`;
  725. }
  726. /* eslint-enable no-bitwise, no-mixed-operators */
  727. function buildRoadTypeButtonCss() {
  728. const lines = [];
  729. const useOldColors = _settings.useOldRoadColors;
  730. Object.keys(roadTypeSettings).forEach(roadTypeAbbr => {
  731. const roadType = roadTypeSettings[roadTypeAbbr];
  732. const bgColor = useOldColors ? roadType.svColor : roadType.wmeColor;
  733. let output = `.cs-rt-buttons-container .cs-rt-button-${roadTypeAbbr} {background-color:${
  734. bgColor};box-shadow:0 2px ${shadeColor2(bgColor, -0.5)};border-color:${shadeColor2(bgColor, -0.15)};}`;
  735. output += ` .cs-rt-buttons-container .cs-rt-button-${roadTypeAbbr}:hover {background-color:${
  736. shadeColor2(bgColor, 0.2)}}`;
  737. lines.push(output);
  738. });
  739. return lines.join(' ');
  740. }
  741. function injectCss() {
  742. const css = [
  743. // Road type button formatting
  744. '.csRoadTypeButtonsCheckBoxContainer {margin-left:15px;}',
  745. '.cs-rt-buttons-container {margin-bottom:5px;height:21px;}',
  746. '.cs-rt-buttons-container .cs-rt-button {font-size:11px;line-height:20px;color:black;padding:0px 4px;height:20px;'
  747. + 'margin-right:2px;border-style:solid;border-width:1px;}',
  748. buildRoadTypeButtonCss(),
  749. '.btn.cs-rt-button:active {box-shadow:none;transform:translateY(2px)}',
  750. 'div .cs-rt-buttons-group {float:left; margin: 0px 5px 5px 0px;}',
  751. '#sidepanel-clicksaver .controls-container {padding:0px;}',
  752. '#sidepanel-clicksaver .controls-container label {white-space: normal;}',
  753. '#sidepanel-clicksaver {font-size:13px;}',
  754. // Compact moad road type button formatting.
  755. '.cs-compact-button[checked="false"] {opacity: 0.65;}',
  756. // Lock button formatting
  757. '.cs-group-label {font-size: 11px; width: 100%; font-family: Poppins, sans-serif;'
  758. + ' text-transform: uppercase; font-weight: 700; color: #354148; margin-bottom: 6px;}'
  759. ].join(' ');
  760. $(`<style type="text/css">${css}</style>`).appendTo('head');
  761. }
  762. function createSettingsCheckbox(id, settingName, labelText, titleText, divCss, labelCss, optionalAttributes) {
  763. const $container = $('<div>', { class: 'controls-container' });
  764. const $input = $('<input>', {
  765. type: 'checkbox', class: 'csSettingsCheckBox', name: id, id, 'data-setting-name': settingName
  766. }).appendTo($container);
  767. const $label = $('<label>', { for: id }).text(labelText).appendTo($container);
  768. // TODO css
  769. if (divCss) $container.css(divCss);
  770. // TODO css
  771. if (labelCss) $label.css(labelCss);
  772. if (titleText) $container.attr({ title: titleText });
  773. if (optionalAttributes) $input.attr(optionalAttributes);
  774. return $container;
  775. }
  776. async function initUserPanel() {
  777. const $roadTypesDiv = $('<div>', { class: 'csRoadTypeButtonsCheckBoxContainer' });
  778. $roadTypesDiv.append(
  779. createSettingsCheckbox('csUseOldRoadColorsCheckBox', 'useOldRoadColors', trans.prefs.useOldRoadColors)
  780. );
  781. Object.keys(roadTypeSettings).forEach(roadTypeAbbr => {
  782. const roadType = roadTypeSettings[roadTypeAbbr];
  783. const id = `cs${roadTypeAbbr}CheckBox`;
  784. const title = I18n.t('segment.road_types')[roadType.id];
  785. $roadTypesDiv.append(
  786. createSettingsCheckbox(id, 'roadType', title, null, null, null, {
  787. 'data-road-type': roadTypeAbbr
  788. })
  789. );
  790. if (['PLR', 'PR', 'RR', 'PB', 'OR'].includes(roadTypeAbbr)) { // added RR & PB by jm6087
  791. $roadTypesDiv.append(
  792. // TODO css
  793. createSettingsCheckbox(
  794. `csClearNew${roadTypeAbbr}CheckBox`,
  795. `setNew${roadTypeAbbr}StreetToNone`,
  796. trans.prefs.setStreetCityToNone,
  797. trans.prefs.setStreetCityToNone_Title,
  798. { paddingLeft: '20px', marginRight: '4px' },
  799. { fontStyle: 'italic' }
  800. ),
  801. createSettingsCheckbox(
  802. `csSetNew${roadTypeAbbr}CityCheckBox`,
  803. `setNew${roadTypeAbbr}City`,
  804. trans.prefs.setCityToConnectedSegCity,
  805. '',
  806. { paddingLeft: '30px', marginRight: '4px' },
  807. { fontStyle: 'italic' }
  808. )
  809. );
  810. }
  811. });
  812. const $panel = $('<div>', { id: 'sidepanel-clicksaver' }).append(
  813. $('<div>', { class: 'side-panel-section>' }).append(
  814. // TODO css
  815. $('<div>', { style: 'margin-bottom:8px;' }).append(
  816. $('<div>', { class: 'form-group' }).append(
  817. $('<label>', { class: 'cs-group-label' }).text(trans.prefs.dropdownHelperGroup),
  818. $('<div>').append(
  819. createSettingsCheckbox(
  820. 'csRoadTypeButtonsCheckBox',
  821. 'roadButtons',
  822. trans.prefs.roadTypeButtons
  823. )
  824. ).append($roadTypesDiv),
  825. createSettingsCheckbox(
  826. 'csAddCompactColorsCheckBox',
  827. 'addCompactColors',
  828. trans.prefs.addCompactColors
  829. ),
  830. createSettingsCheckbox(
  831. 'csHideUncheckedRoadTypeButtonsCheckBox',
  832. 'hideUncheckedRoadTypeButtons',
  833. trans.prefs.hideUncheckedRoadTypeButtons
  834. )
  835. ),
  836. $('<label>', { class: 'cs-group-label' }).text(trans.prefs.timeSaversGroup),
  837. $('<div>', { style: 'margin-bottom:8px;' }).append(
  838. createSettingsCheckbox(
  839. 'csAddAltCityButtonCheckBox',
  840. 'addAltCityButton',
  841. trans.prefs.showAddAltCityButton
  842. ),
  843. isSwapPedestrianPermitted() ? createSettingsCheckbox(
  844. 'csAddSwapPedestrianButtonCheckBox',
  845. 'addSwapPedestrianButton',
  846. trans.prefs.showSwapDrivingWalkingButton
  847. ) : '',
  848. createSettingsCheckbox(
  849. 'csAddSwitchPrimaryNameCheckBox',
  850. 'addSwitchPrimaryNameButton',
  851. trans.prefs.showSwitchStreetNamesButton
  852. )
  853. )
  854. )
  855. )
  856. );
  857. $panel.append(
  858. // TODO css
  859. $('<div>', { style: 'margin-top:20px;font-size:10px;color:#999999;' }).append(
  860. $('<div>').text(`v. ${argsObject.scriptVersion}${argsObject.scriptName.toLowerCase().includes('beta') ? ' beta' : ''}`),
  861. $('<div>').append(
  862. $('<a>', { href: argsObject.forumUrl, target: '__blank' }).text(trans.prefs.discussionForumLinkText)
  863. )
  864. )
  865. );
  866. const { tabLabel, tabPane } = await sdk.Sidebar.registerScriptTab();
  867. $(tabLabel).text('CS');
  868. $(tabPane).append($panel);
  869. // Decrease spacing around the tab contents.
  870. $(tabPane).parent().css({ 'padding-top': '0px', 'padding-left': '8px' });
  871. // Add change events
  872. $('#csRoadTypeButtonsCheckBox').change(function onRoadTypeButtonCheckChanged() {
  873. if (this.checked) {
  874. $('.csRoadTypeButtonsCheckBoxContainer').show();
  875. } else {
  876. $('.csRoadTypeButtonsCheckBoxContainer').hide();
  877. }
  878. saveSettingsToStorage();
  879. });
  880. $('.csSettingsCheckBox').change(function onSettingsCheckChanged() {
  881. const { checked } = this;
  882. const settingName = $(this).data('setting-name');
  883. if (settingName === 'roadType') {
  884. const roadType = $(this).data('road-type');
  885. const array = _settings.roadTypeButtons;
  886. const index = array.indexOf(roadType);
  887. if (checked && index === -1) {
  888. array.push(roadType);
  889. } else if (!checked && index !== -1) {
  890. array.splice(index, 1);
  891. }
  892. } else {
  893. _settings[settingName] = checked;
  894. }
  895. saveSettingsToStorage();
  896. });
  897. }
  898. function updateControls() {
  899. if ($(roadTypeDropdownSelector).length > 0) {
  900. if (isChecked('csRoadTypeButtonsCheckBox')) addRoadTypeButtons();
  901. }
  902. addCompactRoadTypeColors();
  903. if (isSwapPedestrianPermitted() && isChecked('csAddSwapPedestrianButtonCheckBox')) {
  904. addSwapPedestrianButton();
  905. }
  906. // if ($(PARKING_SPACES_DROPDOWN_SELECTOR).length > 0 && isChecked('csParkingSpacesButtonsCheckBox')) {
  907. // addParkingSpacesButtons(); // TODO - add option setting
  908. // }
  909. // if ($(PARKING_COST_DROPDOWN_SELECTOR).length > 0 && isChecked('csParkingCostButtonsCheckBox')) {
  910. // addParkingCostButtons(); // TODO - add option setting
  911. // }
  912. }
  913. function replaceWord(target, searchWord, replaceWithWord) {
  914. return target.replace(new RegExp(`\\b${searchWord}\\b`, 'g'), replaceWithWord);
  915. }
  916. function titleCase(word) {
  917. return word.charAt(0).toUpperCase() + word.substring(1).toLowerCase();
  918. }
  919. function mcCase(word) {
  920. return word.charAt(0).toUpperCase() + word.charAt(1).toLowerCase()
  921. + word.charAt(2).toUpperCase() + word.substring(3).toLowerCase();
  922. }
  923. function upperCase(word) {
  924. return word.toUpperCase();
  925. }
  926. function processSubstring(target, substringRegex, processFunction) {
  927. const substrings = target.match(substringRegex);
  928. if (substrings) {
  929. for (let idx = 0; idx < substrings.length; idx++) {
  930. const substring = substrings[idx];
  931. const newSubstring = processFunction(substring);
  932. target = replaceWord(target, substring, newSubstring);
  933. }
  934. }
  935. return target;
  936. }
  937. function onPaste(e) {
  938. const targetNode = e.target;
  939. if (targetNode.name === 'streetName' || targetNode.className.includes('street-name')) {
  940. // Get the text that's being pasted.
  941. let pastedText = e.clipboardData.getData('text/plain');
  942. // If pasting text in ALL CAPS...
  943. if (/^[^a-z]*$/.test(pastedText)) {
  944. [
  945. // Title case all words first.
  946. [/\b[a-zA-Z]+(?:'S)?\b/g, titleCase],
  947. // Then process special cases.
  948. [/\bMC\w+\b/ig, mcCase], // e.g. McCaulley
  949. [/\b(?:I|US|SH|SR|CH|CR|CS|PR|PS)\s*-?\s*\d+\w*\b/ig, upperCase], // e.g. US-25, US25
  950. /* eslint-disable-next-line max-len */
  951. [/\b(?:AL|AK|AS|AZ|AR|CA|CO|CT|DE|DC|FM|FL|GA|GU|HI|ID|IL|IN|IA|KS|KY|LA|ME|MH|MD|MA|MI|MN|MS|MO|MT|NE|NV|NH|NJ|NM|NY|NC|ND|MP|OH|OK|OR|PW|PA|PR|RI|SC|SD|TN|TX|UT|VT|VI|VA|WA|WV|WI|WY)\s*-?\s*\d+\w*\b/ig, upperCase], // e.g. WV-52
  952. [/\b(?:NE|NW|SE|SW)\b/ig, upperCase]
  953. ].forEach(item => {
  954. pastedText = processSubstring(pastedText, item[0], item[1]);
  955. });
  956. // Insert new text in the focused node.
  957. document.execCommand('insertText', false, pastedText);
  958. // Prevent the default paste behavior.
  959. e.preventDefault();
  960. return false;
  961. }
  962. }
  963. return true;
  964. }
  965. function getTranslationObject() {
  966. if (argsObject.useDefaultTranslation) {
  967. return defaultTranslation;
  968. }
  969. let locale = I18n.currentLocale().toLowerCase();
  970. if (!argsObject.translations.hasOwnProperty(locale)) {
  971. locale = 'en-us';
  972. }
  973. return argsObject.translations[locale];
  974. }
  975. function errorHandler(callback) {
  976. try {
  977. callback();
  978. } catch (ex) {
  979. console.error(`${argsObject.scriptName}:`, ex);
  980. }
  981. }
  982. /**
  983. * This event handler is needed in the following scenarios:
  984. * 1. When the user changes the selected compact road type chip to adjust its styling.
  985. * 2. When the switch alternative name button is clicked.
  986. */
  987. function onSegmentsChanged() {
  988. addCompactRoadTypeColors();
  989. addSwitchPrimaryNameButton();
  990. }
  991. async function onCopyCoordinatesShortcut() {
  992. try {
  993. const center = sdk.Map.getMapCenter();
  994. const output = `${center.lat.toFixed(5)}, ${center.lon.toFixed(5)}`;
  995. await navigator.clipboard.writeText(output);
  996. WazeWrap.Alerts.info('WME ClickSaver', `Map center coordinate copied to clipboard:\n${output}`, false, false, 2000);
  997. // console.debug('Map coordinates copied to clipboard:', center);
  998. } catch (err) {
  999. console.error('Failed to copy map center coordinates to clipboard: ', err);
  1000. }
  1001. }
  1002. function onToggleDrawNewRoadsAsTwoWayShortcut() {
  1003. const options = sdk.Settings.getUserSettings();
  1004. options.isCreateRoadsAsTwoWay = !options.isCreateRoadsAsTwoWay;
  1005. sdk.Settings.setUserSettings(options);
  1006. WazeWrap.Alerts.info('WME ClickSaver', `New segments will be drawn as <b>${options.isCreateRoadsAsTwoWay ? 'two-way' : 'one-way'}</b>.`, false, false, 2000);
  1007. }
  1008. function createShortcut(shortcutId, description, callback) {
  1009. let shortcutKeys = _settings.shortcuts?.[shortcutId] ?? null;
  1010. if (shortcutKeys && sdk.Shortcuts.areShortcutKeysInUse({ shortcutKeys })) {
  1011. shortcutKeys = null;
  1012. }
  1013. sdk.Shortcuts.createShortcut({
  1014. shortcutId,
  1015. shortcutKeys,
  1016. description,
  1017. callback
  1018. });
  1019. }
  1020. function hideUncheckedRoadTypeButtons() {
  1021. const selection = getSelectedSegments();
  1022. if (!selection) {
  1023. return;
  1024. }
  1025. const selectedRoadTypes = selection
  1026. .map(segmentId => sdk.DataModel.Segments.getById({ segmentId }))
  1027. .map(segment => segment.roadType);
  1028. const checkedRoadTypes = new Set(
  1029. _settings.roadTypeButtons
  1030. .map(roadType => roadTypeSettings[roadType])
  1031. .map(setting => setting.id)
  1032. .concat(selectedRoadTypes)
  1033. .map(id => id.toString())
  1034. );
  1035. // eslint-disable-next-line func-names
  1036. $('wz-chip-select.road-type-chip-select wz-checkable-chip').each(function() {
  1037. const buttonValue = $(this).attr('value');
  1038. if (buttonValue === 'MIXED') {
  1039. return;
  1040. }
  1041. if (!checkedRoadTypes.has(buttonValue)) {
  1042. $(this).parent().parent().remove();
  1043. }
  1044. });
  1045. }
  1046. async function init() {
  1047. logDebug('Initializing...');
  1048. trans = getTranslationObject();
  1049. Object.keys(roadTypeSettings).forEach(rtName => {
  1050. roadTypeSettings[rtName].text = trans.roadTypeButtons[rtName].text;
  1051. });
  1052. document.addEventListener('paste', onPaste);
  1053. sdk.Events.trackDataModelEvents({ dataModelName: 'segments' });
  1054. sdk.Events.on({
  1055. eventName: 'wme-data-model-objects-changed',
  1056. eventHandler: () => errorHandler(onSegmentsChanged)
  1057. });
  1058. sdk.Events.on({
  1059. eventName: 'wme-selection-changed',
  1060. eventHandler: () => errorHandler(updateControls)
  1061. });
  1062. // check for changes in the edit-panel
  1063. const observer = new MutationObserver(mutations => {
  1064. mutations.forEach(mutation => {
  1065. for (let i = 0; i < mutation.addedNodes.length; i++) {
  1066. const addedNode = mutation.addedNodes[i];
  1067. if (addedNode.nodeType === Node.ELEMENT_NODE) {
  1068. // Checks to identify if this is a segment in regular display mode.
  1069. if (addedNode.querySelector(roadTypeDropdownSelector)) {
  1070. if (isChecked('csRoadTypeButtonsCheckBox')) addRoadTypeButtons();
  1071. if (isSwapPedestrianPermitted() && isChecked('csAddSwapPedestrianButtonCheckBox')) {
  1072. addSwapPedestrianButton();
  1073. }
  1074. }
  1075. // Checks to identify if this is a segment in compact display mode.
  1076. if (addedNode.querySelector(roadTypeChipSelector)) {
  1077. if (isChecked('csRoadTypeButtonsCheckBox')) {
  1078. addCompactRoadTypeChangeEvents();
  1079. }
  1080. if (isSwapPedestrianPermitted() && isChecked('csAddSwapPedestrianButtonCheckBox')) {
  1081. addSwapPedestrianButton();
  1082. }
  1083. if (isChecked('csHideUncheckedRoadTypeButtonsCheckBox')) {
  1084. hideUncheckedRoadTypeButtons();
  1085. }
  1086. }
  1087. // if (addedNode.querySelector(PARKING_SPACES_DROPDOWN_SELECTOR) && isChecked('csParkingSpacesButtonsCheckBox')) {
  1088. // addParkingSpacesButtons();
  1089. // }
  1090. // if (addedNode.querySelector(PARKING_COST_DROPDOWN_SELECTOR)
  1091. // && isChecked('csParkingCostButtonsCheckBox')) {
  1092. // addParkingCostButtons();
  1093. // }
  1094. if (addedNode.querySelector('.side-panel-section') && isChecked('csAddAltCityButtonCheckBox')) {
  1095. addAddAltCityButton();
  1096. }
  1097. if (addedNode.querySelector('.alt-streets') && isChecked('csAddSwitchPrimaryNameCheckBox')) {
  1098. // Cancel button doesn't change the datamodel so re-add the switch arrow on cancel click
  1099. // eslint-disable-next-line func-names
  1100. addedNode.addEventListener('click', event => {
  1101. if (event.target.classList.contains('alt-address-cancel-button')) {
  1102. addSwitchPrimaryNameButton();
  1103. }
  1104. });
  1105. addSwitchPrimaryNameButton();
  1106. }
  1107. }
  1108. }
  1109. });
  1110. });
  1111. observer.observe(document.getElementById('edit-panel'), { childList: true, subtree: true });
  1112. await initUserPanel();
  1113. loadSettingsFromStorage();
  1114. createShortcut('toggleTwoWaySegDrawingShortcut', 'Toggle new segment two-way drawing', onToggleDrawNewRoadsAsTwoWayShortcut);
  1115. createShortcut('copyCoordinatesShortcut', 'Copy map center coordinates', onCopyCoordinatesShortcut);
  1116. window.addEventListener('beforeunload', saveSettingsToStorage, false);
  1117. injectCss();
  1118. updateControls(); // In case of PL w/ segments selected.
  1119. logDebug('Initialized');
  1120. }
  1121. function skipLoginDialog(tries = 0) {
  1122. if (sdk || tries === 1000) return;
  1123. if ($('wz-button.do-login').length) {
  1124. $('wz-button.do-login').click();
  1125. return;
  1126. }
  1127. setTimeout(skipLoginDialog, 100, ++tries);
  1128. }
  1129. skipLoginDialog();
  1130. sdk = await bootstrap({ scriptUpdateMonitor: { downloadUrl } });
  1131. init();
  1132. } // END clicksaver function (used to be injected, now just runs as a function)
  1133. // function exists(...objects) {
  1134. // return objects.every(object => typeof object !== 'undefined' && object !== null);
  1135. // }
  1136. function injectScript(argsObject) {
  1137. // 3/31/2023 - removing script injection due to loading errors that I can't track down ("require is not defined").
  1138. // Not sure if injection is needed anymore. I believe it was to get around an issue with Greasemonkey / Firefox.
  1139. clicksaver(argsObject);
  1140. // if (exists(require, $)) {
  1141. // GM_addElement('script', {
  1142. // textContent: `(function(){${clicksaver.toString()}\n clicksaver(${JSON.stringify(argsObject).replace('\'', '\\\'')})})();`
  1143. // });
  1144. // } else {
  1145. // setTimeout(() => injectScript(argsObject), 250);
  1146. // }
  1147. }
  1148. function setValue(object, path, value) {
  1149. const pathParts = path.split('.');
  1150. for (let i = 0; i < pathParts.length - 1; i++) {
  1151. const pathPart = pathParts[i];
  1152. if (pathPart in object) {
  1153. object = object[pathPart];
  1154. } else {
  1155. object[pathPart] = {};
  1156. object = object[pathPart];
  1157. }
  1158. }
  1159. object[pathParts[pathParts.length - 1]] = value;
  1160. }
  1161. function convertTranslationsArrayToObject(arrayIn) {
  1162. const translations = {};
  1163. let iRow;
  1164. let iCol;
  1165. const languages = arrayIn[0].map(lang => lang.toLowerCase());
  1166. for (iCol = 1; iCol < languages.length; iCol++) {
  1167. translations[languages[iCol]] = {};
  1168. }
  1169. for (iRow = 1; iRow < arrayIn.length; iRow++) {
  1170. const row = arrayIn[iRow];
  1171. const propertyPath = row[0];
  1172. for (iCol = 1; iCol < row.length; iCol++) {
  1173. setValue(translations[languages[iCol]], propertyPath, row[iCol]);
  1174. }
  1175. }
  1176. return translations;
  1177. }
  1178. function loadTranslations() {
  1179. if (typeof $ === 'undefined') {
  1180. setTimeout(loadTranslations, 250);
  1181. console.debug('ClickSaver:', 'jQuery not ready. Retry loading translations...');
  1182. } else {
  1183. // This call retrieves the data from the translations spreadsheet and then injects
  1184. // the main code into the page. If the spreadsheet call fails, the default English
  1185. // translation is used.
  1186. const args = {
  1187. scriptName,
  1188. scriptVersion,
  1189. forumUrl
  1190. };
  1191. $.getJSON(`${translationsUrl}?${DEC(apiKey)}`).then(res => {
  1192. args.translations = convertTranslationsArrayToObject(res.values);
  1193. console.debug('ClickSaver:', 'Translations loaded.');
  1194. }).fail(() => {
  1195. console.error('ClickSaver: Error loading translations spreadsheet. Using default translation (English).');
  1196. args.useDefaultTranslation = true;
  1197. }).always(() => {
  1198. // Leave this document.ready function. Some people randomly get a "require is not defined" error unless the injectMain function
  1199. // is called late enough. Even with a "typeof require !== 'undefined'" check.
  1200. $(document).ready(() => {
  1201. injectScript(args);
  1202. });
  1203. });
  1204. }
  1205. }
  1206. function sandboxBootstrap() {
  1207. if (WazeWrap?.Ready) {
  1208. WazeWrap.Interface.ShowScriptUpdate(scriptName, scriptVersion, updateMessage, forumUrl);
  1209. } else {
  1210. setTimeout(sandboxBootstrap, 250);
  1211. }
  1212. }
  1213. // Go ahead and start loading translations, and inject the main code into the page.
  1214. loadTranslations();
  1215. // Start the "sandboxed" code.
  1216. sandboxBootstrap();
  1217. })();