Просмотр исходного кода

refactor and typescriptize to fix lint errors

Yuki Takei 3 лет назад
Родитель
Сommit
04b2a5f8c0

+ 2 - 2
packages/core/src/index.ts

@@ -1,11 +1,10 @@
-import * as _customTagUtils from './plugin/util/custom-tag-utils';
 import * as _envUtils from './utils/env-utils';
 
 // export utils by *.js
 export const envUtils = _envUtils;
-export const customTagUtils = _customTagUtils;
 
 // export utils with namespace
+export * as customTagUtils from './plugin/util/custom-tag-utils';
 export * as templateChecker from './utils/template-checker';
 export * as objectIdUtils from './utils/objectid-utils';
 export * as pagePathUtils from './utils/page-path-utils';
@@ -13,6 +12,7 @@ export * as pathUtils from './utils/path-utils';
 export * as pageUtils from './utils/page-utils';
 
 // export all
+export * from './plugin/interfaces/option-parser';
 export * from './interfaces/attachment';
 export * from './interfaces/common';
 export * from './interfaces/has-object-id';

+ 4 - 0
packages/core/src/plugin/interfaces/option-parser.ts

@@ -0,0 +1,4 @@
+export type ParseRangeResult = {
+  start: number,
+  end: number,
+}

+ 8 - 4
packages/core/src/plugin/model/tag-context.js → packages/core/src/plugin/model/tag-context.ts

@@ -1,14 +1,18 @@
 /**
  * Context class for custom-tag-utils#findTagAndReplace
  */
