Преглед на файлове

basic feature implementation

Rohit Taware преди 1 година
родител
ревизия
a4d1eda3b8
променени са 3 файла, в които са добавени 198 реда и са изтрити 35 реда
  1. 7 1
      _includes/vue-rule-script.html
  2. 21 3
      _layouts/library.html
  3. 170 31
      assets/js/vue.rules.js

+ 7 - 1
_includes/vue-rule-script.html

@@ -231,12 +231,18 @@
             </div>
         </div>
         <div class="btn-group" v-if="!legacy && !view">
-            <vue-button class="primary is-large" @click="handleClickPublish" :icon="icons.publish" :loading="publishing">Publish</vue-button>
+            <!-- <vue-button class="primary is-large" @click="handleClickPublish" :icon="icons.publish" :loading="publishing">Publish</vue-button> -->
+            <vue-button v-if="edit" class="primary is-large" @click="handleClickPublish" :icon="icons.edit" :loading="editing">
+                Edit
+              </vue-button>
+              <vue-button v-else class="primary is-large" @click="handleClickPublish" :icon="icons.publish" :loading="publishing">Publish</vue-button>
+              </vue-button>
             <vue-button class="is-large" @click="handleClickDownload" :icon="icons.download">Download</vue-button>
             <vue-button class="is-large" @click="handleClickImport" :icon="icons.upload">Import <div class="btn-cover">coming soon!</div></vue-button>
         </div>
         <div class="btn-group" v-if="view && !legacy">
             <vue-button class="primary is-large" @click="clickPreview" :icon="icons.fork">Fork &amp; Edit</vue-button>
+            <vue-button class="primary is-large" @click="clickPreviewEdit" :icon="icons.fork">Edit </vue-button>
             <vue-button class="is-large" @click="handleClickDownload" :icon="icons.download">Download</vue-button>
         </div>
     </div>

+ 21 - 3
_layouts/library.html

@@ -9,10 +9,26 @@ layout: default
       const store = new SteinStore(
           "https://api.steinhq.com/v1/storages/5e8b937ab88d3d04ae0816a5"
       );
+
+      const backendUrl = "http://localhost:3000/api/get_rules";
       var rules = "";
