rule-scripts.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  1. <!-- Enables dragging on mobile
  2. https://github.com/Bernardo-Castilho/dragdroptouch -->
  3. <script src="/assets/DragDropTouch.js"></script>
  4. <script>
  5. // Enter JavaScript-land!
  6. // First, some functions, followed by initialization commands
  7. // Begin BUILDER functions
  8. // source: https://www.codecanal.com/html5-drag-and-copy/
  9. function allowDrop(ev) {
  10. ev.preventDefault();
  11. }
  12. function drag(ev) {
  13. ev.dataTransfer.setData("text", ev.target.id);
  14. }
  15. function drop(ev) {
  16. ev.preventDefault();
  17. var target = ev.target;
  18. // First, confirm target location is valid
  19. function targetCheck () {
  20. if (!editMode) {
  21. return false;
  22. } else if (target.id == "module-input") {
  23. return true;
  24. } else if (!document.getElementById("module-input").contains(target)) {
  25. // Ignore destinations not in the correct area
  26. return false;
  27. } else if (target.id == "drag-directions") {
  28. // Prevents dropping into dummy text field
  29. target = target.parentElement;
  30. return true;
  31. } else if (target.classList[0] == "module") {
  32. return true;
  33. } else {
  34. // be sure we're adding to module, not its children
  35. target = target.parentElement;
  36. return targetCheck();
  37. }
  38. }
  39. if (!targetCheck()) { return; }
  40. // Set up transfer
  41. var data = ev.dataTransfer.getData("text");
  42. // Iff module is from the menu clone it
  43. var module = document.getElementById(data);
  44. if ((module.parentElement.id == "module-menu") ||
  45. (module.parentElement.parentElement.id == "module-menu")) {
  46. // ^ because a subgroup might be parent
  47. module = module.cloneNode(true);
  48. var name = null;
  49. if (module.id == "module-custom") {
  50. // For custom modules: replace the <input> with text
  51. name = module.getElementsByTagName("input")[0].value;
  52. module.getElementsByTagName("input")[0].remove();
  53. var customText = document.createElement("span");
  54. customText.id = "module-name";
  55. customText.append(name);
  56. module.prepend(customText);
  57. }
  58. // append id with unique timestamp
  59. var nowModule = new Date();
  60. module.id += "-" + nowModule.getTime();
  61. }
  62. // display the deletion button
  63. module.children[2].style.display = "inline";
  64. // pop it in!
  65. target.appendChild(module);
  66. // add module-field button (using HTML so it saves to Library)
  67. module.outerHTML = module.outerHTML.replace("id=\"module-name\"",
  68. "id=\"module-name\" onclick=\"moduleEditField(this.parentNode.id)\"");
  69. // create the module-field
  70. moduleEditField(module.id);
  71. // be sure the dummy text is gone
  72. if (document.contains(document.getElementById("drag-directions"))) {
  73. document.getElementById("drag-directions").remove();
  74. }
  75. }
  76. // Edits the title field of a given module based on #custom-field
  77. function moduleTitleEdit(moduleID) {
  78. var module = document.getElementById(moduleID).children[0];
  79. var content =
  80. stripHTML(document.getElementById("custom-field").innerHTML);
  81. module.title = content;
  82. }
  83. // Sets up a field for displaying and editing module details
  84. function moduleEditField(moduleID) {
  85. var module = document.getElementById(moduleID);
  86. var moduleName = module.children[0].innerHTML;
  87. var moduleTitle = module.children[0].title;
  88. if (editMode) {
  89. var query = "How does the <strong>" + moduleName
  90. + "</strong> module work?";
  91. var destination = document.getElementById("builder-field");
  92. if (moduleName == null) { moduleName = ""; }
  93. var output = '\n<div id="custom-field-container">';
  94. output += '<span class="prompt">' + query + '</span>';
  95. output += '<div class="field-controls"><a onclick="this.parentNode.parentNode.remove()"><img src="{% link assets/tabler_icons/x.svg %}" class="delete-module" /></a></div>';
  96. output += '<p contenteditable="true" class="editable" id="custom-field" oninput="moduleTitleEdit(\'' + moduleID + '\')">' + moduleTitle + '</p>';
  97. output += '</div>\n';
  98. destination.innerHTML = output;
  99. } else {
  100. var output = '\n<div id="custom-field-container">';
  101. output += '<div class="field-controls"><a onclick="this.parentNode.parentNode.remove()"><img src="{% link assets/tabler_icons/x.svg %}" class="delete-module" /></a></div>';
  102. output += '<p class="editable" id="custom-field">'
  103. + moduleTitle + '</p>';
  104. }
  105. }
  106. // Tests if the RuleBuilder is empty
  107. function builderEmpty() {
  108. var builder = document.getElementById("module-input");
  109. var childs = builder.children;
  110. if (builder.getElementsByClassName("module").length > 0) {
  111. return false;
  112. } else {
  113. return true;
  114. }
  115. }
  116. // Turns RuleBuilder contents into an output-ready nested array
  117. // Returns empty array if no modules
  118. function builderArray() {
  119. var modules = document.getElementById("module-input").children;
  120. // takes an array of children
  121. // returns an array with all modules in the array, recursively nested
  122. function iterateArray (childs) {
  123. var moduleArray = [];
  124. if (childs.length > 0) {
  125. for (var i = 0; i < childs.length; i++) {
  126. module = childs[i];
  127. if (module.classList[0] == "module") {
  128. var moduleName = module.children.item("module-name");
  129. var moduleData = moduleName.title;
  130. var moduleChilds = module.children;
  131. moduleArray.push(
  132. [stripHTML(moduleName.innerHTML),
  133. stripHTML(moduleData),
  134. iterateArray(moduleChilds)]);
  135. }
  136. }
  137. }
  138. return moduleArray;
  139. } // end function
  140. return iterateArray(modules);
  141. }
  142. // returns HTML version of Builder content
  143. function displayBuilderHTML() {
  144. var output = "";
  145. var mainArray = builderArray();
  146. function arrayHTML(thisArray) {
  147. var thisOutput = "";
  148. if (thisArray.length > 0) {
  149. thisOutput += '<ul>\n';
  150. for (var i = 0; i < thisArray.length; i++) {
  151. var item = thisArray[i];
  152. thisOutput += '<li><strong>' + item[0] + '</strong> ';
  153. thisOutput += item[1] + '</li>\n';
  154. if (item[2].length > 0) {
  155. thisOutput += arrayHTML(item[2]);
  156. }
  157. }
  158. thisOutput += '</ul>\n';
  159. }
  160. return thisOutput
  161. }
  162. if (mainArray.length > 0) {
  163. output += '<div class="builder-list">\n';
  164. output += arrayHTML(mainArray) + '\n</div>\n';
  165. }
  166. return output;
  167. }
  168. // returns Markdown version of Builder content
  169. function displayBuilderMD() {
  170. var mainArray = builderArray();
  171. var indentLevel = 0;
  172. function arrayMD(thisArray) {
  173. var thisOutput = "";
  174. if (thisArray.length > 0) {
  175. for (var i = 0; i < thisArray.length; i++) {
  176. var item = thisArray[i];
  177. for (var x = 0; x < indentLevel; x++) {
  178. thisOutput += " ";
  179. }
  180. thisOutput += "* **" + item[0] + "** ";
  181. thisOutput += item[1] + "\n";
  182. if (item[2].length > 0) {
  183. indentLevel++;
  184. thisOutput += arrayMD(item[2]);
  185. indentLevel--;
  186. }
  187. }
  188. }
  189. return thisOutput;
  190. }
  191. return arrayMD(mainArray);
  192. }
  193. // end RuleBuilder functions
  194. // Removes all HTML content, replacing line break tags with newlines
  195. function stripHTML(input) {
  196. input = input.replace(/<br ?\/?>/ig, "\n").replace(/(<([^>]+)>)/ig,'');
  197. return input;
  198. }
  199. // Intercepts the paste event for editable fields and
  200. // converts the pasted content to plain text,
  201. // stripping styles and unwanted markup added by programs like Word.
  202. function handleEditablePaste(event) {
  203. try {
  204. var pastedText = event.clipboardData
  205. ? event.clipboardData.getData("text/plain")
  206. : window.clipboardData.getData("Text"); // support IE
  207. var cleanedText = cleanPastedText(pastedText);
  208. // Pastes the cleaned up text.
  209. if (document.queryCommandSupported('insertText')) {
  210. document.execCommand('insertText', false, cleanedText);
  211. } else { // support IE
  212. document.execCommand('paste', false, cleanedText);
  213. }
  214. event.stopPropagation();
  215. event.preventDefault();
  216. return false;
  217. } catch (err) {
  218. // If anything goes wrong with browser compatibility,
  219. // pass the event through without modification.
  220. return true;
  221. }
  222. }
  223. // Removes junk that comes with pasting from text editors like Word.
  224. // taken from https://stackoverflow.com/questions/2875027/clean-microsoft-word-pasted-text-using-javascript
  225. function cleanPastedText(text) {
  226. return text.replace(/.*<!--.*-->/g, "");
  227. }
  228. // toggleVisible(id)
  229. // Toggles the visibility of a given element by given ID
  230. function toggleVisible(id) {
  231. var x = document.getElementById(id);
  232. if (x.style.display === "none") {
  233. x.style.display = "block";
  234. } else {
  235. x.style.display = "none";
  236. }
  237. }
  238. // classDisplayAll(className, value)
  239. // Assigns given display value to all elements with a given className
  240. function classDisplayAll(className, value) {
  241. var elements = document.getElementsByClassName(className);
  242. for (var i = 0; i < elements.length; i++) {
  243. elements[i].style.display = value;
  244. }
  245. }
  246. // toggleEditMode()
  247. // Toggles whether editable fields are editable or not
  248. // and removes editing tools.
  249. function toggleEditMode() {
  250. if (editMode === true) { // switch to preview mode
  251. editMode = false;
  252. classDisplayAll("button","none");
  253. classDisplayAll("prompt","none");
  254. classDisplayAll("delete-module","none");
  255. var editableFields = document.getElementsByClassName("editable");
  256. // de-editable-ize the editable fields
  257. for (var i = 0; i < editableFields.length; i++) {
  258. editableFields[i].contentEditable = "false";
  259. editableFields[i].style.borderStyle = "none";
  260. // Remove empty fields entirely
  261. var content = editableFields[i].innerHTML;
  262. content = stripHTML(content);
  263. if (content === "") {
  264. editableFields[i].style.display = "none";
  265. }
  266. }
  267. // RuleBuilder sections
  268. if (builderEmpty()) {
  269. document.getElementById("rule-builder").style.display = "none";
  270. } else {
  271. document.getElementById("builder-field").innerHTML = displayBuilderHTML();
  272. document.getElementById("module-input").style.border = "none";
  273. }
  274. if (document.contains(document.getElementById("custom-field-container"))) {
  275. document.getElementById("custom-field-container").remove();
  276. }
  277. document.getElementById("module-menu").style.display = "none";
  278. // Handle author link
  279. var authorName = document.getElementById("author-text").value;
  280. var authorURL = document.getElementById("author-url").value;
  281. if (authorName != "") {
  282. document.getElementById("authorship-words").style.display = "inline";
  283. if (authorURL != "") { // both author and URL present
  284. document.getElementById("authorship-result").innerHTML = "<a href='" + authorURL +"'>" + authorName + "</a>";
  285. document.getElementById("authorship-result").style.display = "inline";
  286. } else { // only authorName present
  287. document.getElementById("authorship-result").innerHTML = authorName;
  288. document.getElementById("authorship-result").style.display = "inline";
  289. }
  290. } else {
  291. document.getElementById("authorship").style.display = "none";
  292. }
  293. // Finally, change button name
  294. document.getElementById("editToggle").innerHTML = "Customize";
  295. } else { // Switch to editMode
  296. editMode = true;
  297. classDisplayAll("button","block");
  298. classDisplayAll("prompt","block");
  299. classDisplayAll("editable","block");
  300. // RuleBuilder handling
  301. classDisplayAll("delete-module","inline");
  302. document.getElementById("rule-builder").style.display = "block";
  303. document.getElementById("module-menu").style.display = "block";
  304. document.getElementById("module-input").style.border = "";
  305. document.getElementById("builder-field").innerHTML = "";
  306. // link handling
  307. classDisplayAll("link-text","inline");
  308. classDisplayAll("link-url","inline");
  309. document.getElementById("authorship-result").style.display = "none";
  310. document.getElementById("authorship-words").style.display = "none";
  311. document.getElementById("authorship").style.display = "block";
  312. // make all editable fields visible
  313. var editableFields = document.getElementsByClassName("editable");
  314. for (var i = 0; i < editableFields.length; i++) {
  315. editableFields[i].style.borderStyle = "none none dashed none";
  316. editableFields[i].contentEditable = "true";
  317. }
  318. // Change button name
  319. document.getElementById("editToggle").innerHTML = "Preview";
  320. }
  321. }
  322. // toggleDisplayMode()
  323. // toggles full displayMode, the Rule-only display for a published Rule
  324. // first, initialize variable:
  325. var displayMode = false;
  326. function toggleDisplayMode() {
  327. if (displayMode == false) {
  328. editMode = true;
  329. toggleEditMode(); // turns off editMode
  330. classDisplayAll("site-nav","none");
  331. classDisplayAll("post-header","none");
  332. classDisplayAll("site-footer","none");
  333. document.getElementById("attribution").style.display = "block";
  334. document.getElementById("fork").style.display = "inline-block";
  335. document.getElementById("publishRule").style.display = "none";
  336. document.getElementById("trash").style.display = "inline-block";
  337. // Turn on RuleWriter if there's content
  338. if ("" != document.getElementById("rulewriter").innerHTML) {
  339. document.getElementById("rulewriter-box").style.display = "inline-block";
  340. }
  341. // Finish
  342. displayMode = true;
  343. } else {
  344. toggleEditMode() // turns on editMode
  345. classDisplayAll("site-nav","block");
  346. classDisplayAll("post-header","block");
  347. classDisplayAll("site-footer","block");
  348. document.getElementById("attribution").style.display = "none";
  349. document.getElementById("fork").style.display = "none";
  350. document.getElementById("publishRule").style.display = "inline-block";
  351. document.getElementById("trash").style.display = "none";
  352. displayMode = false;
  353. }
  354. if (document.getElementById("lineage-list").innerHTML != "") {
  355. document.getElementById("lineage").style.display = "block";
  356. }
  357. }
  358. // textOutput()
  359. // Produces Markdown rendition of Rule from Export button
  360. function textOutput() {
  361. var filename = 'GOVERNANCE.md';
  362. // First, add title, whether there is one or not
  363. var content = '# '+ document.getElementById('communityname').innerHTML + '\n\n';
  364. content = stripHTML(content);
  365. // Next, add structure field
  366. var structure = document.getElementById('structure').innerHTML;
  367. if (structure != "") {
  368. content += stripHTML(structure) + '\n\n';
  369. }
  370. // Add Builder content
  371. if (!builderEmpty()) {
  372. content += displayBuilderMD() + "\n\n";
  373. }
  374. // Now, begin adding Writer elements
  375. var elements = document.getElementsByClassName('output');
  376. for (var i = 2; i < elements.length; i++) { // start after structure
  377. var thisBit = elements[i].innerHTML;
  378. thisBit = stripHTML(thisBit);
  379. if (thisBit != "") {
  380. if (elements[i].classList.contains("subhead")) {
  381. // Before printing subhead, make sure it's not empty
  382. var i2 = i + 1;
  383. while ((i2 < elements.length) &&
  384. (!(elements[i2].classList.contains("subhead")))) {
  385. if (elements[i2].innerHTML != "") {
  386. // in this case, it's not empty, so print and move on
  387. content += '## ';
  388. content += thisBit + '\n\n';
  389. break;
  390. } else { i2++; }
  391. } // won't print anything if a subhead has only empty children
  392. } else {
  393. // Non-subhead elements can just go ahead and print
  394. content += thisBit + '\n\n';
  395. }
  396. }
  397. }
  398. // Add authorship block
  399. var authorName = document.getElementById("author-text").value;
  400. var authorURL = document.getElementById("author-url").value;
  401. var authorshipBlock = "---\n\nCreated by ";
  402. if (authorName != "") {
  403. if (authorURL != "") { // both author and URL present
  404. authorshipBlock += ("[" + authorName + "](" + authorURL + ")");
  405. } else { // only authorName present
  406. authorshipBlock += authorName;
  407. }
  408. content += (authorshipBlock + "\n");
  409. }
  410. // Add attribution block
  411. content += document.getElementById('attributionMD').innerHTML;
  412. // Starting here, see https://stackoverflow.com/a/33542499
  413. var blob = new Blob([content], {type: 'text/plain'});
  414. if(window.navigator.msSaveOrOpenBlob) {
  415. window.navigator.msSaveBlob(blob, filename);
  416. }
  417. else{
  418. var elem = window.document.createElement('a');
  419. elem.href = window.URL.createObjectURL(blob);
  420. elem.download = filename;
  421. document.body.appendChild(elem);
  422. elem.click();
  423. document.body.removeChild(elem);
  424. URL.revokeObjectURL(); // This needs an arg but I can't figure out what
  425. }
  426. var myFile = new Blob([fileContent], {type: 'text/plain'});
  427. window.URL = window.URL || window.webkitURL; document.getElementById('download').setAttribute('href',window.URL.createObjectURL(myFile));
  428. document.getElementById('download').setAttribute('download', fileName);
  429. }
  430. // BEGIN Publish tools, via SteinHQ.com
  431. // publishRule()
  432. // Publishes existing fields to new page, /builder/?rule=[ruleID]
  433. // Opens new page in Display mode
  434. function publishRule() {
  435. // Confirm user knows what they're getting into
  436. var r = confirm("Publish to the public Library?");
  437. if (r == false) { return; }
  438. // Proceed with publication
  439. var now = new Date();
  440. // Numerical ID for published Rule
  441. var timeID = now.getTime();
  442. // Readable UTC timestamp
  443. var dateTime = now.getUTCFullYear()+'.'+(now.getUTCMonth()+1)+'.'+now.getUTCDate()
  444. +' '+now.getUTCHours()+":"+ now.getUTCMinutes()+":"+now.getUTCSeconds()
  445. + ' UTC';
  446. // Check if ruleID exists; while yes, replace and repeat
  447. var rule = [{
  448. ruleID: timeID,
  449. timestamp: dateTime,
  450. }];
  451. // begin adding data
  452. // first, RuleBuilder data
  453. document.getElementById("builder-field").innerHTML = ""; // so it doesn't publish
  454. if (!builderEmpty()) {
  455. rule[0]["modules"] = document.getElementById("module-input").innerHTML;
  456. }
  457. // next, RuleWriter data
  458. var fields = document.getElementsByClassName("editable");
  459. for (var i = 0; i < fields.length; i++) {
  460. var key = fields[i].id;
  461. var value = "";
  462. // including input fields
  463. if (fields[i].nodeName == "INPUT") { // for <input>
  464. value = fields[i].value.replace(/(<([^>]+)>)/ig,"");
  465. } else { // for other fields
  466. value = fields[i].innerHTML.replace(/(<([^>]+)>)/ig,"");
  467. }
  468. rule[0][key] = value;
  469. }
  470. // add to lineage (if it is a fork)
  471. if (rID) {
  472. rule[0]["lineage"] = document.getElementById("lineage-list").innerHTML;
  473. }
  474. // add to database
  475. const store = new SteinStore(
  476. "https://api.steinhq.com/v1/storages/5e8b937ab88d3d04ae0816a5"
  477. );
  478. store.append("library", rule).then(data => {
  479. window.open("/create/?r=" + timeID, "_self", false);
  480. });
  481. }
  482. // addLineage
  483. // Adds the current page to the lineage
  484. function addLineage() {
  485. var communityname = document.getElementById("communityname").innerHTML;
  486. var newLineage = " < " + '<a href="/create/?r=' + rID + '">'
  487. + communityname + '</a>';
  488. var oldLineage = document.getElementById("lineage-list").innerHTML;
  489. document.getElementById("lineage-list").innerHTML = newLineage + oldLineage;
  490. }
  491. // fork()
  492. // Forks the current Rule and updates the derivation lineage
  493. function fork() {
  494. document.getElementById("lineage").style.display = "block";
  495. addLineage();
  496. toggleDisplayMode();
  497. }
  498. // displayRule(ID)
  499. // Displays content based on ID
  500. function displayRule(ID) {
  501. const store = new SteinStore(
  502. "https://api.steinhq.com/v1/storages/5e8b937ab88d3d04ae0816a5"
  503. );
  504. (async () => {
  505. var sheets = ["library","templates"];
  506. // create empty set of rules (should only get one member)
  507. var ruleArray = [];
  508. // read values from all sheets
  509. for (var i = 0; i < sheets.length; i++) {
  510. await store.read(sheets[i], { search: { ruleID: ID } }).then(data => {
  511. // test if there's anything in data
  512. if (data.length > 0) {
  513. ruleArray = data;
  514. }
  515. });
  516. }
  517. // Only runs the rest if the array has something
  518. if (ruleArray.length > 0) {
  519. var rule = ruleArray[0];
  520. var fields = document.getElementsByClassName("editable");
  521. for (var i = 0; i < fields.length; i++) {
  522. var key = fields[i].id;
  523. var value = rule[key];
  524. if (typeof value === "undefined") {
  525. value = "";
  526. } else if (key.includes("-")) { // links
  527. document.getElementById(key).value = value;
  528. } else {
  529. document.getElementById(key).innerHTML = value;
  530. }
  531. }
  532. // Add Builder content
  533. document.getElementById("module-input").innerHTML = rule["modules"];
  534. // Add lineage
  535. var lineage = rule["lineage"];
  536. if (typeof lineage === "undefined") {
  537. document.getElementById("lineage-list").innerHTML = "";
  538. } else {
  539. document.getElementById("lineage-list").innerHTML = lineage;
  540. document.getElementById("lineage").display = "block";
  541. }
  542. // Publish timestamp to Rule
  543. document.getElementById('dateTime').innerHTML = rule['timestamp'];
  544. // Finish
  545. displayMode = false;
  546. toggleDisplayMode();
  547. document.title = rule['communityname'] + " / CommunityRule";
  548. }
  549. })();
  550. }
  551. // deleteRule()
  552. // A temporary placeholder that sends an email requesting rule deletion
  553. function deleteRule() {
  554. var urlParamz = new URLSearchParams(window.location.search);
  555. var rID = urlParamz.get('r');
  556. window.open("mailto:medlab@colorado.edu?subject=Delete Rule request ("
  557. + rID + ")&body=Please explain your rationale:\n");
  558. }
  559. // END Publish tools
  560. // FINALLY, Page loading
  561. // First, grab the current URL
  562. var urlParams = new URLSearchParams(window.location.search);
  563. // Determine if it is a published Rule
  564. if (urlParams.has('r')) {
  565. // If so, grab the Rule from database and enter displayMode
  566. var rID = urlParams.get('r');
  567. displayRule(rID);
  568. } else {
  569. // Otherwise, open in editMode as default
  570. var editMode = true;
  571. }
  572. // eqip editable fields to remove formatting from pasted content
  573. window.onload = function() {
  574. var editableElements = document.getElementsByClassName("editable");
  575. for (var i = 0; i < editableElements.length; i++ ) {
  576. editableElements[i].addEventListener("paste", handleEditablePaste);
  577. }
  578. }
  579. </script>