-class TagContext {
+export class TagContext {
 
-  constructor(initArgs = {}) {
+  tagExpression: string | null;
+
+  method: string | null;
+
+  args: any;
+
+  constructor(initArgs: any = {}) {
     this.tagExpression = initArgs.tagExpression || null;
     this.method = initArgs.method || null;
     this.args = initArgs.args || null;
   }
 
 }
-
-module.exports = TagContext;

+ 1 - 3
packages/core/src/plugin/util/args-parser.js

@@ -1,7 +1,7 @@
 /**
  * Arguments parser for custom tag
  */
-class ArgsParser {
+export class ArgsParser {
 
   /**
    * @typedef ParseArgsResult
@@ -55,5 +55,3 @@ class ArgsParser {
   }
 
 }
-
-module.exports = ArgsParser;

+ 0 - 88
packages/core/src/plugin/util/custom-tag-utils.js

@@ -1,88 +0,0 @@
-const TagContext = require('../model/tag-context');
-
-/**
- * @private
- *
- * create random strings
- * @see http://qiita.com/ryounagaoka/items/4736c225bdd86a74d59c
- *
- * @param {number} length
- * @return {string} 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;
-}
-
-/**
- * @typedef FindTagAndReplaceResult
- * @property {string} html - HTML string
- * @property {Object} tagContextMap - Object.<string, [TagContext]{@link ../model/tag-context.html#TagContext}>
- *
- * @memberof customTagUtils
- */
-/**
- * @param {RegExp} tagPattern
- * @param {string} html
- * @param {function} replace replace function
- * @return {FindTagAndReplaceResult}
- *
- * @memberof customTagUtils
- */
-function findTagAndReplace(tagPattern, html, replace) {
-  let replacedHtml = html;
-  const tagContextMap = {};
-
-  if (tagPattern == null || html == null) {
-    return { html: replacedHtml, tagContextMap };
-  }
-
-  // see: https://regex101.com/r/NQq3s9/9
-  const pattern = new RegExp(`\\$(${tagPattern.source})\\((.*?)\\)(?=[<\\[\\s\\$])|\\$(${tagPattern.source})\\((.*)\\)(?![<\\[\\s\\$])`, 'g');
-
-  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({ tagExpression, method, 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 };
-}
-
-/**
- * @namespace customTagUtils
- */
-module.exports = {
-  findTagAndReplace,
-  /**
-   * Context class used by findTagAndReplace
-   * @memberof customTagUtils
-   */
-  TagContext,
-  /**
-   * [ArgsParser]{@link ./args-parser#ArgsParser}
-   * @memberof customTagUtils
-   */
-  ArgsParser: require('./args-parser'),
-  /**
-   * [OptionParser]{@link ./option-parser#OptionParser}
-   * @memberof customTagUtils
-   */
-  OptionParser: require('./option-parser'),
-};

+ 5 - 0
packages/core/src/plugin/util/custom-tag-utils.ts

@@ -0,0 +1,5 @@
+export * from '../model/tag-context';
+
+export * from './args-parser';
+
+export * from './option-parser';

+ 4 - 10
packages/core/src/plugin/util/option-parser.js → packages/core/src/plugin/util/option-parser.ts

@@ -1,13 +1,9 @@
+import { ParseRangeResult } from '../interfaces/option-parser';
+
 /**
  * Options parser for custom tag
  */
-class OptionParser {
-
-  /**
-   * @typedef ParseRangeResult
-   * @property {number} start - start index
-   * @property {number} end - end index
-   */
+export class OptionParser {
 
   /**
    * Parse range expression
@@ -27,7 +23,7 @@ class OptionParser {
    * @param {string} str
    * @returns {ParseRangeResult}
    */
-  static parseRange(str) {
+  static parseRange(str: string): ParseRangeResult | null {
     if (str == null) {
       return null;
     }
@@ -66,5 +62,3 @@ class OptionParser {
   }
 
 }
-
-module.exports = OptionParser;

+ 2 - 2
packages/core/src/test/plugin/service/tag-cache-manager.test.js

@@ -3,8 +3,8 @@
 // import each from 'jest-each';
 jest.mock('~/service/localstorage-manager');
 
-import * as TagCacheManager from '~/plugin/service/tag-cache-manager';
-import * as LocalStorageManager from '~/service/localstorage-manager';
+import { TagCacheManager } from '~/plugin/service/tag-cache-manager';
+import { LocalStorageManager } from '~/service/localstorage-manager';
 /* eslint-enable import/first */
 
 describe('TagCacheManager.constructor', () => {

+ 1 - 1
packages/core/src/test/plugin/util/args-parser.test.js

@@ -1,4 +1,4 @@
-import ArgsParser from '~/plugin/util/args-parser';
+import { ArgsParser } from '~/plugin/util/args-parser';
 
 describe('args-parser', () => {
 

+ 50 - 48
packages/core/src/test/plugin/util/custom-tag-utils.test.js

@@ -1,8 +1,9 @@
 import rewire from 'rewire';
 
-import customTagUtils from '~/plugin/util/custom-tag-utils';
+import * as customTagUtils from '~/plugin/util/custom-tag-utils';
 
-const rewiredCustomTagUtils = rewire('../../../plugin/util/custom-tag-utils');
+// leave it commented out for rewire example -- 2022.08.18 Yuki Takei
+// const rewiredCustomTagUtils = rewire('../../../plugin/util/custom-tag-utils');
 
 describe('customTagUtils', () => {
 
@@ -21,52 +22,53 @@ describe('customTagUtils', () => {
     expect(typeof customTagUtils.OptionParser).toBe('function');
   });
 
-  test('.createRandomStr(10) returns random string', () => {
-    // get private resource
-    const createRandomStr = rewiredCustomTagUtils.__get__('createRandomStr');
-    expect(createRandomStr(10)).toMatch(/^[a-z0-9]{10}$/);
-  });
-
-  test('.findTagAndReplace() returns default object when tagPattern is null', () => {
-    const htmlMock = jest.fn();
-    htmlMock.replace = jest.fn();
-
-    const result = customTagUtils.findTagAndReplace(null, '');
-
-    expect(result).toEqual({ html: '', tagContextMap: {} });
-    expect(htmlMock.replace).not.toHaveBeenCalled();
-  });
-
-  test('.findTagAndReplace() returns default object when html is null', () => {
-    const tagPatternMock = jest.fn();
-    tagPatternMock.source = jest.fn();
-
-    const result = customTagUtils.findTagAndReplace(tagPatternMock, null);
-
-    expect(result).toEqual({ html: null, tagContextMap: {} });
-    expect(tagPatternMock.source).not.toHaveBeenCalled();
-  });
-
-  test('.findTagAndReplace() works correctly', () => {
-    // setup mocks for private function
-    rewiredCustomTagUtils.__set__('createRandomStr', (length) => {
-      return 'dummyDomId';
-    });
-
-    const tagPattern = /ls|lsx/;
-    const html = '<section><h1>header</h1>\n$ls(/)</section>';
-
-    const result = rewiredCustomTagUtils.findTagAndReplace(tagPattern, html);
-
-    expect(result.html).toMatch(/<section><h1>header<\/h1>\n<div id="ls-dummyDomId"><\/div>/);
-    expect(result.tagContextMap).toEqual({
-      'ls-dummyDomId': {
-        tagExpression: '$ls(/)',
-        method: 'ls',
-        args: '/',
-      },
-    });
-  });
+  // leave it commented out for rewire example -- 2022.08.18 Yuki Takei
+  // test('.createRandomStr(10) returns random string', () => {
+  //   // get private resource
+  //   const createRandomStr = rewiredCustomTagUtils.__get__('createRandomStr');
+  //   expect(createRandomStr(10)).toMatch(/^[a-z0-9]{10}$/);
+  // });
+
+  // test('.findTagAndReplace() returns default object when tagPattern is null', () => {
+  //   const htmlMock = jest.fn();
+  //   htmlMock.replace = jest.fn();
+
+  //   const result = customTagUtils.findTagAndReplace(null, '');
+
+  //   expect(result).toEqual({ html: '', tagContextMap: {} });
+  //   expect(htmlMock.replace).not.toHaveBeenCalled();
+  // });
+
+  // test('.findTagAndReplace() returns default object when html is null', () => {
+  //   const tagPatternMock = jest.fn();
+  //   tagPatternMock.source = jest.fn();
+
+  //   const result = customTagUtils.findTagAndReplace(tagPatternMock, null);
+
+  //   expect(result).toEqual({ html: null, tagContextMap: {} });
+  //   expect(tagPatternMock.source).not.toHaveBeenCalled();
+  // });
+
+  // test('.findTagAndReplace() works correctly', () => {
+  //   // setup mocks for private function
+  //   rewiredCustomTagUtils.__set__('createRandomStr', (length) => {
+  //     return 'dummyDomId';
+  //   });
+
+  //   const tagPattern = /ls|lsx/;
+  //   const html = '<section><h1>header</h1>\n$ls(/)</section>';
+
+  //   const result = rewiredCustomTagUtils.findTagAndReplace(tagPattern, html);
+
+  //   expect(result.html).toMatch(/<section><h1>header<\/h1>\n<div id="ls-dummyDomId"><\/div>/);
+  //   expect(result.tagContextMap).toEqual({
+  //     'ls-dummyDomId': {
+  //       tagExpression: '$ls(/)',
+  //       method: 'ls',
+  //       args: '/',
+  //     },
+  //   });
+  // });
 
 
 });

+ 1 - 1
packages/core/src/test/plugin/util/option-parser.test.js

@@ -1,6 +1,6 @@
 import each from 'jest-each';
 
-import OptionParser from '~/plugin/util/option-parser';
+import { OptionParser } from '~/plugin/util/option-parser';
 
 describe('option-parser', () => {
 

+ 1 - 1
packages/core/src/test/service/localstorage-manager.test.js

@@ -1,7 +1,7 @@
 // eslint-disable-next-line import/no-unresolved
 import 'jest-localstorage-mock';
 
-import * as LocalStorageManager from '~/service/localstorage-manager';
+import { LocalStorageManager } from '~/service/localstorage-manager';
 
 let localStorageManager = null;
 

+ 3 - 3
packages/plugin-lsx/src/components/lsx-context.ts

@@ -1,4 +1,4 @@
-import { customTagUtils } from '@growi/core';
+import { customTagUtils, ParseRangeResult } from '@growi/core';
 
 const { OptionParser } = customTagUtils;
 
@@ -18,9 +18,9 @@ export class LsxContext {
     this.options = options;
   }
 
-  getOptDepth() {
+  getOptDepth(): ParseRangeResult | null {
     if (this.options?.depth == null) {
-      return undefined;
+      return null;
     }
     return OptionParser.parseRange(this.options.depth);
   }