Skip to content

Commit d8987f0

Browse files
authored
feat(code): add syntax highlighting for TypeScript (#37)
1 parent c1062fa commit d8987f0

File tree

7 files changed

+623
-29
lines changed

7 files changed

+623
-29
lines changed

app/src/main/java/com/discord/simpleast/sample/SampleTexts.kt

Lines changed: 52 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -233,22 +233,69 @@ object SampleTexts {
233233
JavaScript code block:
234234
```js
235235
const { performance } = require('perf_hooks');
236+
236237
function getMem() {
237238
return Object.entries(process.memoryUsage())
238-
.map(([K, V]) => `${'$'}{K}: ${'$'}{(V / (1024 ** 2)).toFixed(1)}MB`)
239+
.map(([K, V]) =>
240+
`${'$'}{K}: ${'$'}{(V / (1024 ** 2)).toFixed(1)}MB`)
239241
.join('\n');
240242
}
243+
241244
const memories = [];
242245
let timer = performance.now();
243-
for (let i = 0; i < 50; i++) {
246+
247+
for (let i = 0; i < 50; i++)
244248
if (memories.length === 5) break;
245-
else if (i % 5 === 0) memories.push(getMem());
246-
}
249+
else if (i % 5 === 0)
250+
memories.push(getMem());
251+
247252
timer = performance.now() - timer;
248253
249254
console.log(`Took ${'$'}{timer} ms`);
250255
```
251256
"""
257+
258+
private const val CODE_BLOCK_TYPESCRIPT = """
259+
TypeScript code block:
260+
```ts
261+
import { inspect } from 'util';
262+
import type { InspectOptions } from 'util';
263+
264+
interface LogOptions extends InspectOptions {
265+
showDate?: boolean;
266+
}
267+
268+
class Logger {
269+
private options: LogOptions;
270+
271+
public constructor(loggerOptions: LogOptions = {}) {
272+
this.options = loggerOptions;
273+
}
274+
275+
private log(value: any, options: LogOptions): void {
276+
const showDate: boolean =
277+
options.showDate ?? false;
278+
279+
delete options.showDate;
280+
281+
console.log((showDate ?
282+
`[${'$'}{new Date().toLocaleTimeString()}] `
283+
: '') + inspect(value, options));
284+
}
285+
286+
public info(value: any, options: LogOptions = this.options): void {
287+
this.log(value, options);
288+
}
289+
}
290+
291+
const logger: Logger = new Logger({
292+
showDate: true,
293+
showHidden: true
294+
});
295+
296+
logger.info(1);
297+
```
298+
"""
252299

253300
const val CODE_BLOCKS = """
254301
# Code block samples
@@ -266,6 +313,7 @@ object SampleTexts {
266313
$CODE_BLOCK_XML
267314
$CODE_BLOCK_CRYSTAL
268315
$CODE_BLOCK_JAVASCRIPT
316+
$CODE_BLOCK_TYPESCRIPT
269317
270318
That should do it....
271319
"""

simpleast-core/src/main/java/com/discord/simpleast/code/CodeRules.kt

Lines changed: 34 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -116,9 +116,11 @@ object CodeRules {
116116
"string|bool|double|float|bytes",
117117
"int32|uint32|sint32|int64|unit64|sint64",
118118
"map"),
119-
"required|repeated|optional|option|oneof|default|reserved",
120-
"package|import",
121-
"rpc|returns")
119+
keywords = arrayOf(
120+
"required|repeated|optional|option|oneof|default|reserved",
121+
"package|import",
122+
"rpc|returns")
123+
)
122124

123125
val pythonRules = createGenericCodeRules<R, S>(
124126
codeStyleProviders,
@@ -133,12 +135,12 @@ object CodeRules {
133135
.toMatchGroupRule(stylesProvider = codeStyleProviders.genericsStyleProvider)),
134136
definitions = arrayOf("class", "def", "lambda"),
135137
builtIns = arrayOf("True|False|None"),
136-
"from|import|global|nonlocal",
137-
"async|await|class|self|cls|def|lambda",
138-
"for|while|if|else|elif|break|continue|return",
139-
"try|except|finally|raise|pass|yeild",
140-
"in|as|is|del",
141-
"and|or|not|assert",
138+
keywords = arrayOf("from|import|global|nonlocal",
139+
"async|await|class|self|cls|def|lambda",
140+
"for|while|if|else|elif|break|continue|return",
141+
"try|except|finally|raise|pass|yeild",
142+
"in|as|is|del",
143+
"and|or|not|assert")
142144
)
143145

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

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

208+
val typescriptRules = createGenericCodeRules<R, S>(
209+
codeStyleProviders,
210+
additionalRules = TypeScript.createCodeRules(codeStyleProviders),
211+
definitions = arrayOf("class", "interface", "enum",
212+
"namespace", "module", "type"),
213+
builtIns = TypeScript.BUILT_INS,
214+
keywords = TypeScript.KEYWORDS,
215+
types = TypeScript.TYPES
216+
)
217+
206218
return mapOf(
207219
"kt" to kotlinRules,
208220
"kotlin" to kotlinRules,
@@ -228,6 +240,9 @@ object CodeRules {
228240

229241
"js" to javascriptRules,
230242
"javascript" to javascriptRules,
243+
244+
"ts" to typescriptRules,
245+
"typescript" to typescriptRules
231246
)
232247
}
233248

@@ -237,13 +252,17 @@ object CodeRules {
237252
private fun <R, S> createGenericCodeRules(
238253
codeStyleProviders: CodeStyleProviders<R>,
239254
additionalRules: List<Rule<R, Node<R>, S>>,
240-
definitions: Array<String>, builtIns: Array<String>, vararg keywords: String
255+
definitions: Array<String>,
256+
builtIns: Array<String>,
257+
keywords: Array<String>,
258+
types: Array<String> = arrayOf(" ")
241259
): List<Rule<R, Node<R>, S>> =
242260
additionalRules +
243261
listOf(
244262
createDefinitionRule(codeStyleProviders, *definitions),
245263
createWordPattern(*builtIns).toMatchGroupRule(stylesProvider = codeStyleProviders.genericsStyleProvider),
246264
createWordPattern(*keywords).toMatchGroupRule(stylesProvider = codeStyleProviders.keywordStyleProvider),
265+
createWordPattern(*types).toMatchGroupRule(stylesProvider = codeStyleProviders.typesStyleProvider),
247266
PATTERN_NUMBERS.toMatchGroupRule(stylesProvider = codeStyleProviders.literalStyleProvider),
248267
PATTERN_LEADING_WS_CONSUMER.toMatchGroupRule(),
249268
PATTERN_TEXT.toMatchGroupRule(),

0 commit comments

Comments
 (0)