-      store.read(sheet, { limit: 0, offset: 0 }).then(data => {
-          rules = data.reverse();
+    
+    fetch(backendUrl, {
+          method: 'GET',
+          headers: {
+              'Content-Type': 'application/json',
+              // Add any other headers you may need, such as authorization headers
+          },
+    }).then(response => {
+        if (!response.ok) {
+            throw new Error('Network response was not ok');
+        }
+        return response.json(); // This returns another Promise
+    }).then(data => {
+            
           libHTML = "";
+          rules = JSON.parse(data.rules)
+        //   console.log(JSON.parse(rules))
           // iterating over all the rules
           for (var i = 0; i < rules.length; i++) {
               libHTML += "<div class='library-item'>\n";
@@ -22,11 +38,12 @@ layout: default
               if (icon != null) {
                   iconHTML = "<span class='icon'><img src='" + icon + "' /></span>";
               }
+
               // first the titles
               var title = rules[i]["name"];
               if (title == null) { title = "Untitled"; }
               libHTML += "<h2 class='library-rule-name'>" + 
-                  "<a href='/create/?r=" + rules[i]["ruleID"] + "'>" + iconHTML +
+                  "<a href='/create/?r=" + rules[i]["rule_id"] + "'>" + iconHTML +
                   title + "</a></h2>\n";
               // then the authors
               var author = rules[i]["creatorName"];
@@ -57,6 +74,7 @@ layout: default
           }
           libHTML += "</div>\n";
           document.getElementById("librarylist").innerHTML = libHTML;
+          console.log(libHTML)
       });
   }
 

+ 170 - 31
assets/js/vue.rules.js

@@ -28,16 +28,20 @@ const app = Vue.createApp({
           name: "",
           url: "",
         },
-        modules: []
+        modules: [],
+        latest_version: 1
       },
       legacy: false,
       rID: false,
       loading: false,
       publishing: false,
+      edit: false,
       view: (global.rule) ? true : false,
       preview: (global.rule) ? true : false,
       template: (global.rule) ? true : false,
       steinAPI: 'https://api.steinhq.com/v1/storages/5e8b937ab88d3d04ae0816a5',
+      backendUrl: 'http://localhost:3000/api/validate_otp',
+      backendUrlrule: 'http://localhost:3000/api/get_rule',
       // TODO keep an array of past states for undo/redo
       history: [],
       // the data of the current module in the editor
@@ -452,17 +456,89 @@ const app = Vue.createApp({
       const store = new SteinStore(
         this.steinAPI
       );
+      const backendUrlGetRule = this.backendUrlrule + "?ruleId="+id;
 
       (async () => {
         var rule = [];
         // read values from all sheets
-        await store.read('rules', { search: { ruleID: id } }).then(data => {
-          // test if there's anything in data
-          if (data.length > 0) {
-            rule = data[0];
-          }
-          console.log(rule);
-        });
+        console.log(backendUrlGetRule)
+        await fetch(backendUrlGetRule, {
+        method: 'GET',
+        headers: {
+            'Content-Type': 'application/json',
+            // Add any other headers you may need, such as authorization headers
+        },
+      }).then(response => {
+        if (!response.ok) {
+          throw new Error('Network response was not ok');
+        }
+        return response.json(); // This returns another Promise
+      })
+      .then (data => {
+
+        if (data.rules.length > 0) {
+          rule = JSON.parse(data.rules)[0];
+        }
+
+      });
+        // no rule found, exit
+        // TODO: inform the user that the rule was not found
+        if (!rule) {
+          this.loading = false;
+          return;
+        }
+        // if this is a legacy (pre-v3) set it as such
+        if (rule.version < 3) {
+          this.loading = false;
+          this.legacy = true;
+          this.rule = rule;
+
+          Vue.nextTick(() => {
+            if (rule.version == 2) displayBuilderHTML();
+          });
+
+          return;
+        }
+        this.rule = {
+          ruleID: rule.rule_id,
+          timestamp: rule.time_stamp,
+          icon: rule.icon,
+          name: rule.name,
+          lineage: rule.lineage,
+          summary: rule.summary,
+          config: rule.config,  
+          creator: {
+            name: rule.creator_name,
+            url: rule.creator_url,
+          },
+          modules: (rule.modules) ? JSON.parse(rule.modules) : [],
+          latest_version: rule.latest_version
+        }
+
+        console.log(this.rule.latest_version)
+        /** Add name to <title> for v3+ rules */
+        document.title = rule.name + " / CommunityRule"
+          
+        this.loading = false;
+        
+      })();
+      /*fetch(backendUrlGetRule, {
+        method: 'GET',
+        headers: {
+            'Content-Type': 'application/json',
+            // Add any other headers you may need, such as authorization headers
+        },
+      }).then(response => {
+        if (!response.ok) {
+          throw new Error('Network response was not ok');
+        }
+        return response.json(); // This returns another Promise
+      }).then (data => {
+        var rule = [];
+
+        if (data.rules.length > 0) {
+          rule = data.rules;
+        }
 
         // no rule found, exit
         // TODO: inform the user that the rule was not found
@@ -498,13 +574,13 @@ const app = Vue.createApp({
           },
           modules: (rule.modules) ? JSON.parse(rule.modules) : []
         }
+        console.log('dadsfasdfasdfasdfasdf')
+        console.log(this.rule)
 
-        /** Add name to <title> for v3+ rules */
         document.title = rule.name + " / CommunityRule"
           
         this.loading = false;
-        
-      })();
+      }); */
     },
 
     // editor methods =========================================================
