You've already forked AstralRinth
forked from didirus/AstralRinth
Move files in preparation for monorepo migration
This commit is contained in:
377
libs/omorphia/lib/helpers/codemirror.ts
Normal file
377
libs/omorphia/lib/helpers/codemirror.ts
Normal file
@@ -0,0 +1,377 @@
|
||||
import { insertNewlineAndIndent } from '@codemirror/commands'
|
||||
import { deleteMarkupBackward } from '@codemirror/lang-markdown'
|
||||
import { getIndentation, indentString, syntaxTree } from '@codemirror/language'
|
||||
import { type EditorState, type Transaction } from '@codemirror/state'
|
||||
import { type EditorView, type Command, type KeyBinding } from '@codemirror/view'
|
||||
|
||||
const toggleBold: Command = ({ state, dispatch }) => {
|
||||
return toggleAround(state, dispatch, '**', '**')
|
||||
}
|
||||
|
||||
const toggleItalic: Command = ({ state, dispatch }) => {
|
||||
return toggleAround(state, dispatch, '_', '_')
|
||||
}
|
||||
|
||||
const toggleStrikethrough: Command = ({ state, dispatch }) => {
|
||||
return toggleAround(state, dispatch, '~~', '~~')
|
||||
}
|
||||
|
||||
const toggleCodeBlock: Command = ({ state, dispatch }) => {
|
||||
const lineBreak = state.lineBreak
|
||||
const codeBlockMark = lineBreak + '```' + lineBreak
|
||||
return toggleAround(state, dispatch, codeBlockMark, codeBlockMark)
|
||||
}
|
||||
|
||||
const toggleSpoiler: Command = ({ state, dispatch }) => {
|
||||
// Insert details tag with a summary tag at the start
|
||||
const detailsTags = ['\n<details>\n<summary>Spoiler</summary>\n\n', '\n\n</details>\n\n']
|
||||
return toggleAround(state, dispatch, detailsTags[0], detailsTags[1])
|
||||
}
|
||||
|
||||
const toggleHeader: Command = ({ state, dispatch }) => {
|
||||
return toggleLineStart(state, dispatch, '# ')
|
||||
}
|
||||
|
||||
const toggleHeader2: Command = ({ state, dispatch }) => {
|
||||
return toggleLineStart(state, dispatch, '## ')
|
||||
}
|
||||
|
||||
const toggleHeader3: Command = ({ state, dispatch }) => {
|
||||
return toggleLineStart(state, dispatch, '### ')
|
||||
}
|
||||
|
||||
const toggleHeader4: Command = ({ state, dispatch }) => {
|
||||
return toggleLineStart(state, dispatch, '#### ')
|
||||
}
|
||||
|
||||
const toggleHeader5: Command = ({ state, dispatch }) => {
|
||||
return toggleLineStart(state, dispatch, '##### ')
|
||||
}
|
||||
|
||||
const toggleHeader6: Command = ({ state, dispatch }) => {
|
||||
return toggleLineStart(state, dispatch, '###### ')
|
||||
}
|
||||
|
||||
const toggleQuote: Command = ({ state, dispatch }) => {
|
||||
return toggleLineStart(state, dispatch, '> ')
|
||||
}
|
||||
|
||||
const toggleBulletList: Command = ({ state, dispatch }) => {
|
||||
return toggleLineStart(state, dispatch, '- ')
|
||||
}
|
||||
|
||||
const toggleOrderedList: Command = ({ state, dispatch }) => {
|
||||
return toggleLineStart(state, dispatch, '1. ')
|
||||
}
|
||||
|
||||
const yankSelection = ({ state }: EditorView): string => {
|
||||
const { from, to } = state.selection.main
|
||||
const selectedText = state.doc.sliceString(from, to)
|
||||
return selectedText
|
||||
}
|
||||
|
||||
const replaceSelection = ({ state, dispatch }: EditorView, text: string) => {
|
||||
const { from, to } = state.selection.main
|
||||
const transaction = state.update({
|
||||
changes: { from, to, insert: text },
|
||||
selection: { anchor: from + text.length, head: from + text.length },
|
||||
})
|
||||
dispatch(transaction)
|
||||
return true
|
||||
}
|
||||
|
||||
type Dispatch = (tr: Transaction) => void
|
||||
|
||||
const surroundedByText = (
|
||||
state: EditorState,
|
||||
open: string,
|
||||
close: string
|
||||
): 'inclusive' | 'exclusive' | 'none' => {
|
||||
const { from, to } = state.selection.main
|
||||
|
||||
// Check for inclusive surrounding first
|
||||
const selectedText = state.doc.sliceString(from, to)
|
||||
if (selectedText.startsWith(open) && selectedText.endsWith(close)) {
|
||||
return 'inclusive'
|
||||
}
|
||||
|
||||
// Then check for exclusive surrounding
|
||||
const beforeText = state.doc.sliceString(Math.max(0, from - open.length), from)
|
||||
const afterText = state.doc.sliceString(to, to + close.length)
|
||||
if (beforeText === open && afterText === close) {
|
||||
return 'exclusive'
|
||||
}
|
||||
|
||||
// Return 'none' if no surrounding detected
|
||||
return 'none'
|
||||
}
|
||||
|
||||
// TODO: Node based toggleAround so that we can support nested delimiters
|
||||
const toggleAround = (
|
||||
state: EditorState,
|
||||
dispatch: Dispatch,
|
||||
open: string,
|
||||
close: string
|
||||
): boolean => {
|
||||
const { from, to } = state.selection.main
|
||||
|
||||
const isSurrounded = surroundedByText(state, open, close)
|
||||
|
||||
if (isSurrounded !== 'none') {
|
||||
const isInclusive = isSurrounded === 'inclusive'
|
||||
let transaction: Transaction
|
||||
|
||||
if (isInclusive) {
|
||||
// Remove delimiters on the inside edges of the selected text
|
||||
transaction = state.update({
|
||||
changes: [
|
||||
{ from, to: from + open.length, insert: '' },
|
||||
{ from: to - close.length, to, insert: '' },
|
||||
],
|
||||
})
|
||||
} else {
|
||||
// Remove delimiters on the outside edges of the selected text
|
||||
transaction = state.update({
|
||||
changes: [
|
||||
{ from: from - open.length, to: from, insert: '' },
|
||||
{ from: to, to: to + close.length, insert: '' },
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
dispatch(transaction)
|
||||
return true
|
||||
}
|
||||
|
||||
// Add delimiters around the selected text
|
||||
const transaction = state.update({
|
||||
changes: [
|
||||
{ from, insert: open },
|
||||
{ from: to, insert: close },
|
||||
],
|
||||
selection: { anchor: from + open.length, head: to + open.length },
|
||||
})
|
||||
|
||||
dispatch(transaction)
|
||||
return true
|
||||
}
|
||||
|
||||
const toggleLineStart = (state: EditorState, dispatch: Dispatch, text: string): boolean => {
|
||||
const lines = state.doc.lineAt(state.selection.main.from)
|
||||
const lineBreak = state.lineBreak
|
||||
|
||||
const range = {
|
||||
from: lines.from,
|
||||
to: state.selection.main.to,
|
||||
}
|
||||
|
||||
const selectedText = state.doc.sliceString(range.from, range.to)
|
||||
const shouldRemove = selectedText.startsWith(text)
|
||||
|
||||
let transaction: Transaction | undefined
|
||||
|
||||
if (shouldRemove) {
|
||||
const numOfSelectedLinesThatNeedToBeRemoved = selectedText.split(lineBreak + text).length
|
||||
const modifiedText = selectedText.substring(text.length).replaceAll(lineBreak + text, lineBreak)
|
||||
transaction = state.update({
|
||||
changes: { from: range.from, to: range.to, insert: modifiedText },
|
||||
selection: {
|
||||
anchor: state.selection.main.from - text.length,
|
||||
head: state.selection.main.to - text.length * numOfSelectedLinesThatNeedToBeRemoved,
|
||||
},
|
||||
})
|
||||
} else {
|
||||
const modifiedText = text + selectedText.replaceAll(lineBreak, lineBreak + text)
|
||||
const lengthDiff = modifiedText.length - selectedText.length
|
||||
transaction = state.update({
|
||||
changes: { from: range.from, to: range.to, insert: modifiedText },
|
||||
selection: {
|
||||
anchor: state.selection.main.from + text.length,
|
||||
head: state.selection.main.to + lengthDiff,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
if (!transaction) return false
|
||||
|
||||
dispatch(transaction)
|
||||
return true
|
||||
}
|
||||
|
||||
const continueNodeTypes = ['ListItem', 'Blockquote']
|
||||
const blackListedNodeTypes = ['CodeBlock']
|
||||
|
||||
const getListStructure = (state: EditorState, head: number) => {
|
||||
const tree = syntaxTree(state)
|
||||
const headNode = tree.resolve(head, -1)
|
||||
const stack = []
|
||||
|
||||
let node: typeof headNode.parent = headNode
|
||||
while (node) {
|
||||
if (continueNodeTypes.includes(node.name)) {
|
||||
stack.push(node)
|
||||
}
|
||||
if (blackListedNodeTypes.includes(node.name)) {
|
||||
return null
|
||||
}
|
||||
if (node.name === 'Document') {
|
||||
break
|
||||
}
|
||||
|
||||
node = node.parent
|
||||
}
|
||||
|
||||
return stack
|
||||
}
|
||||
|
||||
const insertNewlineContinueMark: Command = (view): boolean => {
|
||||
const { state, dispatch } = view
|
||||
const {
|
||||
selection: {
|
||||
main: { head },
|
||||
},
|
||||
} = state
|
||||
|
||||
// Get the current list structure to examine
|
||||
const stack = getListStructure(state, head)
|
||||
if (!stack || stack.length === 0) {
|
||||
// insert a newline as normal so that mobile works
|
||||
return insertNewlineAndIndent(view)
|
||||
}
|
||||
|
||||
const lastNode = stack[stack.length - 1]
|
||||
|
||||
// Get the necessary indentation
|
||||
const indentation = getIndentation(state, head)
|
||||
const indentStr = indentation ? indentString(state, indentation) : ''
|
||||
|
||||
// Initialize a transaction variable
|
||||
let transaction: Transaction | undefined
|
||||
|
||||
const lineContent = state.doc.lineAt(head).text
|
||||
|
||||
// Identify the patterns that should cancel the list continuation
|
||||
// TODO: Implement Node based cancellation
|
||||
const cancelPatterns = ['```', '# ', '> ']
|
||||
|
||||
const listMark = lastNode.getChild('ListMark')
|
||||
if (listMark) {
|
||||
cancelPatterns.push(state.doc.sliceString(listMark.from, listMark.to) + ' ')
|
||||
}
|
||||
|
||||
// Skip if current line matches any of the cancel patterns
|
||||
if (cancelPatterns.includes(lineContent)) {
|
||||
transaction = createSimpleTransaction(state)
|
||||
dispatch(transaction)
|
||||
return true
|
||||
}
|
||||
|
||||
switch (lastNode.name) {
|
||||
case 'ListItem':
|
||||
if (!listMark) return false
|
||||
transaction = createListTransaction(state, indentStr, listMark.from, listMark.to)
|
||||
break
|
||||
case 'Blockquote':
|
||||
transaction = createBlockquoteTransaction(state, indentStr)
|
||||
break
|
||||
}
|
||||
|
||||
if (transaction) {
|
||||
dispatch(transaction)
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// Creates a transaction for a simple line break
|
||||
const createSimpleTransaction = (state: EditorState) => {
|
||||
const {
|
||||
lineBreak,
|
||||
selection: {
|
||||
main: { head },
|
||||
},
|
||||
} = state
|
||||
const line = state.doc.lineAt(head)
|
||||
return state.update({
|
||||
changes: {
|
||||
from: line.from,
|
||||
to: line.to,
|
||||
insert: lineBreak,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// Creates a transaction for continuing a list item
|
||||
const createListTransaction = (state: EditorState, indentStr: string, from: number, to: number) => {
|
||||
const {
|
||||
lineBreak,
|
||||
selection: {
|
||||
main: { head },
|
||||
},
|
||||
} = state
|
||||
const listMarkContent = state.doc.sliceString(from, to)
|
||||
const insert = `${lineBreak}${indentStr}${incrementMark(listMarkContent)} `
|
||||
return state.update({
|
||||
changes: { from: head, insert },
|
||||
selection: { anchor: head + insert.length, head: head + insert.length },
|
||||
})
|
||||
}
|
||||
|
||||
// Creates a transaction for continuing a blockquote
|
||||
const createBlockquoteTransaction = (state: EditorState, indentStr: string) => {
|
||||
const {
|
||||
lineBreak,
|
||||
selection: {
|
||||
main: { head },
|
||||
},
|
||||
} = state
|
||||
const insert = `${lineBreak}${indentStr}> `
|
||||
return state.update({
|
||||
changes: { from: head, insert },
|
||||
selection: { anchor: head + insert.length, head: head + insert.length },
|
||||
})
|
||||
}
|
||||
|
||||
const incrementMark = (mark: string): string => {
|
||||
const numberedListRegex = /^(\d+)\.$/
|
||||
const match = numberedListRegex.exec(mark)
|
||||
if (match) {
|
||||
const number = parseInt(match[1])
|
||||
return (number + 1).toString() + '.'
|
||||
}
|
||||
return mark
|
||||
}
|
||||
|
||||
const commands = {
|
||||
toggleBold,
|
||||
toggleItalic,
|
||||
toggleStrikethrough,
|
||||
toggleCodeBlock,
|
||||
toggleSpoiler,
|
||||
toggleHeader,
|
||||
toggleHeader2,
|
||||
toggleHeader3,
|
||||
toggleHeader4,
|
||||
toggleHeader5,
|
||||
toggleHeader6,
|
||||
toggleQuote,
|
||||
toggleBulletList,
|
||||
toggleOrderedList,
|
||||
insertNewlineContinueMark,
|
||||
|
||||
// Utility
|
||||
yankSelection,
|
||||
replaceSelection,
|
||||
}
|
||||
|
||||
export const markdownCommands = commands
|
||||
export const modrinthMarkdownEditorKeymap: KeyBinding[] = [
|
||||
{ key: 'Enter', run: insertNewlineContinueMark },
|
||||
{ key: 'Backspace', run: deleteMarkupBackward },
|
||||
{ key: 'Mod-b', run: toggleBold },
|
||||
{ key: 'Mod-i', run: toggleItalic },
|
||||
{ key: 'Mod-e', run: toggleCodeBlock },
|
||||
{ key: 'Mod-s', run: toggleStrikethrough },
|
||||
{ key: 'Mod-Shift-.', run: toggleQuote },
|
||||
]
|
||||
65
libs/omorphia/lib/helpers/highlight.js
Normal file
65
libs/omorphia/lib/helpers/highlight.js
Normal file
@@ -0,0 +1,65 @@
|
||||
import hljs from 'highlight.js/lib/core'
|
||||
// Scripting
|
||||
import javascript from 'highlight.js/lib/languages/javascript'
|
||||
import python from 'highlight.js/lib/languages/python'
|
||||
import lua from 'highlight.js/lib/languages/lua'
|
||||
// Coding
|
||||
import java from 'highlight.js/lib/languages/java'
|
||||
import kotlin from 'highlight.js/lib/languages/kotlin'
|
||||
import scala from 'highlight.js/lib/languages/scala'
|
||||
import groovy from 'highlight.js/lib/languages/groovy'
|
||||
// Configs
|
||||
import gradle from 'highlight.js/lib/languages/gradle'
|
||||
import json from 'highlight.js/lib/languages/json'
|
||||
import ini from 'highlight.js/lib/languages/ini'
|
||||
import yaml from 'highlight.js/lib/languages/yaml'
|
||||
import xml from 'highlight.js/lib/languages/xml'
|
||||
import properties from 'highlight.js/lib/languages/properties'
|
||||
import { md, configuredXss } from '@/helpers/parse'
|
||||
|
||||
/* REGISTRATION */
|
||||
// Scripting
|
||||
hljs.registerLanguage('javascript', javascript)
|
||||
hljs.registerLanguage('python', python)
|
||||
hljs.registerLanguage('lua', lua)
|
||||
// Coding
|
||||
hljs.registerLanguage('java', java)
|
||||
hljs.registerLanguage('kotlin', kotlin)
|
||||
hljs.registerLanguage('scala', scala)
|
||||
hljs.registerLanguage('groovy', groovy)
|
||||
// Configs
|
||||
hljs.registerLanguage('gradle', gradle)
|
||||
hljs.registerLanguage('json', json)
|
||||
hljs.registerLanguage('ini', ini)
|
||||
hljs.registerLanguage('yaml', yaml)
|
||||
hljs.registerLanguage('xml', xml)
|
||||
hljs.registerLanguage('properties', properties)
|
||||
|
||||
/* ALIASES */
|
||||
// Scripting
|
||||
hljs.registerAliases(['js'], { languageName: 'javascript' })
|
||||
hljs.registerAliases(['py'], { languageName: 'python' })
|
||||
// Coding
|
||||
hljs.registerAliases(['kt'], { languageName: 'kotlin' })
|
||||
// Configs
|
||||
hljs.registerAliases(['json5'], { languageName: 'json' })
|
||||
hljs.registerAliases(['toml'], { languageName: 'ini' })
|
||||
hljs.registerAliases(['yml'], { languageName: 'yaml' })
|
||||
hljs.registerAliases(['html', 'htm', 'xhtml', 'mcui', 'fxml'], { languageName: 'xml' })
|
||||
|
||||
export const renderHighlightedString = (string) =>
|
||||
configuredXss.process(
|
||||
md({
|
||||
highlight: function (str, lang) {
|
||||
if (lang && hljs.getLanguage(lang)) {
|
||||
try {
|
||||
return hljs.highlight(str, { language: lang }).value
|
||||
} catch (__) {
|
||||
/* empty */
|
||||
}
|
||||
}
|
||||
|
||||
return ''
|
||||
},
|
||||
}).render(string)
|
||||
)
|
||||
5
libs/omorphia/lib/helpers/index.js
Normal file
5
libs/omorphia/lib/helpers/index.js
Normal file
@@ -0,0 +1,5 @@
|
||||
export * from './highlight.js'
|
||||
export * from './parse.js'
|
||||
export * from './projects.js'
|
||||
export * from './users.js'
|
||||
export * from './utils.js'
|
||||
156
libs/omorphia/lib/helpers/parse.js
Normal file
156
libs/omorphia/lib/helpers/parse.js
Normal file
@@ -0,0 +1,156 @@
|
||||
import MarkdownIt from 'markdown-it'
|
||||
import xss from 'xss'
|
||||
|
||||
export const configuredXss = new xss.FilterXSS({
|
||||
whiteList: {
|
||||
...xss.whiteList,
|
||||
summary: [],
|
||||
h1: ['id'],
|
||||
h2: ['id'],
|
||||
h3: ['id'],
|
||||
h4: ['id'],
|
||||
h5: ['id'],
|
||||
h6: ['id'],
|
||||
kbd: ['id'],
|
||||
input: ['checked', 'disabled', 'type'],
|
||||
iframe: ['width', 'height', 'allowfullscreen', 'frameborder', 'start', 'end'],
|
||||
img: [...xss.whiteList.img, 'usemap', 'style'],
|
||||
map: ['name'],
|
||||
area: [...xss.whiteList.a, 'coords'],
|
||||
a: [...xss.whiteList.a, 'rel'],
|
||||
td: [...xss.whiteList.td, 'style'],
|
||||
th: [...xss.whiteList.th, 'style'],
|
||||
picture: [],
|
||||
source: ['media', 'sizes', 'src', 'srcset', 'type'],
|
||||
},
|
||||
css: {
|
||||
whiteList: {
|
||||
'image-rendering': /^pixelated$/,
|
||||
'text-align': /^center|left|right$/,
|
||||
float: /^left|right$/,
|
||||
},
|
||||
},
|
||||
onIgnoreTagAttr: (tag, name, value) => {
|
||||
// Allow iframes from acceptable sources
|
||||
if (tag === 'iframe' && name === 'src') {
|
||||
const allowedSources = [
|
||||
{
|
||||
regex:
|
||||
/^https?:\/\/(www\.)?youtube(-nocookie)?\.com\/embed\/[a-zA-Z0-9_-]{11}(\?&autoplay=[0-1]{1})?$/,
|
||||
remove: ['&autoplay=1'], // Prevents autoplay
|
||||
},
|
||||
{
|
||||
regex: /^https?:\/\/(www\.)?discord\.com\/widget\?id=\d{18,19}(&theme=\w+)?$/,
|
||||
remove: [/&theme=\w+/],
|
||||
},
|
||||
]
|
||||
|
||||
for (const source of allowedSources) {
|
||||
if (source.regex.test(value)) {
|
||||
for (const remove of source.remove) {
|
||||
value = value.replace(remove, '')
|
||||
}
|
||||
return name + '="' + xss.escapeAttrValue(value) + '"'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// For Highlight.JS
|
||||
if (name === 'class' && ['pre', 'code', 'span'].includes(tag)) {
|
||||
const allowedClasses = []
|
||||
for (const className of value.split(/\s/g)) {
|
||||
if (className.startsWith('hljs-') || className.startsWith('language-')) {
|
||||
allowedClasses.push(className)
|
||||
}
|
||||
}
|
||||
return name + '="' + xss.escapeAttrValue(allowedClasses.join(' ')) + '"'
|
||||
}
|
||||
},
|
||||
safeAttrValue(tag, name, value, cssFilter) {
|
||||
if (tag === 'img' && name === 'src' && !value.startsWith('data:')) {
|
||||
try {
|
||||
const url = new URL(value)
|
||||
|
||||
if (url.hostname.includes('wsrv.nl')) {
|
||||
url.searchParams.delete('errorredirect')
|
||||
}
|
||||
|
||||
const allowedHostnames = [
|
||||
'imgur.com',
|
||||
'i.imgur.com',
|
||||
'cdn-raw.modrinth.com',
|
||||
'cdn.modrinth.com',
|
||||
'staging-cdn-raw.modrinth.com',
|
||||
'staging-cdn.modrinth.com',
|
||||
'github.com',
|
||||
'raw.githubusercontent.com',
|
||||
'img.shields.io',
|
||||
'i.postimg.cc',
|
||||
'wsrv.nl',
|
||||
'cf.way2muchnoise.eu',
|
||||
'bstats.org',
|
||||
]
|
||||
|
||||
if (!allowedHostnames.includes(url.hostname)) {
|
||||
return xss.safeAttrValue(
|
||||
tag,
|
||||
name,
|
||||
`https://wsrv.nl/?url=${encodeURIComponent(
|
||||
url.toString().replaceAll('&', '&')
|
||||
)}&n=-1`,
|
||||
cssFilter
|
||||
)
|
||||
} else {
|
||||
return xss.safeAttrValue(tag, name, url.toString(), cssFilter)
|
||||
}
|
||||
} catch (err) {
|
||||
/* empty */
|
||||
}
|
||||
}
|
||||
|
||||
return xss.safeAttrValue(tag, name, value, cssFilter)
|
||||
},
|
||||
})
|
||||
|
||||
export const md = (options = {}) => {
|
||||
const md = new MarkdownIt('default', {
|
||||
html: true,
|
||||
linkify: true,
|
||||
breaks: false,
|
||||
...options,
|
||||
})
|
||||
|
||||
const defaultLinkOpenRenderer =
|
||||
md.renderer.rules.link_open ||
|
||||
function (tokens, idx, options, _env, self) {
|
||||
return self.renderToken(tokens, idx, options)
|
||||
}
|
||||
|
||||
md.renderer.rules.link_open = function (tokens, idx, options, env, self) {
|
||||
const token = tokens[idx]
|
||||
const index = token.attrIndex('href')
|
||||
|
||||
if (index !== -1) {
|
||||
const href = token.attrs[index][1]
|
||||
|
||||
try {
|
||||
const url = new URL(href)
|
||||
const allowedHostnames = ['modrinth.com']
|
||||
|
||||
if (allowedHostnames.includes(url.hostname)) {
|
||||
return defaultLinkOpenRenderer(tokens, idx, options, env, self)
|
||||
}
|
||||
} catch (err) {
|
||||
/* empty */
|
||||
}
|
||||
}
|
||||
|
||||
tokens[idx].attrSet('rel', 'noopener nofollow ugc')
|
||||
|
||||
return defaultLinkOpenRenderer(tokens, idx, options, env, self)
|
||||
}
|
||||
|
||||
return md
|
||||
}
|
||||
|
||||
export const renderString = (string) => configuredXss.process(md().render(string))
|
||||
109
libs/omorphia/lib/helpers/projects.js
Normal file
109
libs/omorphia/lib/helpers/projects.js
Normal file
@@ -0,0 +1,109 @@
|
||||
// noinspection JSUnusedGlobalSymbols
|
||||
|
||||
export const getProjectTypeForDisplay = (type, categories, tags) => {
|
||||
if (type === 'mod') {
|
||||
const isPlugin = categories.some((category) => {
|
||||
return tags.loaderData.allPluginLoaders.includes(category)
|
||||
})
|
||||
const isMod = categories.some((category) => {
|
||||
return tags.loaderData.modLoaders.includes(category)
|
||||
})
|
||||
const isDataPack = categories.some((category) => {
|
||||
return tags.loaderData.dataPackLoaders.includes(category)
|
||||
})
|
||||
|
||||
if (isMod && isPlugin && isDataPack) {
|
||||
return 'mod, plugin, and data pack'
|
||||
} else if (isMod && isPlugin) {
|
||||
return 'mod and plugin'
|
||||
} else if (isMod && isDataPack) {
|
||||
return 'mod and data pack'
|
||||
} else if (isPlugin && isDataPack) {
|
||||
return 'plugin and data pack'
|
||||
} else if (isDataPack) {
|
||||
return 'data pack'
|
||||
} else if (isPlugin) {
|
||||
return 'plugin'
|
||||
}
|
||||
}
|
||||
|
||||
return type
|
||||
}
|
||||
|
||||
export const getProjectTypeForUrl = (type, loaders, tags) => {
|
||||
if (type === 'mod') {
|
||||
const isMod = loaders.some((category) => {
|
||||
return tags.loaderData.modLoaders.includes(category)
|
||||
})
|
||||
|
||||
const isPlugin = loaders.some((category) => {
|
||||
return tags.loaderData.allPluginLoaders.includes(category)
|
||||
})
|
||||
|
||||
const isDataPack = loaders.some((category) => {
|
||||
return tags.loaderData.dataPackLoaders.includes(category)
|
||||
})
|
||||
|
||||
if (isDataPack) {
|
||||
return 'datapack'
|
||||
} else if (isPlugin) {
|
||||
return 'plugin'
|
||||
} else if (isMod) {
|
||||
return 'mod'
|
||||
} else {
|
||||
return 'mod'
|
||||
}
|
||||
} else {
|
||||
return type
|
||||
}
|
||||
}
|
||||
|
||||
export const getProjectLink = (project) => {
|
||||
return `/${getProjectTypeForUrl(project.project_type, project.loaders)}/${
|
||||
project.slug ? project.slug : project.id
|
||||
}`
|
||||
}
|
||||
|
||||
export const getVersionLink = (project, version) => {
|
||||
if (version) {
|
||||
return getProjectLink(project) + '/version/' + version.id
|
||||
} else {
|
||||
return getProjectLink(project)
|
||||
}
|
||||
}
|
||||
|
||||
export const isApproved = (project) => {
|
||||
return project && APPROVED_PROJECT_STATUSES.includes(project.status)
|
||||
}
|
||||
|
||||
export const isListed = (project) => {
|
||||
return project && LISTED_PROJECT_STATUSES.includes(project.status)
|
||||
}
|
||||
|
||||
export const isUnlisted = (project) => {
|
||||
return project && UNLISTED_PROJECT_STATUSES.includes(project.status)
|
||||
}
|
||||
|
||||
export const isPrivate = (project) => {
|
||||
return project && PRIVATE_PROJECT_STATUSES.includes(project.status)
|
||||
}
|
||||
|
||||
export const isRejected = (project) => {
|
||||
return project && REJECTED_PROJECT_STATUSES.includes(project.status)
|
||||
}
|
||||
|
||||
export const isUnderReview = (project) => {
|
||||
return project && UNDER_REVIEW_PROJECT_STATUSES.includes(project.status)
|
||||
}
|
||||
|
||||
export const isDraft = (project) => {
|
||||
return project && DRAFT_PROJECT_STATUSES.includes(project.status)
|
||||
}
|
||||
|
||||
export const APPROVED_PROJECT_STATUSES = ['approved', 'archived', 'unlisted', 'private']
|
||||
export const LISTED_PROJECT_STATUSES = ['approved', 'archived']
|
||||
export const UNLISTED_PROJECT_STATUSES = ['unlisted', 'withheld']
|
||||
export const PRIVATE_PROJECT_STATUSES = ['private', 'rejected', 'processing']
|
||||
export const REJECTED_PROJECT_STATUSES = ['rejected', 'withheld']
|
||||
export const UNDER_REVIEW_PROJECT_STATUSES = ['processing']
|
||||
export const DRAFT_PROJECT_STATUSES = ['draft']
|
||||
11
libs/omorphia/lib/helpers/users.js
Normal file
11
libs/omorphia/lib/helpers/users.js
Normal file
@@ -0,0 +1,11 @@
|
||||
// noinspection JSUnusedGlobalSymbols
|
||||
|
||||
export const getUserLink = (user) => {
|
||||
return `/user/${user.username}`
|
||||
}
|
||||
|
||||
export const isStaff = (user) => {
|
||||
return user && STAFF_ROLES.includes(user.role)
|
||||
}
|
||||
|
||||
export const STAFF_ROLES = ['moderator', 'admin']
|
||||
302
libs/omorphia/lib/helpers/utils.js
Normal file
302
libs/omorphia/lib/helpers/utils.js
Normal file
@@ -0,0 +1,302 @@
|
||||
// noinspection JSUnusedGlobalSymbols
|
||||
|
||||
import dayjs from 'dayjs'
|
||||
|
||||
export const external = (cosmetics) => (cosmetics.externalLinksNewTab ? '_blank' : '')
|
||||
|
||||
// Only use on the complete list of versions for a project,
|
||||
// partial lists will generate the wrong version slugs
|
||||
export const computeVersions = (versions, members) => {
|
||||
const visitedVersions = []
|
||||
const returnVersions = []
|
||||
const authorMembers = {}
|
||||
|
||||
for (const version of versions.sort(
|
||||
(a, b) => dayjs(a.date_published) - dayjs(b.date_published)
|
||||
)) {
|
||||
if (visitedVersions.includes(version.version_number)) {
|
||||
visitedVersions.push(version.version_number)
|
||||
version.displayUrlEnding = version.id
|
||||
} else {
|
||||
visitedVersions.push(version.version_number)
|
||||
version.displayUrlEnding = version.version_number
|
||||
}
|
||||
version.primaryFile = version.files.find((file) => file.primary) ?? version.files[0]
|
||||
|
||||
if (!version.primaryFile) {
|
||||
version.primaryFile = {
|
||||
hashes: {
|
||||
sha1: '',
|
||||
sha512: '',
|
||||
},
|
||||
url: '#',
|
||||
filename: 'unknown',
|
||||
primary: false,
|
||||
size: 0,
|
||||
file_type: null,
|
||||
}
|
||||
}
|
||||
|
||||
version.author = authorMembers[version.author_id]
|
||||
if (!version.author) {
|
||||
version.author = members.find((x) => x.user.id === version.author_id)
|
||||
authorMembers[version.author_id] = version.author
|
||||
}
|
||||
|
||||
returnVersions.push(version)
|
||||
}
|
||||
|
||||
return returnVersions
|
||||
.reverse()
|
||||
.map((version, index) => {
|
||||
const nextVersion = returnVersions[index + 1]
|
||||
if (nextVersion && version.changelog && nextVersion.changelog === version.changelog) {
|
||||
return { duplicate: true, ...version }
|
||||
} else {
|
||||
return { duplicate: false, ...version }
|
||||
}
|
||||
})
|
||||
.sort((a, b) => dayjs(b.date_published) - dayjs(a.date_published))
|
||||
}
|
||||
|
||||
export const sortedCategories = (tags) => {
|
||||
return tags.categories.slice().sort((a, b) => {
|
||||
const headerCompare = a.header.localeCompare(b.header)
|
||||
if (headerCompare !== 0) {
|
||||
return headerCompare
|
||||
}
|
||||
if (a.header === 'resolutions' && b.header === 'resolutions') {
|
||||
return a.name.replace(/\D/g, '') - b.name.replace(/\D/g, '')
|
||||
} else if (a.header === 'performance impact' && b.header === 'performance impact') {
|
||||
const x = ['potato', 'low', 'medium', 'high', 'screenshot']
|
||||
|
||||
return x.indexOf(a.name) - x.indexOf(b.name)
|
||||
}
|
||||
return 0
|
||||
})
|
||||
}
|
||||
|
||||
export const formatNumber = (number, abbreviate = true) => {
|
||||
const x = +number
|
||||
if (x >= 1000000 && abbreviate) {
|
||||
return (x / 1000000).toFixed(2).toString() + 'M'
|
||||
} else if (x >= 10000 && abbreviate) {
|
||||
return (x / 1000).toFixed(1).toString() + 'k'
|
||||
} else {
|
||||
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
|
||||
}
|
||||
}
|
||||
|
||||
export function formatMoney(number, abbreviate = false) {
|
||||
const x = +number
|
||||
if (x >= 1000000 && abbreviate) {
|
||||
return '$' + (x / 1000000).toFixed(2).toString() + 'M'
|
||||
} else if (x >= 10000 && abbreviate) {
|
||||
return '$' + (x / 1000).toFixed(2).toString() + 'k'
|
||||
} else {
|
||||
return (
|
||||
'$' +
|
||||
x
|
||||
.toFixed(2)
|
||||
.toString()
|
||||
.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export const formatBytes = (bytes, decimals = 2) => {
|
||||
if (bytes === 0) return '0 Bytes'
|
||||
|
||||
const k = 1024
|
||||
const dm = decimals < 0 ? 0 : decimals
|
||||
const sizes = ['Bytes', 'KiB', 'MiB', 'GiB']
|
||||
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k))
|
||||
|
||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]
|
||||
}
|
||||
|
||||
export const capitalizeString = (name) => {
|
||||
return name ? name.charAt(0).toUpperCase() + name.slice(1) : name
|
||||
}
|
||||
|
||||
export const formatWallet = (name) => {
|
||||
if (name === 'paypal') {
|
||||
return 'PayPal'
|
||||
}
|
||||
return capitalizeString(name)
|
||||
}
|
||||
|
||||
export const formatProjectType = (name) => {
|
||||
if (name === 'resourcepack') {
|
||||
return 'Resource Pack'
|
||||
} else if (name === 'datapack') {
|
||||
return 'Data Pack'
|
||||
}
|
||||
|
||||
return capitalizeString(name)
|
||||
}
|
||||
|
||||
export const formatCategory = (name) => {
|
||||
if (name === 'modloader') {
|
||||
return "Risugami's ModLoader"
|
||||
} else if (name === 'bungeecord') {
|
||||
return 'BungeeCord'
|
||||
} else if (name === 'liteloader') {
|
||||
return 'LiteLoader'
|
||||
} else if (name === 'neoforge') {
|
||||
return 'NeoForge'
|
||||
} else if (name === 'game-mechanics') {
|
||||
return 'Game Mechanics'
|
||||
} else if (name === 'worldgen') {
|
||||
return 'World Generation'
|
||||
} else if (name === 'core-shaders') {
|
||||
return 'Core Shaders'
|
||||
} else if (name === 'gui') {
|
||||
return 'GUI'
|
||||
} else if (name === '8x-') {
|
||||
return '8x or lower'
|
||||
} else if (name === '512x+') {
|
||||
return '512x or higher'
|
||||
} else if (name === 'kitchen-sink') {
|
||||
return 'Kitchen Sink'
|
||||
} else if (name === 'path-tracing') {
|
||||
return 'Path Tracing'
|
||||
} else if (name === 'pbr') {
|
||||
return 'PBR'
|
||||
} else if (name === 'datapack') {
|
||||
return 'Data Pack'
|
||||
} else if (name === 'colored-lighting') {
|
||||
return 'Colored Lighting'
|
||||
} else if (name === 'optifine') {
|
||||
return 'OptiFine'
|
||||
}
|
||||
|
||||
return capitalizeString(name)
|
||||
}
|
||||
|
||||
export const formatCategoryHeader = (name) => {
|
||||
return capitalizeString(name)
|
||||
}
|
||||
|
||||
export const formatProjectStatus = (name) => {
|
||||
if (name === 'approved') {
|
||||
return 'Public'
|
||||
} else if (name === 'processing') {
|
||||
return 'Under review'
|
||||
}
|
||||
|
||||
return capitalizeString(name)
|
||||
}
|
||||
|
||||
export const formatVersions = (versionArray, gameVersions) => {
|
||||
const allVersions = gameVersions.slice().reverse()
|
||||
const allReleases = allVersions.filter((x) => x.version_type === 'release')
|
||||
|
||||
const intervals = []
|
||||
let currentInterval = 0
|
||||
|
||||
for (let i = 0; i < versionArray.length; i++) {
|
||||
const index = allVersions.findIndex((x) => x.version === versionArray[i])
|
||||
const releaseIndex = allReleases.findIndex((x) => x.version === versionArray[i])
|
||||
|
||||
if (i === 0) {
|
||||
intervals.push([[versionArray[i], index, releaseIndex]])
|
||||
} else {
|
||||
const intervalBase = intervals[currentInterval]
|
||||
|
||||
if (
|
||||
(index - intervalBase[intervalBase.length - 1][1] === 1 ||
|
||||
releaseIndex - intervalBase[intervalBase.length - 1][2] === 1) &&
|
||||
(allVersions[intervalBase[0][1]].version_type === 'release' ||
|
||||
allVersions[index].version_type !== 'release')
|
||||
) {
|
||||
intervalBase[1] = [versionArray[i], index, releaseIndex]
|
||||
} else {
|
||||
currentInterval += 1
|
||||
intervals[currentInterval] = [[versionArray[i], index, releaseIndex]]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const newIntervals = []
|
||||
for (let i = 0; i < intervals.length; i++) {
|
||||
const interval = intervals[i]
|
||||
|
||||
if (interval.length === 2 && interval[0][2] !== -1 && interval[1][2] === -1) {
|
||||
let lastSnapshot = null
|
||||
for (let j = interval[1][1]; j > interval[0][1]; j--) {
|
||||
if (allVersions[j].version_type === 'release') {
|
||||
newIntervals.push([
|
||||
interval[0],
|
||||
[
|
||||
allVersions[j].version,
|
||||
j,
|
||||
allReleases.findIndex((x) => x.version === allVersions[j].version),
|
||||
],
|
||||
])
|
||||
|
||||
if (lastSnapshot !== null && lastSnapshot !== j + 1) {
|
||||
newIntervals.push([[allVersions[lastSnapshot].version, lastSnapshot, -1], interval[1]])
|
||||
} else {
|
||||
newIntervals.push([interval[1]])
|
||||
}
|
||||
|
||||
break
|
||||
} else {
|
||||
lastSnapshot = j
|
||||
}
|
||||
}
|
||||
} else {
|
||||
newIntervals.push(interval)
|
||||
}
|
||||
}
|
||||
|
||||
const output = []
|
||||
|
||||
for (const interval of newIntervals) {
|
||||
if (interval.length === 2) {
|
||||
output.push(`${interval[0][0]}–${interval[1][0]}`)
|
||||
} else {
|
||||
output.push(interval[0][0])
|
||||
}
|
||||
}
|
||||
|
||||
return (output.length === 0 ? versionArray : output).join(', ')
|
||||
}
|
||||
|
||||
export function cycleValue(value, values) {
|
||||
const index = values.indexOf(value) + 1
|
||||
return values[index % values.length]
|
||||
}
|
||||
|
||||
export const fileIsValid = (file, validationOptions) => {
|
||||
const { maxSize, alertOnInvalid } = validationOptions
|
||||
if (maxSize !== null && maxSize !== undefined && file.size > maxSize) {
|
||||
if (alertOnInvalid) {
|
||||
alert(`File ${file.name} is too big! Must be less than ${formatBytes(maxSize)}`)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
export const acceptFileFromProjectType = (projectType) => {
|
||||
switch (projectType) {
|
||||
case 'mod':
|
||||
return '.jar,.zip,.litemod,application/java-archive,application/x-java-archive,application/zip'
|
||||
case 'plugin':
|
||||
return '.jar,.zip,application/java-archive,application/x-java-archive,application/zip'
|
||||
case 'resourcepack':
|
||||
return '.zip,application/zip'
|
||||
case 'shader':
|
||||
return '.zip,application/zip'
|
||||
case 'datapack':
|
||||
return '.zip,application/zip'
|
||||
case 'modpack':
|
||||
return '.mrpack,application/x-modrinth-modpack+zip,application/zip'
|
||||
default:
|
||||
return '*'
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user