1
0
mirror of https://git.sr.ht/~cadence/bibliogram synced 2024-11-22 16:17:29 +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,9 +1,20 @@
const constants = require("../constants") const constants = require("../constants")
function tryMatch(text, against, callback) { function tryMatch(text, against, callback) {
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) let matched = text.match(against)
if (matched) callback(matched) if (matched) callback(matched)
} }
}
function textToParts(text) { function textToParts(text) {
return [{type: "text", text: text}] return [{type: "text", text: text}]
@ -19,11 +30,16 @@ function replacePart(parts, index, match, replacements) {
function partsUsername(parts) { function partsUsername(parts) {
for (let i = 0; i < parts.length; i++) { for (let i = 0; i < parts.length; i++) {
if (parts[i].type === "text") { if (parts[i].type === "text") {
tryMatch(parts[i].text, `@(${constants.external.username_regex})`, match => { 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, [ replacePart(parts, i, match, [
{type: "user", text: match[0], user: match[1]} {type: "user", text: match[0], user: match[1]}
]) ])
i += 1 // skip parts: user i += 1 // skip the newly created part
return false
} else {
return true
}
}) })
} }
} }
@ -37,7 +53,7 @@ function partsHashtag(parts) {
replacePart(parts, i, match, [ replacePart(parts, i, match, [
{type: "hashtag", text: match[0], hashtag: match[1]} {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" "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() childTest.end()
}) })