Skip to content

Commit

Permalink
マークダウン形式からHTMLタグ形式への変換方法を外部から与えるフォーマット文字列を用いる方法に変更
Browse files Browse the repository at this point in the history
  • Loading branch information
goruchanchan committed Mar 10, 2024
1 parent 4ae6625 commit e417e84
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 16 deletions.
4 changes: 4 additions & 0 deletions app/javascript/textarea-initializer.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,10 @@ export default class {
responseKey: 'url',
csrfToken: CSRF.getToken(),
placeholder: '%filenameをアップロード中...',
uploadImageTag:
'<img src=%url width="100" height="100" loading="lazy" decoding="async" alt="%filename">\n',
uploadVideoTag: '<video controls src="%url"></video>\n',
uploadOtherTag: '[%filename (%fileSize)](%url)\n',
afterPreview: () => {
autosize.update(textarea)

Expand Down
32 changes: 16 additions & 16 deletions app/javascript/textarea-markdown-to-html.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,8 @@ export default class TextareaMarkdownToHtml extends TextareaMarkdown {
const bytes = new Uint8Array(reader.result)
const fileType = await FileType.fromBuffer(bytes)
const fileSize = filesize(file.size, { base: 10, standard: 'jedec' })
const text = `<img src=${this.options.placeholder.replace(
/%filename/,
file.name
)} >`
const text =
'![' + this.options.placeholder.replace(/%filename/, file.name) + ']()'

const beforeRange = this.textarea.selectionStart
const beforeText = this.textarea.value.substring(0, beforeRange)
Expand Down Expand Up @@ -48,21 +46,23 @@ export default class TextareaMarkdownToHtml extends TextareaMarkdown {
const responseKey = this.options.responseKey
const url = json[responseKey]
if (this.options.imageableExtensions.includes(fileType.ext)) {
this.textarea.value = this.textarea.value.replace(
text,
`<img src=${url} width="100" height="100" loading="lazy" decoding="async" alt="${file.name}">\n`
)
const uploadTag = this.options.uploadImageTag
.replace(/%filename/, file.name)
.replace(/%url/, url)
this.textarea.value = this.textarea.value.replace(text, uploadTag)
} else if (this.options.videoExtensions.includes(fileType.ext)) {
this.textarea.value = this.textarea.value.replace(
text,
`<video controls src="${url}"></video>\n`
)
const uploadTag = this.options.uploadVideoTag
.replace(/%filename/, file.name)
.replace(/%url/, url)
this.textarea.value = this.textarea.value.replace(text, uploadTag)
} else {
this.textarea.value = this.textarea.value.replace(
text,
`[${file.name} (${fileSize})](${url})\n`
)
const uploadTag = this.options.uploadOtherTag
.replace(/%filename/, file.name)
.replace(/%url/, url)
.replace(/%fileSize/, fileSize)
this.textarea.value = this.textarea.value.replace(text, uploadTag)
}

this.applyPreview()
})
.catch((error) => {
Expand Down

0 comments on commit e417e84

Please sign in to comment.