@@ -651,7 +727,6 @@ const app = Vue.createApp({
       console.log(msg);
     },
 
-    // export and download methods =============================================
 
     /**
      * Handles click event for publishing the rule
@@ -673,28 +748,83 @@ const app = Vue.createApp({
       this.publishing = true;
 
       const rule = this.ruleExport;
-      const ruleID = new Date().getTime(); // TODO: allow for custom named IDs, check for uniqueness
+      var ruleID = new Date().getTime(); // TODO: allow for custom named IDs, check for uniqueness
+      if (this.edit) {
+        console.log('asdfasdfasdfasdf' + this.rule.ruleID)
+        ruleID = this.rule.ruleID;
+      } 
+      var latest_ver = 1;
 
+      if (this.edit) {
+        latest_ver = parseInt(this.rule.latest_version) + 1;
+        console.log('Updated version' + latest_ver)
+      }
+// ------------------ exisituing code ---------------
       // add to database
-      const store = new SteinStore(
-        this.steinAPI
-      );
+    //   const store = new SteinStore(
+    //     this.steinAPI
+    //   );
+
+    //   store.append('rules', [{
+    //     ruleID: ruleID,
+    //     timestamp: rule.timestamp,
+    //     icon: rule.icon,
+    //     name: rule.name,
+    //     lineage: rule.lineage,
+    //     summary: rule.summary,
+    //     config: this.jsonify(rule.config),
+    //     modules: this.jsonify(rule.modules),
+    //     creatorName: rule.creator.name,
+    //     creatorUrl: rule.creator.url,
+    //     version: 3
+    //   }]).then(data => {
+    //     this.publishing = false;
+    //     window.open("/create/?r=" + ruleID, "_self", false);
+    //   });
+
+    // -=---------------------------- updated code -------------------
 
-      store.append('rules', [{
-        ruleID: ruleID,
-        timestamp: rule.timestamp,
-        icon: rule.icon,
-        name: rule.name,
-        lineage: rule.lineage,
-        summary: rule.summary,
-        config: this.jsonify(rule.config),
-        modules: this.jsonify(rule.modules),
-        creatorName: rule.creator.name,
-        creatorUrl: rule.creator.url,
-        version: 3
-      }]).then(data => {
-        this.publishing = false;
-        window.open("/create/?r=" + ruleID, "_self", false);
+    const requestData = {
+          ruleID: ruleID,
+          timestamp: rule.timestamp,
+          icon: rule.icon,
+          name: rule.name,
+          lineage: rule.lineage,
+          summary: rule.summary,
+          config: this.jsonify(rule.config),
+          modules: this.jsonify(rule.modules),
+          creatorName: rule.creator.name,
+          creatorUrl: rule.creator.url,
+          email: 'rota3015@colorado.edu',
+          edit: this.edit,
+          otp: 1234,
+          version: 3,
+          latest_version: latest_ver
+        }
+    
+    fetch(this.backendUrl, {
+          method: 'POST',
+          headers: {
+              'Content-Type': 'application/json',
+              'Access-Control-Allow-Methods': 'POST',
+              'Access-Control-Allow-Headers': 'Content-Type'
+              // Add any other headers you may need, such as authorization headers
+          },
+          body: JSON.stringify(requestData),
+      }).then(response => {
+        if (!response.ok) {
+            throw new Error(`HTTP error! Status: ${response.status}`);
+        }
+        return response.json(); // or response.text() if expecting plain text
+      }).then(data => {
+        // Handle the data received from the backend
+        console.log('Data from backend:', data);
+      }).then(data => {
+              this.publishing = false;
+              window.open("/create/?r=" + ruleID, "_self", false);
+      }).catch(error => {
+        // Handle errors that occurred during the fetch
+        console.error('Fetch error:', error);
       });
     },
     /**
@@ -763,6 +893,15 @@ const app = Vue.createApp({
       this.view = false;
       this.preview = !this.preview;
     },
+    /**
+     * Handles the click event for activating the rule preview for edit rule
+     */
+    clickPreviewEdit() {
+      if(this.template) this.rule.icon = ''; // TODO: find a less hacky way to reset template icons
+        this.view = false;
+        this.preview = !this.preview;
+        this.edit = true;
+    },
     /**
      * Filters module library based on the search term
      * @param {String} type the name of the type to filter