Skip to content

Commit

Permalink
feat(code): add syntax highlighting for TypeScript (#37)
Browse files Browse the repository at this point in the history
  • Loading branch information
VoltrexKeyva authored Nov 4, 2021

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
1 parent c1062fa commit d8987f0
Show file tree
Hide file tree
Showing 7 changed files with 623 additions and 29 deletions.
56 changes: 52 additions & 4 deletions app/src/main/java/com/discord/simpleast/sample/SampleTexts.kt
Original file line number Diff line number Diff line change
Expand Up @@ -233,22 +233,69 @@ object SampleTexts {
JavaScript code block:
```js
const { performance } = require('perf_hooks');
function getMem() {
return Object.entries(process.memoryUsage())
.map(([K, V]) => `${'$'}{K}: ${'$'}{(V / (1024 ** 2)).toFixed(1)}MB`)
.map(([K, V]) =>
`${'$'}{K}: ${'$'}{(V / (1024 ** 2)).toFixed(1)}MB`)
.join('\n');
}
const memories = [];
let timer = performance.now();
for (let i = 0; i < 50; i++) {
for (let i = 0; i < 50; i++)
if (memories.length === 5) break;
else if (i % 5 === 0) memories.push(getMem());
}
else if (i % 5 === 0)
memories.push(getMem());
timer = performance.now() - timer;
console.log(`Took ${'$'}{timer} ms`);
```
"""

private const val CODE_BLOCK_TYPESCRIPT = """
TypeScript code block:
```ts
import { inspect } from 'util';
import type { InspectOptions } from 'util';
interface LogOptions extends InspectOptions {
showDate?: boolean;
}
class Logger {
private options: LogOptions;
public constructor(loggerOptions: LogOptions = {}) {
this.options = loggerOptions;
}
private log(value: any, options: LogOptions): void {
const showDate: boolean =
options.showDate ?? false;
delete options.showDate;
console.log((showDate ?
`[${'$'}{new Date().toLocaleTimeString()}] `
: '') + inspect(value, options));
}
public info(value: any, options: LogOptions = this.options): void {
this.log(value, options);
}
}
const logger: Logger = new Logger({
showDate: true,
showHidden: true
});
logger.info(1);
```
"""

const val CODE_BLOCKS = """
# Code block samples
Expand All @@ -266,6 +313,7 @@ object SampleTexts {
$CODE_BLOCK_XML
$CODE_BLOCK_CRYSTAL
$CODE_BLOCK_JAVASCRIPT
$CODE_BLOCK_TYPESCRIPT
That should do it....
"""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,9 +116,11 @@ object CodeRules {
"string|bool|double|float|bytes",
"int32|uint32|sint32|int64|unit64|sint64",
"map"),
"required|repeated|optional|option|oneof|default|reserved",
"package|import",
"rpc|returns")
keywords = arrayOf(
"required|repeated|optional|option|oneof|default|reserved",
"package|import",
"rpc|returns")
)

val pythonRules = createGenericCodeRules<R, S>(
codeStyleProviders,
Expand All @@ -133,12 +135,12 @@ object CodeRules {
.toMatchGroupRule(stylesProvider = codeStyleProviders.genericsStyleProvider)),
definitions = arrayOf("class", "def", "lambda"),
builtIns = arrayOf("True|False|None"),
"from|import|global|nonlocal",
"async|await|class|self|cls|def|lambda",
"for|while|if|else|elif|break|continue|return",
"try|except|finally|raise|pass|yeild",
"in|as|is|del",
"and|or|not|assert",
keywords = arrayOf("from|import|global|nonlocal",
"async|await|class|self|cls|def|lambda",
"for|while|if|else|elif|break|continue|return",
"try|except|finally|raise|pass|yeild",
"in|as|is|del",
"and|or|not|assert")
)

val rustRules = createGenericCodeRules<R, S>(
Expand All @@ -157,11 +159,11 @@ object CodeRules {
"Arc|Rc|Box|Pin|Future",
"true|false|bool|usize|i64|u64|u32|i32|str|String"
),
"let|mut|static|const|unsafe",
"crate|mod|extern|pub|pub(super)|use",
"struct|enum|trait|type|where|impl|dyn|async|await|move|self|fn",
"for|while|loop|if|else|match|break|continue|return|try",
"in|as|ref",
keywords = arrayOf("let|mut|static|const|unsafe",
"crate|mod|extern|pub|pub(super)|use",
"struct|enum|trait|type|where|impl|dyn|async|await|move|self|fn",
"for|while|loop|if|else|match|break|continue|return|try",
"in|as|ref")
)

val xmlRules = listOf<Rule<R, Node<R>, S>>(
Expand Down Expand Up @@ -203,6 +205,16 @@ object CodeRules {
builtIns = JavaScript.BUILT_INS,
keywords = JavaScript.KEYWORDS)

val typescriptRules = createGenericCodeRules<R, S>(
codeStyleProviders,
additionalRules = TypeScript.createCodeRules(codeStyleProviders),
definitions = arrayOf("class", "interface", "enum",
"namespace", "module", "type"),
builtIns = TypeScript.BUILT_INS,
keywords = TypeScript.KEYWORDS,
types = TypeScript.TYPES
)

return mapOf(
"kt" to kotlinRules,
"kotlin" to kotlinRules,
Expand All @@ -228,6 +240,9 @@ object CodeRules {

"js" to javascriptRules,
"javascript" to javascriptRules,

"ts" to typescriptRules,
"typescript" to typescriptRules
)
}

Expand All @@ -237,13 +252,17 @@ object CodeRules {
private fun <R, S> createGenericCodeRules(
codeStyleProviders: CodeStyleProviders<R>,
additionalRules: List<Rule<R, Node<R>, S>>,
definitions: Array<String>, builtIns: Array<String>, vararg keywords: String
definitions: Array<String>,
builtIns: Array<String>,
keywords: Array<String>,
types: Array<String> = arrayOf(" ")
): List<Rule<R, Node<R>, S>> =
additionalRules +
listOf(
createDefinitionRule(codeStyleProviders, *definitions),
createWordPattern(*builtIns).toMatchGroupRule(stylesProvider = codeStyleProviders.genericsStyleProvider),
createWordPattern(*keywords).toMatchGroupRule(stylesProvider = codeStyleProviders.keywordStyleProvider),
createWordPattern(*types).toMatchGroupRule(stylesProvider = codeStyleProviders.typesStyleProvider),
PATTERN_NUMBERS.toMatchGroupRule(stylesProvider = codeStyleProviders.literalStyleProvider),
PATTERN_LEADING_WS_CONSUMER.toMatchGroupRule(),
PATTERN_TEXT.toMatchGroupRule(),
Expand Down
Loading

0 comments on commit d8987f0

Please sign in to comment.