All files / client/util/LangProcessor Template.ts

0% Statements 0/24
0% Branches 0/8
0% Functions 0/8
0% Lines 0/24

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76                                                                                                                                                       
import moment from 'moment'
import Crowi from 'client/crowi'
 
type templatePatternKey = keyof Template['templatePattern']
 
export default class Template {
  templatePattern: {
    year: () => string
    month: () => string
    date: () => string
    user: () => string
  }
 
  constructor(crowi: Crowi) {
    this.templatePattern = {
      year: this.getYear,
      month: this.getMonth,
      date: this.getDate,
      user: this.getUser,
    }
  }
 
  getYear(): string {
    return moment().format('YYYY')
  }
 
  getMonth(): string {
    return moment().format('YYYY/MM')
  }
 
  getDate(): string {
    return moment().format('YYYY/MM/DD')
  }
 
  getUser() {
    // FIXME
    const user = window.crowi.getUser()
    const username = user ? user.name : null
 
    if (!username) {
      return ''
    }
 
    return `/user/${username}`
  }
 
  parseTemplateString(templateString: string) {
    let parsed = templateString
 
    const templatePatternKeys = Object.keys(this.templatePattern) as templatePatternKey[]
    templatePatternKeys.forEach(key => {
      const k = key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
      const matcher = new RegExp(`{${k}}`, 'g')
      if (parsed.match(matcher)) {
        const replacer = this.templatePattern[key]()
        parsed = parsed.replace(matcher, replacer)
      }
    })
 
    return parsed
  }
 
  process(code: string, lang: string) {
    const templateId = new Date().getTime().toString(16) + Math.floor(1000 * Math.random()).toString(16)
    let pageName = lang
    if (lang.match(':')) {
      pageName = this.parseTemplateString(lang.split(':')[1])
    }
    code = this.parseTemplateString(code)
    return `
    <div class="page-template-builder">
    <button class="template-create-button btn btn-secondary" data-template="${templateId}" data-path="${pageName}"><i class="mdi mdi-pencil-outline"></i> ${pageName}</button>
      <pre><code id="${templateId}" class="lang-${lang}">${code}\n</code></pre></div>\n`
  }
}