Skip to content

Commit

Permalink
Merge pull request #57 from github/allow-processing-selected-text
Browse files Browse the repository at this point in the history
Add optional process func for selection text
  • Loading branch information
mattcosta7 authored Jun 4, 2024
2 parents 03be4f5 + 5e48bd5 commit 91db2a9
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
11 changes: 9 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import {extractFragment, insertMarkdownSyntax} from './markdown'

type ProcessSelectionTextFn = (str: string) => string

export class Quote {
selection = window.getSelection()
processSelectionText: ProcessSelectionTextFn = str => str

closest(selector: string): Element | null {
const startContainer = this.range.startContainer
Expand All @@ -25,8 +28,12 @@ export class Quote {
this.selection?.addRange(range)
}

set processSelectionTextFn(fn: ProcessSelectionTextFn) {
this.processSelectionText = fn
}

get selectionText(): string {
return this.selection?.toString().trim() || ''
return this.processSelectionText(this.selection?.toString().trim() || '')
}

get quotedText(): string {
Expand Down Expand Up @@ -91,6 +98,6 @@ export class MarkdownQuote extends Quote {
} finally {
body.removeChild(div)
}
return selectionText.trim()
return this.processSelectionText(selectionText.trim())
}
}
14 changes: 14 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,20 @@ describe('quote-selection', function () {

assert.equal(textarea.value, 'Has text\n\n> bold\n\n')
})

it('allows processing the quoted text before inserting it', function () {
const el = document.querySelector('#quotable')
const selection = window.getSelection()
window.getSelection = () => createSelection(selection, el)

const textarea = document.querySelector('#not-hidden-textarea')
const quote = new Quote()
quote.processSelectionTextFn = text => text.replace('Quotable', 'replaced')

quote.insert(textarea)

assert.equal(textarea.value, 'Has text\n\n> Test replaced text, bold.\n\n')
})
})

describe('with markdown enabled', function () {
Expand Down

0 comments on commit 91db2a9

Please sign in to comment.