vue.rules.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095
  1. /**
  2. * The Vue application instance.
  3. * https://vuejs.org/guide/essentials/application.html
  4. * This is the root component
  5. */
  6. const app = Vue.createApp({
  7. /**
  8. * to prevent conflict with jekyll we change the
  9. * delimiters from {{ }} to [[ ]]
  10. */
  11. delimiters: ['[[', ']]'],
  12. /**
  13. * The data object of the root component.
  14. * These variables are available in the html template.
  15. */
  16. data() {
  17. return {
  18. // The rule object
  19. rule: global.rule || {
  20. ruleID: "",
  21. timestamp: "",
  22. icon: "",
  23. name: "",
  24. lineage: "",
  25. summary: "",
  26. config: {},
  27. creator: {
  28. name: "",
  29. url: "",
  30. },
  31. modules: []
  32. },
  33. legacy: false,
  34. rID: false,
  35. loading: false,
  36. publishing: false,
  37. view: (global.rule) ? true : false,
  38. preview: (global.rule) ? true : false,
  39. template: (global.rule) ? true : false,
  40. steinAPI: 'https://api.steinhq.com/v1/storages/5e8b937ab88d3d04ae0816a5',
  41. // TODO keep an array of past states for undo/redo
  42. history: [],
  43. // the data of the current module in the editor
  44. editor: {
  45. source: null,
  46. previousState: null,
  47. module: null,
  48. },
  49. // the module that is currently being dragged
  50. holding: false,
  51. // object of icons for easy access
  52. icons: {
  53. plus: '/assets/tabler_icons/circle-plus.svg',
  54. info: '/assets/tabler_icons/info-circle.svg',
  55. chevron: '/assets/tabler_icons/chevrons-down.svg',
  56. blank: '/assets/tabler_icons/circle-dotted.svg',
  57. view: '/assets/tabler_icons/eye.svg',
  58. edit: '/assets/tabler_icons/tool.svg',
  59. plus: '/assets/tabler_icons/plus.svg',
  60. minus: '/assets/tabler_icons/minus.svg',
  61. publish: '/assets/tabler_icons/cloud-upload.svg',
  62. download: '/assets/tabler_icons/download.svg',
  63. export: '/assets/tabler_icons/file-download.svg',
  64. upload: '/assets/tabler_icons/file-upload.svg',
  65. fork: '/assets/tabler_icons/git-fork.svg',
  66. },
  67. // icons available in the editor
  68. moduleIcons: {
  69. culture: '/assets/tabler_icons/palette.svg',
  70. decision: '/assets/tabler_icons/thumb-up.svg',
  71. process: '/assets/tabler_icons/rotate.svg',
  72. structure: '/assets/tabler_icons/building.svg',
  73. relationship: '/assets/tabler_icons/heart.svg',
  74. economic: '/assets/tabler_icons/coin.svg',
  75. legal: '/assets/tabler_icons/license.svg',
  76. map: '/assets/tabler_icons/map.svg',
  77. communications: '/assets/tabler_icons/microphone.svg',
  78. },
  79. // icons available for rules
  80. ruleIcons: {
  81. atom: '/assets/tabler_icons/atom.svg',
  82. bandage: '/assets/tabler_icons/bandage.svg',
  83. book: '/assets/tabler_icons/book.svg',
  84. box: '/assets/tabler_icons/box.svg',
  85. church: '/assets/tabler_icons/building-church.svg',
  86. store: '/assets/tabler_icons/building-store.svg',
  87. brush: '/assets/tabler_icons/brush.svg',
  88. car: '/assets/tabler_icons/car.svg',
  89. clock: '/assets/tabler_icons/clock.svg',
  90. cloud: '/assets/tabler_icons/cloud.svg',
  91. compass: '/assets/tabler_icons/compass.svg',
  92. game: '/assets/tabler_icons/device-gamepad.svg',
  93. flask: '/assets/tabler_icons/flask.svg',
  94. location: '/assets/tabler_icons/location.svg',
  95. moon: '/assets/tabler_icons/moon.svg',
  96. settings: '/assets/tabler_icons/settings.svg',
  97. shield: '/assets/tabler_icons/shield.svg',
  98. star: '/assets/tabler_icons/star.svg',
  99. tool: '/assets/tabler_icons/tool.svg',
  100. world: '/assets/tabler_icons/world.svg',
  101. },
  102. // the template for modules
  103. moduleTemplate: {
  104. moduleID: "",
  105. name: "",
  106. icon: "",
  107. summary: "",
  108. config: {},
  109. type: "",
  110. modules: []
  111. },
  112. // tracks the current module library tab that is open
  113. moduleLibrary: 'culture',
  114. moduleTypes: {
  115. // custom: {
  116. // question: 'Modules that you\'ve created.',
  117. // icon: '/assets/tabler_icons/circle-plus.svg',
  118. // open: true
  119. // },
  120. culture: {
  121. question: 'What are the core missions, values, and norms?',
  122. icon: '/assets/tabler_icons/palette.svg',
  123. open: true
  124. },
  125. decision: {
  126. question: 'Who can make decisions and how?',
  127. icon: '/assets/tabler_icons/thumb-up.svg',
  128. open: false
  129. },
  130. process: {
  131. question: 'How are policies implemented, and how do they evolve?',
  132. icon: '/assets/tabler_icons/rotate.svg ',
  133. open: false
  134. },
  135. structure: {
  136. question: 'What kinds of roles and internal entities are there?',
  137. icon: '/assets/tabler_icons/building.svg',
  138. open: false
  139. }
  140. },
  141. // array of modules that have been created by the user
  142. // TODO: implement custom modules
  143. customModules: [],
  144. // library of existing modules
  145. modules: global.modules,
  146. exports: {
  147. markdown: null,
  148. json: null,
  149. }
  150. }
  151. },
  152. /**
  153. * Vue provide passes data to other components.
  154. * https://vuejs.org/guide/components/provide-inject.html#provide-inject
  155. */
  156. provide() {
  157. return {
  158. editor: this.editor,
  159. icons: this.icons,
  160. }
  161. },
  162. created() {
  163. this.addToEditor(this.newModule());
  164. var urlParams = new URLSearchParams(window.location.search);
  165. if (urlParams.has('r')) {
  166. this.rID = urlParams.get('r');
  167. this.preview = true;
  168. this.view = true;
  169. this.fetchRule(this.rID);
  170. }
  171. },
  172. computed: {
  173. /**
  174. * Exports the current rule into a normalized format
  175. * Cleans up all submodules so they are ready for export
  176. * @returns {Object} a Rule object
  177. */
  178. ruleExport() {
  179. //TODO: test if icon is an absolute url and only add the global if it is not
  180. /**
  181. * Takes a module and recursively cleans it and all submodules up
  182. * @param {Object} module a module object
  183. * @returns
  184. */
  185. function cleanModules(module) {
  186. const newModule = {
  187. moduleID: module.moduleID,
  188. name: module.name,
  189. icon: (module.icon && !module.icon.includes('http')) ? global.url + module.icon : module.icon,
  190. summary: module.summary,
  191. config: module.config,
  192. type: module.type,
  193. modules: (module.modules) ? module.modules.map(cleanModules) : [],
  194. }
  195. return newModule;
  196. }
  197. return {
  198. ruleID: (this.rule.ruleID) ? this.rule.ruleID : this.slugify(this.rule.name),
  199. timestamp: this.timesString(),
  200. icon: (this.rule.icon && !this.rule.icon.includes('http')) ? global.url + this.rule.icon : this.rule.icon,
  201. name: this.rule.name,
  202. lineage: this.rule.lineage,
  203. summary: this.rule.summary,
  204. config: this.rule.config,
  205. creator: {
  206. name: this.rule.creator.name,
  207. url: this.rule.creator.url,
  208. },
  209. modules: this.rule.modules.map(cleanModules)
  210. }
  211. },
  212. /**
  213. * @returns {String} the current rule as a JSON string
  214. */
  215. json() {
  216. return JSON.stringify(this.ruleExport, null, 2);
  217. },
  218. /**
  219. * Creates an array of all moduleIDs in use
  220. * @returns {Array} an array of all module's (in the library and custom modules) moduleID
  221. */
  222. listModuleIds() {
  223. const modules = [...this.rule.modules, ...this.customModules];
  224. return modules.map(module => module.moduleID)
  225. },
  226. /**
  227. * @returns {Object} the current module in the editor
  228. */
  229. moduleInEditor() {
  230. return this.moduleEditor[0]
  231. },
  232. /**
  233. * Tests if the current module in the editor has been modified
  234. * against the editor.previousState object
  235. * @returns {Boolean} true if the module in the editor has been modified
  236. */
  237. //TODO: find a more accurate solution than just turning the object into a string
  238. editorHasEdits() {
  239. return this.editor.module && Object.entries(this.editor.module).toString() !== Object.entries(this.editor.previousState).toString();
  240. },
  241. },
  242. methods: {
  243. // module methods ===========================================================
  244. /**
  245. * @returns {Object} a new module object from the moduleTemplate
  246. */
  247. newModule() {
  248. return JSON.parse(JSON.stringify(this.moduleTemplate));
  249. },
  250. /**
  251. * spreads a source module into a new module from the moduleTemplate
  252. * @param {Object} sourceModule the module to copy
  253. * @param {Boolean} includeSubmodules whether to copy submodules or not
  254. * @returns
  255. */
  256. cloneModule(sourceModule,includeSubmodules) {
  257. let output = {
  258. ...this.moduleTemplate,
  259. ...sourceModule,
  260. //TODO: implement lineage pattern, same as the rule does
  261. source: sourceModule, // keep track of where this module came from
  262. };
  263. if (!includeSubmodules) output.modules = [];
  264. // clear configs
  265. document.getElementById("newConfigKey").value =
  266. "Configuration";
  267. document.getElementById("newConfigValue").value =
  268. "Value";
  269. // delete unnecessary properties
  270. delete output.content;
  271. delete output.readonly;
  272. // TODO: give module a unique id
  273. // if (output.moduleID) output.moduleID = this.getUniqueId(output.moduleID);
  274. return output;
  275. },
  276. /**
  277. * Handles the click event to copy a module
  278. * @param {Event} ev the click event
  279. */
  280. handleClickCopyModule(ev) {
  281. const clickTarget = this.getClosestModule(ev.target);
  282. if (!clickTarget) return;
  283. this.copyModule(clickTarget.module);
  284. },
  285. /**
  286. * Handles the click event to edit a module
  287. * @param {Event} ev the click event
  288. */
  289. handleClickEditModule(ev) {
  290. const clickTarget = this.getClosestModule(ev.target);
  291. if (!clickTarget) return;
  292. this.editModule(clickTarget.module);
  293. },
  294. /**
  295. * Copies a module to the editor
  296. * @param {Object} module the module to copy
  297. */
  298. copyModule(module) {
  299. this.copyToEditor(module);
  300. },
  301. /**
  302. * moves a module to the editor
  303. * @param {Object} module the module to edit
  304. */
  305. editModule(module) {
  306. this.addToEditor(module);
  307. },
  308. /**
  309. * add a module to another module (or to the rule by default) as a submodule
  310. * @param {Object} module to add
  311. * @param {Object} target a module or the rule Object where the module should be added as a submodule
  312. */
  313. addModule(module,target = this.rule) {
  314. target.modules.push(module);
  315. },
  316. /**
  317. * remove a module from another module (or from the rule)
  318. * recursively moves through all submodules in the target
  319. * removes ONLY the first instance of the module
  320. * @param {Object} module the module to remove from target
  321. * @param {Object} target the module or rule to remove the module from (defaults to rule)
  322. */
  323. removeModule(module, target = this.rule) {
  324. if (! this.moduleContains(module, target)) return; // if the module is not in the target, do nothing
  325. //
  326. target.modules.forEach((m, idx) => {
  327. if (m === module) {
  328. target.modules.splice(idx, 1);
  329. return;
  330. } else {
  331. this.removeModule(module, m);
  332. }
  333. });
  334. },
  335. /**
  336. * Deletes custom module from the customModules array and clears the editor
  337. * @param {Object} module the module to be deleted
  338. */
  339. deleteModule(module) {
  340. this.removeCustomModule(module);
  341. // TODO: only clear the editor if the module is present in the editor
  342. this.clearEditor();
  343. },
  344. /**
  345. * Handles the start drag event for a module
  346. * @param {Event} ev the drag event
  347. */
  348. startDragModule(ev) {
  349. const targetModule = this.getClosestModule(ev.target);
  350. if (!targetModule) return;
  351. const module = targetModule.module;
  352. ev.dataTransfer.setDragImage(targetModule, ev.offsetX, ev.offsetY);
  353. this.holding = {module};
  354. },
  355. /**
  356. * Handles the start drag event for a module
  357. * when the module is being rearranged within the rule
  358. * @param {Event} ev the drag event
  359. */
  360. rearrangeModule(ev) {
  361. const targetModule = this.getClosestModule(ev.target);
  362. if (!targetModule) return;
  363. const source = this.getClosestModule(targetModule.parentNode).module;
  364. const module = targetModule.module;
  365. ev.dataTransfer.setDragImage(targetModule, ev.offsetX, ev.offsetY);
  366. this.holding = {
  367. module,
  368. source,
  369. };
  370. },
  371. /**
  372. * Handles the dragend event for a module
  373. */
  374. endDragModule() {
  375. this.holding = false;
  376. },
  377. /**
  378. * Recursively searches modules and their submodules for a module
  379. * @param {Object} needle the module to search for
  380. * @param {Object} haystack the module to search in (defaults to rule)
  381. * @returns {Boolean} true if the module is in the haystack
  382. */
  383. // TODO: return the module location in the haystack (Maybe?)
  384. moduleContains(needle, haystack = this.rule) {
  385. if (! haystack.modules ) return false; // does the haystack even have modules?
  386. if (haystack.modules.includes(needle)) return true; // is the needle in the haystack?
  387. return haystack.modules.some(submodule => this.moduleContains(needle, submodule)); // is the needle in any of the submodules?
  388. },
  389. // rule methods ===========================================================
  390. /**
  391. * Handles the drop event for a module
  392. * adds the module to the closest submodule or the rule depending on what it is dropped onto
  393. * then adds the module to the editor
  394. * @param {Event} ev the drop event
  395. */
  396. dropOnRule(ev) {
  397. //TODO browser drag objects that hover over drop zone are showing a 'add' icon
  398. const landingNode = this.getClosestModule(ev.target);
  399. if (!this.holding.module || !landingNode) return; // if there is no module to drop or no landing node, do nothing
  400. const landingModule = landingNode.module; // module is set with the v-bind prop binding
  401. const holdingModule = this.holding.module;
  402. if (holdingModule === landingModule) return; // if the module is the same, do nothing
  403. // if the module being dropped is readyonly clone it, otherwise use the original
  404. const readonly = holdingModule.readonly;
  405. const module = (readonly) ? this.cloneModule(holdingModule) : holdingModule;
  406. if (this.holding.source) {
  407. // if the module has a source, remove it from that source
  408. this.removeModule(holdingModule, this.holding.source);
  409. }
  410. this.addModule(module, landingModule);
  411. this.editModule(module);
  412. this.endDragModule();
  413. },
  414. fetchRule(id) {
  415. this.loading = true;
  416. // handle legacy links
  417. // TODO: handle this at a global level
  418. let redirect = {
  419. 'benevolent_dictator': 'benevolent-dictator',
  420. circles: 'circles',
  421. consensus: 'consensus',
  422. 'do-ocracy': 'do-ocracy',
  423. 'elected_board': 'elected-board',
  424. jury: 'jury',
  425. petition: 'petition',
  426. 'self-appointed_board': 'self-appointed-board',
  427. }
  428. // if the rule is a legacy link, redirect
  429. if (redirect[id]) {
  430. location.href = `/templates/${redirect[id]}`;
  431. return;
  432. }
  433. const store = new SteinStore(
  434. this.steinAPI
  435. );
  436. (async () => {
  437. var rule = [];
  438. // read values from all sheets
  439. await store.read('rules', { search: { ruleID: id } }).then(data => {
  440. // test if there's anything in data
  441. if (data.length > 0) {
  442. rule = data[0];
  443. }
  444. console.log(rule);
  445. });
  446. // no rule found, exit
  447. // TODO: inform the user that the rule was not found
  448. if (!rule) {
  449. this.loading = false;
  450. return;
  451. }
  452. // if this is a legacy (pre-v3) set it as such
  453. if (rule.version < 3) {
  454. this.loading = false;
  455. this.legacy = true;
  456. this.rule = rule;
  457. Vue.nextTick(() => {
  458. if (rule.version == 2) displayBuilderHTML();
  459. });
  460. return;
  461. }
  462. this.rule = {
  463. ruleID: rule.ruleID,
  464. timestamp: rule.timestamp,
  465. icon: rule.icon,
  466. name: rule.name,
  467. lineage: rule.lineage,
  468. summary: rule.summary,
  469. config: rule.config,
  470. creator: {
  471. name: rule.creatorName,
  472. url: rule.creatorUrl,
  473. },
  474. modules: (rule.modules) ? JSON.parse(rule.modules) : []
  475. }
  476. /** Add name to <title> for v3+ rules */
  477. document.title = rule.name + " / CommunityRule"
  478. this.loading = false;
  479. })();
  480. },
  481. // editor methods =========================================================
  482. /**
  483. * Adds a module to the editor
  484. * @param {Object} module the module to add to the editor
  485. */
  486. addToEditor(module) {
  487. this.preventEditorLoss();
  488. this.setEditorSource(module);
  489. this.setEditorPreviousState(module);
  490. this.editor.module = module;
  491. },
  492. /**
  493. * Copies a module to the editor
  494. * @param {Object} module the module to copy to the editor
  495. */
  496. copyToEditor(module) {
  497. const moduleCopy = this.cloneModule(module);
  498. this.preventEditorLoss();
  499. this.setEditorSource(module);
  500. this.setEditorPreviousState(moduleCopy);
  501. this.editor.module = moduleCopy;
  502. },
  503. /**
  504. * Takes a module and clones it into the editor.previousState
  505. * @param {Object} module the module to add to the previous state
  506. */
  507. setEditorPreviousState(module) {
  508. this.editor.previousState = { ...module };
  509. },
  510. /**
  511. * Sets the editor.source to the module
  512. * @param {Object} module the module to set the editor source to
  513. */
  514. setEditorSource(module) {
  515. this.editor.source = module;
  516. },
  517. /**
  518. * Checks if the editor has edits and that the current module in the editor is not present in the rule
  519. * If the module in the editor would be lost, confirm with the user
  520. * then adds the module to the customModules array
  521. */
  522. preventEditorLoss() {
  523. // if the editor has changes and the module isn't in the rule, save it to the custom modules
  524. if (this.editorHasEdits && !this.moduleContains(this.editor.module)) {
  525. this.confirm('You have unsaved changes. Are you sure you want to discard them?')
  526. this.addCustomModule(this.editor.module);
  527. }
  528. },
  529. /**
  530. * Handles the click event for adding a module from the editor to the rule
  531. */
  532. clickAddModule() {
  533. const module = this.editor.module;
  534. this.addModule(module);
  535. this.addToEditor(module);
  536. },
  537. /**
  538. * Handles the click event for removing a module in the editor from the rule
  539. */
  540. clickRemoveModule() {
  541. const module = this.editor.module;
  542. this.removeModule(module);
  543. },
  544. /**
  545. * Clears the editor
  546. */
  547. clearEditor() {
  548. this.preventEditorLoss();
  549. this.editor.module = null;
  550. this.editor.previousState = null;
  551. },
  552. /**
  553. * Saves the module in the editor to customModules array
  554. */
  555. saveEditor() {
  556. this.addCustomModule(this.editor.module);
  557. this.setEditorPreviousState(this.editor.module);
  558. },
  559. // config methods =========================================================
  560. /**
  561. * Add custom config entry to the module
  562. */
  563. addConfig() {
  564. const k = document.getElementById("newConfigKey").value;
  565. const v = document.getElementById("newConfigValue").value;
  566. this.editor.module.config[k] = v;
  567. this.resetNewConfigInputs();
  568. },
  569. /**
  570. * Removes the config entry from the module
  571. */
  572. removeConfig(key) {
  573. delete this.editor.module.config[key];
  574. },
  575. // custom module methods ==================================================
  576. /**
  577. * Adds a module to the customModules array
  578. * @param {Object} module the module to add to the customModules array
  579. */
  580. addCustomModule(module) {
  581. // if module is not in customModules, add it
  582. if (!this.customModules.includes(module)) {
  583. this.customModules.unshift(module);
  584. }
  585. },
  586. /**
  587. * Creates a new module, sets a default name, and adds it to the editor
  588. */
  589. newCustomModule() {
  590. const module = this.newModule();
  591. module.name = 'New Module';
  592. module.config = {};
  593. this.resetNewConfigInputs();
  594. this.addToEditor(module);
  595. },
  596. resetNewConfigInputs() {
  597. document.getElementById("newConfigKey").value = "Configuration";
  598. document.getElementById("newConfigValue").value = "Value";
  599. },
  600. /**
  601. * Removes a module from the customModules array
  602. * @param {Object} module the module to remove from the customModules array
  603. */
  604. removeCustomModule(module) {
  605. this.confirm("are you sure you want to remove this custom module?");
  606. const index = this.customModules.indexOf(module);
  607. this.customModules.splice(index, 1);
  608. },
  609. /**
  610. * Handles confirmation messages for users
  611. * @param {String} msg the message to display in the confirm dialog
  612. */
  613. // TODO: add a confirm dialog and return boolean based on user input
  614. confirm(msg) {
  615. console.log(msg);
  616. },
  617. // export and download methods =============================================
  618. /**
  619. * Handles click event for publishing the rule
  620. */
  621. handleClickPublish() {
  622. // Confirm user knows what they're getting into
  623. if (!confirm("Publish to the public Library?")) return;
  624. if ( !this.rule.name ) {
  625. alert("Please enter a name for this rule.");
  626. return;
  627. }
  628. if ( this.rule.modules.length < 1 ) {
  629. alert("Please add at least one module to this rule.");
  630. return;
  631. }
  632. this.publishing = true;
  633. const rule = this.ruleExport;
  634. const ruleID = new Date().getTime(); // TODO: allow for custom named IDs, check for uniqueness
  635. // add to database
  636. const store = new SteinStore(
  637. this.steinAPI
  638. );
  639. store.append('rules', [{
  640. ruleID: ruleID,
  641. timestamp: rule.timestamp,
  642. icon: rule.icon,
  643. name: rule.name,
  644. lineage: rule.lineage,
  645. summary: rule.summary,
  646. config: this.jsonify(rule.config),
  647. modules: this.jsonify(rule.modules),
  648. creatorName: rule.creator.name,
  649. creatorUrl: rule.creator.url,
  650. version: 3
  651. }]).then(data => {
  652. this.publishing = false;
  653. window.open("/create/?r=" + ruleID, "_self", false);
  654. });
  655. },
  656. /**
  657. * Handles the click event for downloading the rule as a Markdown file
  658. * Creates a YAML string of the rule
  659. * Then adds it to the bottom of a markdown file
  660. * created from the #rule-export html element
  661. */
  662. handleClickDownload() {
  663. const yaml = jsyaml.dump(this.ruleExport);
  664. const turndown = new TurndownService();
  665. const html = document.getElementById('rule-export');
  666. if (!html) return;
  667. const markdown = turndown.turndown(html);
  668. const output = markdown + '\n\n----\n```yaml\n' + yaml + '\n```';
  669. this.saveFile(`${this.ruleExport.ruleID}.md`, output, 'text/markdown');
  670. },
  671. /**
  672. * Handles the click event for downloading the rule as a JSON file
  673. */
  674. handleClickExport() {
  675. const output = this.json;
  676. this.saveFile(`${this.ruleExport.ruleID}.json`, output, 'application/json');
  677. },
  678. /**
  679. * IE10+ Firefox, and Chrome method for saving a file
  680. * https://stackoverflow.com/a/33542499
  681. * @param {String} filename name of the file to save
  682. * @param {String} data data to save into a file
  683. * @param {String} type MIME type of the file
  684. */
  685. saveFile(filename, data, type) {
  686. const blob = new Blob([data], { type: type });
  687. if (window.navigator.msSaveOrOpenBlob) {
  688. window.navigator.msSaveBlob(blob, filename);
  689. }
  690. else {
  691. const elem = window.document.createElement('a');
  692. elem.href = window.URL.createObjectURL(blob);
  693. elem.download = filename;
  694. document.body.appendChild(elem);
  695. elem.click();
  696. document.body.removeChild(elem);
  697. }
  698. },
  699. /**
  700. * Handles the click event for importing a rule from a JSON file
  701. */
  702. handleClickImport() {
  703. },
  704. // utility methods ===========================================================
  705. /**
  706. * Takes an html element and finds the closest node (inclusive) that has a data-module-id attribute
  707. * @param {Node} el the html element to check
  708. * @returns {Node} the closest node with a data-module-id attribute
  709. */
  710. getClosestModule(el) {
  711. const parent = el.closest('[data-module-id]');
  712. if (!parent) return false;
  713. if (!parent.module) return false;
  714. return parent;
  715. },
  716. /**
  717. * Handles the click event for activating the rule preview
  718. */
  719. clickPreview() {
  720. if(this.template) this.rule.icon = ''; // TODO: find a less hacky way to reset template icons
  721. this.view = false;
  722. this.preview = !this.preview;
  723. },
  724. /**
  725. * Filters module library based on the search term
  726. * @param {String} type the name of the type to filter
  727. * @returns {Array} the filtered module library
  728. */
  729. getModulesByType(type) {
  730. return this.modules.filter(module => module.type === type)
  731. },
  732. /**
  733. * Slugifies a string
  734. * https://gist.github.com/codeguy/6684588 (one of the comments)
  735. * @param {String} string the string to slugify
  736. * @returns
  737. */
  738. slugify(string) {
  739. const separator = '-';
  740. return string
  741. .toString()
  742. .normalize('NFD') // split an accented letter in the base letter and the accent
  743. .replace(/[\u0300-\u036f]/g, '') // remove all previously split accents
  744. .toLowerCase()
  745. .replace(/[^a-z0-9 -]/g, '') // remove all chars not letters, numbers and spaces (to be replaced)
  746. .trim()
  747. .replace(/\s+/g, separator);
  748. },
  749. /**
  750. * Creates a human readable timestamp string
  751. * @param {String} date optional date to format
  752. * @returns {String} human readable date '2022.4.12 14:44:56 UTC'
  753. */
  754. timesString(date) {
  755. let now = new Date(date);
  756. if (isNaN(now)) now = new Date();
  757. return now.getUTCFullYear() + '.' + (now.getUTCMonth() + 1) + '.' + now.getUTCDate()
  758. + ' ' + now.getUTCHours() + ":" + now.getUTCMinutes() + ":" + now.getUTCSeconds()
  759. + ' UTC';
  760. },
  761. /**
  762. * stringify an Object
  763. * @param {Object} obj
  764. * @returns JSON string
  765. */
  766. jsonify(obj) {
  767. return JSON.stringify(obj, null, 2);
  768. },
  769. /**
  770. * Takes a moduleID and checks if that moduleID is in use
  771. * if so, returns the moduleID with a number appended to it
  772. * @param {String} test the moduleID to test
  773. * @returns {String} the moduleID, or if in use, with a number appended to it
  774. */
  775. getUniqueId(test) {
  776. let id = test;
  777. let i = 0;
  778. while (this.listModuleIds.includes(id)) {
  779. i++;
  780. id = `${test}-${i}`;
  781. }
  782. return id
  783. },
  784. },
  785. });
  786. /**
  787. * The Module Vue Component
  788. */
  789. app.component('module', {
  790. delimiters: ['[[', ']]'],
  791. inject: ['editor'],
  792. props: {
  793. module: {
  794. type: Object,
  795. required: true,
  796. },
  797. inEditor: {
  798. type: Boolean,
  799. default: false,
  800. },
  801. hideSubmodules: {
  802. type: Boolean,
  803. default: false,
  804. }
  805. },
  806. data() {
  807. return {
  808. defaultIcon: '/assets/tabler_icons/circle-dotted.svg',
  809. mouseOver: false,
  810. dragOver: false
  811. }
  812. },
  813. computed: {
  814. icon() {
  815. return this.module.icon ? this.module.icon : this.defaultIcon;
  816. },
  817. moduleClass() {
  818. return {
  819. 'in-editor': this.editor.source == this.module,
  820. 'mouse-over': this.mouseOver,
  821. // TODO: when dragging over the icon the drag-over class disappears
  822. 'drag-over': this.dragOver
  823. }
  824. }
  825. },
  826. template: `
  827. <div
  828. class="module"
  829. :class="moduleClass"
  830. .module="module"
  831. @mouseover.stop="this.mouseOver = true"
  832. @mouseout="this.mouseOver = false"
  833. @dragenter.self="this.dragOver = true"
  834. @dragleave.self="this.dragOver = false"
  835. @drop.self="this.dragOver = false"
  836. :data-module-id="module.moduleID"
  837. >
  838. <div class="module__icon-wrapper">
  839. <span class="module__grain"><img src="/assets/tabler_icons/grain.svg"></span>
  840. <span class="module__icon"><img :src="icon"></span>
  841. </div>
  842. [[module.name]]
  843. <div class="submodules" v-if="!hideSubmodules && module.modules && module.modules.length">
  844. <module v-for="submodule in module.modules" :module="submodule" draggable="true"></module>
  845. </div>
  846. </div>
  847. `
  848. })
  849. /**
  850. * A non-interactive Module Vue Component
  851. * Used for displaying the module
  852. */
  853. app.component('moduleDisplay', {
  854. delimiters: ['[[', ']]'],
  855. props: {
  856. module: {
  857. type: Object,
  858. required: true,
  859. }
  860. },
  861. data() {
  862. return {
  863. defaultIcon: '/assets/tabler_icons/circle-dotted.svg'
  864. }
  865. },
  866. computed: {
  867. icon() {
  868. return this.module.icon ? this.module.icon : this.defaultIcon;
  869. }
  870. },
  871. template: `
  872. <div
  873. class="module"
  874. .module="module"
  875. >
  876. <div class="module__icon-wrapper">
  877. <span class="module__icon"><img :src="icon"></span>
  878. </div>
  879. [[module.name]]
  880. <div class="submodules" v-if="module.modules && module.modules.length">
  881. <module-display v-for="submodule in module.modules" :module="submodule"></module-display>
  882. </div>
  883. </div>
  884. `
  885. })
  886. /**
  887. * The Module list Vue Component
  888. */
  889. app.component('moduleList', {
  890. delimiters: ['[[', ']]'],
  891. props: {
  892. module: {
  893. type: Object,
  894. required: true,
  895. },
  896. hideIcon: {
  897. type: Boolean,
  898. default: false,
  899. }
  900. },
  901. data() {
  902. return {
  903. defaultIcon: '/assets/tabler_icons/circle-dotted.svg'
  904. }
  905. },
  906. computed: {
  907. icon() {
  908. return this.module.icon ? this.module.icon : this.defaultIcon;
  909. }
  910. },
  911. template: `
  912. <li class="module-list-item">
  913. <span class="module__icon" v-if="!hideIcon"><img :src="icon"> </span><strong>[[module.name]]</strong>: [[module.summary]]
  914. <span class="module__config">
  915. <span v-for="(value, key) in module.config">
  916. <br />[[key]]: [[value]]
  917. </span>
  918. </span>
  919. <ul class="submodules" v-if="module.modules && module.modules.length">
  920. <module-list v-for="submodule in module.modules" :module="submodule" :hide-icon="hideIcon"></module-list>
  921. </ul>
  922. </li>
  923. `
  924. })
  925. /**
  926. * A simple button Vue Component
  927. */
  928. app.component('vueButton', {
  929. delimiters: ['[[', ']]'],
  930. props: {
  931. icon: {
  932. type: String,
  933. required: false,
  934. default: false
  935. },
  936. loading: {
  937. type: Boolean,
  938. required: false,
  939. default: false
  940. }
  941. },
  942. computed: {
  943. classList() {
  944. return {
  945. 'has-icon': this.icon,
  946. 'is-loading': this.loading
  947. };
  948. },
  949. activeIcon() {
  950. return this.loading ? '/assets/tabler_icons/refresh.svg' : this.icon;
  951. }
  952. },
  953. template: `
  954. <button class="btn" :class="classList"><img :src="activeIcon" v-if="icon"> <slot>Click Here</slot></button>
  955. `
  956. })
  957. /**
  958. * A icon Vue Component
  959. */
  960. app.component('icon', {
  961. delimiters: ['[[', ']]'],
  962. props: {
  963. icon: {
  964. type: String,
  965. required: true,
  966. default: '/assets/tabler_icons/circle-dotted.svg'
  967. }
  968. },
  969. template: `
  970. <span class="icon"><img :src="icon"></span>
  971. `
  972. })
  973. /**
  974. * Mounts the app to the DOM element with the id 'app'
  975. */
  976. vm = app.mount('#app')
  977. /**
  978. * Legacy functions for displaying old rules
  979. */
  980. // Turns RuleBuilder contents into an output-ready nested array
  981. // Returns empty array if no modules
  982. function builderArray() {
  983. var modules = document.getElementById("module-input").children;
  984. // takes an array of children
  985. // returns an array with all modules in the array, recursively nested
  986. function iterateArray(childs) {
  987. var moduleArray = [];
  988. if (childs.length > 0) {
  989. for (var i = 0; i < childs.length; i++) {
  990. module = childs[i];
  991. if (module.classList[0] == "module") {
  992. var moduleName = module.children.item("module-name");
  993. var moduleData = moduleName.title;
  994. var moduleChilds = module.children;
  995. moduleArray.push(
  996. [stripHTML(moduleName.innerHTML),
  997. stripHTML(moduleData),
  998. iterateArray(moduleChilds)]);
  999. }
  1000. }
  1001. }
  1002. return moduleArray;
  1003. } // end function
  1004. return iterateArray(modules);
  1005. }
  1006. // returns HTML version of Builder content
  1007. function displayBuilderHTML() {
  1008. var output = "";
  1009. var mainArray = builderArray();
  1010. function arrayHTML(thisArray) {
  1011. var thisOutput = "";
  1012. if (thisArray.length > 0) {
  1013. thisOutput += '<ul>\n';
  1014. for (var i = 0; i < thisArray.length; i++) {
  1015. var item = thisArray[i];
  1016. thisOutput += '<li><strong>' + item[0] + '</strong> ';
  1017. thisOutput += item[1] + '</li>\n';
  1018. if (item[2].length > 0) {
  1019. thisOutput += arrayHTML(item[2]);
  1020. }
  1021. }
  1022. thisOutput += '</ul>\n';
  1023. }
  1024. return thisOutput
  1025. }
  1026. if (mainArray.length > 0) {
  1027. output += '<div class="builder-list">\n';
  1028. output += arrayHTML(mainArray) + '\n</div>\n';
  1029. }
  1030. document.getElementById("builder-field").innerHTML = output;
  1031. }
  1032. // Removes all HTML content, replacing line break tags with newlines
  1033. function stripHTML(input) {
  1034. input = input.replace(/<br ?\/?>/ig, "\n").replace(/(<([^>]+)>)/ig, '');
  1035. return input;
  1036. }