@instructure/quiz-interactions
Version:
A React UI component Library for quiz interaction types.
46 lines (40 loc) • 2.47 kB
JavaScript
// Some punctuation needs to be grouped/rendered with the blank
// so it does not get awkwardly separated by a line break.
// NOTE: these lists of punctuation are likely incomplete for full i18n support
// all "ending" punctuation symbols at beginning of string until whitespace or end of string
// e.g `, and flowers` (the comma is considered "ending" punctuation)
const ENDING_PUNCTUATION_REGEX =
/^[,,、.::;;!!??%‰"”'’`′″‴\]]】))}>»›」﹂』…⋯᠁ฯ》〉。]*(\s|$)/g
// all "starting" punctuation at end of string following whitespace or start of string
// e.g. `John said, "` (the opening quote is considered "starting" punctuation)
const STARTING_PUNCTUATION_REGEX = /(\s|^)["“'‘`[[【(({<«‹「﹁『《〈¿¡]*$/g
export const trimPunctuation = (stemItem, stemItems) => {
// Trim all punctuation that will be grouped/rendered with the blank.
// e.g. Fill in the _____. (group the period with the blank)
// e.g. Complete the quote: "_____ wrongs don't make a right." (group the opening quote with the blank)
const isFirstStemItem = stemItem.position === 1
const isLastStemItem = stemItem.position === stemItems.length
const initialValue = stemItem.value || ''
// trim "ending" punctuation symbols from start of string (unless first item)
const endingsTrimmed = isFirstStemItem
? initialValue.trim()
: initialValue.trim().replace(ENDING_PUNCTUATION_REGEX, '')
// trim "starting" punctuation symbols from end of string (unless last item)
const startsTrimmed = isLastStemItem
? endingsTrimmed
: endingsTrimmed.replace(STARTING_PUNCTUATION_REGEX, '')
return startsTrimmed
}
export const getTrimmedPunctuation = (stemItem, stemItems) => {
const nextStemItem = stemItems.find(si => si.position === stemItem.position + 1)
const nextStemItemValue = nextStemItem && nextStemItem.value
const endPunctuationMatch =
nextStemItemValue && nextStemItemValue.trim().match(ENDING_PUNCTUATION_REGEX)
const endPunctuation = endPunctuationMatch ? endPunctuationMatch[0] : ''
const prevStemItem = stemItems.find(si => si.position === stemItem.position - 1)
const prevStemItemValue = prevStemItem && prevStemItem.value
const startPunctuationMatch =
prevStemItemValue && prevStemItemValue.trim().match(STARTING_PUNCTUATION_REGEX)
const startPunctuation = startPunctuationMatch ? startPunctuationMatch[0] : ''
return {start: startPunctuation, end: endPunctuation}
}