Bläddra i källkod

add customTagUtils

Yuki Takei 7 år sedan
förälder
incheckning
35024d4780

+ 1 - 1
packages/growi-commons/package.json

@@ -1,6 +1,6 @@
 {
   "name": "growi-commons",
-  "version": "3.2.8",
+  "version": "4.0.0-beta",
   "description": "GROWI Commons Libraries",
   "keywords": [
     "growi"

+ 1 - 2
packages/growi-commons/src/index.js

@@ -2,8 +2,7 @@ module.exports = {
   BasicInterceptor: require('./util/basic-interceptor'),
   pathUtils: require('./util/path-utils'),
   // plugin
-  ArgsParser: require('./plugin/util/args-parser'),
-  OptionParser: require('./plugin/util/option-parser'),
+  customTagUtils: require('./plugin/util/custom-tag-utils'),
   // service
   LocalStorageManager: require('./service/localstorage-manager'),
 };

+ 0 - 4
packages/growi-commons/src/plugin/index.js

@@ -1,4 +0,0 @@
-module.exports = {
-  ArgsParser: require('./util/args-parser'),
-  OptionParser: require('./util/option-parser'),
-};

+ 11 - 0
packages/growi-commons/src/plugin/model/tag-context.js

@@ -0,0 +1,11 @@
+class TagContext {
+
+  constructor() {
+    this.tagExpression = null;
+    this.method = null;
+    this.args = null;
+  }
+
+}
+
+module.exports = TagContext;

+ 51 - 0
packages/growi-commons/src/plugin/util/custom-tag-utils.js

@@ -0,0 +1,51 @@
+const TagContext = require('../model/tag-context');
+
+/**
+ * @see http://qiita.com/ryounagaoka/items/4736c225bdd86a74d59c
+ *
+ * @param {number} length
+ * @return random strings
+ */
+function createRandomStr(length) {
+  const bag = 'abcdefghijklmnopqrstuvwxyz0123456789';
+  let generated = '';
+  for (let i = 0; i < length; i++) {
+    generated += bag[Math.floor(Math.random() * bag.length)];
+  }
+  return generated;
+}
+
+function findTagAndReplace(tagPattern, html, replace) {
+  // see: https://regex101.com/r/NQq3s9/9
+  const pattern = new RegExp(`\\$(${tagPattern.source})\\((.*?)\\)(?=[<\\[\\s\\$])|\\$(${tagPattern.source})\\((.*)\\)(?![<\\[\\s\\$])`, 'g');
+
+  const tagContextMap = {};
+  const replacedHtml = html.replace(pattern, (all, group1, group2, group3, group4) => {
+    const tagExpression = all;
+    const method = (group1 || group3).trim();
+    const args = (group2 || group4 || '').trim();
+
+    // create contexts
+    const tagContext = new TagContext();
+    tagContext.tagExpression = tagExpression;
+    tagContext.method = method;
+    tagContext.args = args;
+
+    if (replace != null) {
+      return replace(tagContext);
+    }
+
+    // replace with empty dom
+    const domId = `${method}-${createRandomStr(8)}`;
+    tagContextMap[domId] = tagContext;
+    return `<div id="${domId}"></div>`;
+  });
+
+  return { html: replacedHtml, tagContextMap };
+}
+
+module.exports = {
+  findTagAndReplace,
+  ArgsParser: require('./args-parser'),
+  OptionParser: require('./option-parser'),
+};

+ 0 - 3
packages/growi-commons/src/service/index.js

@@ -1,3 +0,0 @@
-module.exports = {
-  LocalStorageManager: require('./localstorage-manager'),
-};