1
0
mirror of https://git.sr.ht/~cadence/bibliogram synced 2024-11-22 08:07:30 +00:00
This commit is contained in:
Cadence Ember 2020-05-19 19:03:03 +12:00
parent d4b869046e
commit d285722ddf
No known key found for this signature in database
GPG Key ID: 128B99B1B74A6412
2 changed files with 44 additions and 8 deletions

View File

@ -1,8 +1,19 @@
const constants = require("../constants")
function tryMatch(text, against, callback) {
let matched = text.match(against)
if (matched) callback(matched)
if (against instanceof RegExp && against.global) {
// if it's a global match, keep sending matches to the callback while the callback returns true
let matched
let ok = true
while (ok && (matched = against.exec(text))) {
ok = callback(matched)
}
against.lastIndex = 0
} else {
// if it's a non-global match, just do the match.
let matched = text.match(against)
if (matched) callback(matched)
}
}
function textToParts(text) {
@ -19,11 +30,16 @@ function replacePart(parts, index, match, replacements) {
function partsUsername(parts) {
for (let i = 0; i < parts.length; i++) {
if (parts[i].type === "text") {
tryMatch(parts[i].text, `@(${constants.external.username_regex})`, match => {
replacePart(parts, i, match, [
{type: "user", text: match[0], user: match[1]}
])
i += 1 // skip parts: user
tryMatch(parts[i].text, new RegExp(`@(${constants.external.username_regex})`, "g"), match => {
if (match.index === 0 || parts[i].text[match.index-1].match(/\s/)) { // check that there's a space before the username
replacePart(parts, i, match, [
{type: "user", text: match[0], user: match[1]}
])
i += 1 // skip the newly created part
return false
} else {
return true
}
})
}
}
@ -37,7 +53,7 @@ function partsHashtag(parts) {
replacePart(parts, i, match, [
{type: "hashtag", text: match[0], hashtag: match[1]}
])
i += 1 // skip parts: hashtag
i += 1 // skip the newly created part
})
}
}

View File

@ -132,5 +132,25 @@ tap.test("entire structure works", childTest => {
"special characters"
)
// email address
childTest.same(
structure("someaddress@gmail.com"),
[
{type: "text", text: "someaddress@gmail.com"}
],
"email address"
)
// email address + username
childTest.same(
structure("someaddress@gmail.com @gmail.com"),
[
{type: "text", text: "someaddress@gmail.com "},
{type: "user", text: "@gmail.com", user: "gmail.com"},
{type: "text", text: ""}
],
"email address"
)
childTest.end()
})