Skip to content

Commit

Permalink
feat(pintora-diagrams): add new @config directive, rename the old t…
Browse files Browse the repository at this point in the history
…o `@param`
  • Loading branch information
hikerpig committed Feb 5, 2022
1 parent 6286151 commit 0ca092e
Show file tree
Hide file tree
Showing 47 changed files with 839 additions and 371 deletions.
13 changes: 11 additions & 2 deletions packages/pintora-diagrams/scripts/build-grammar.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const shellExec = require('shell-exec')
const path = require('path')
const fs = require('fs')

const grammarFiles = [
{ input: 'src/er/parser/erDiagram.ne', output: 'src/er/parser/erDiagram.ts' },
Expand All @@ -9,8 +10,16 @@ const grammarFiles = [
{ input: 'src/mindmap/parser/mindmap.ne', output: 'src/mindmap/parser/mindmap.ts' },
]

grammarFiles.forEach(({ input, output }) => {
shellExec(`npx nearleyc ${path.join(__dirname, '..', input)} -o ${path.join(__dirname, '..', output)}`)
grammarFiles.forEach(async ({ input, output }) => {
const outputPath = path.join(__dirname, '..', output)
await shellExec(`npx nearleyc ${path.join(__dirname, '..', input)} -o ${outputPath}`)
.then(console.log)
.catch(console.error)

if (fs.existsSync(outputPath)) {
const content = fs.readFileSync(outputPath).toString()
// the 'declare var' that nearleyc generates may raise TS2300 error 'Duplicate identifier', so we need to ignore it
const newContent = content.replace(/declare\svar/g, '//@ts-ignore\ndeclare var')
fs.writeFileSync(outputPath, newContent)
}
})
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
//@ts-check
import { parse } from '../parser'
import { db } from '../db'
import { getConf } from '../config'
Expand All @@ -7,10 +8,10 @@ describe('activityDiagram config', () => {
db.clear()
})

it('can parse config', () => {
it('can parse param clause', () => {
const example = `
activityDiagram
@config {
@param {
noteTextColor #ff0000
noteMargin 15
}
Expand All @@ -24,10 +25,31 @@ activityDiagram
`
parse(example)
const ir = db.getDiagramIR()
const conf = getConf(ir.configParams)
const conf = getConf(ir)
expect(conf).toMatchObject({
noteTextColor: '#ff0000',
noteMargin: 15,
})
})

it('can parse override clause', () => {
const example = `
activityDiagram
@config({
"activity": {
"edgesep": 4,
"edgeColor": "rgba(0, 0, 0, 1)",
"curvedEdge": true
}
})
`
parse(example)
const ir = db.getDiagramIR()
const conf = getConf(ir)
expect(conf).toMatchObject({
edgesep: 4,
edgeColor: 'rgba(0, 0, 0, 1)',
curvedEdge: true,
})
})
})
4 changes: 2 additions & 2 deletions packages/pintora-diagrams/src/activity/artist.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,8 @@ function isEndAlikeKeyword(keyword: Keyword) {
}

const erArtist: IDiagramArtist<ActivityDiagramIR, ActivityConf> = {
draw(ir) {
conf = getConf(ir.configParams)
draw(ir, config) {
conf = getConf(ir, config)
model = new ArtistModel(ir)
theme = (configApi.getConfig() as PintoraConfig).themeConfig.themeVariables
// console.log('ir', JSON.stringify(ir, null, 2))
Expand Down
32 changes: 17 additions & 15 deletions packages/pintora-diagrams/src/activity/config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { PALETTE } from '../util/theme'
import { configApi, safeAssign, PintoraConfig } from '@pintora/core'
import { interpreteConfigs, ConfigParam } from '../util/style'
import { interpreteConfigs, makeConfigurator } from '../util/style'
import { DEFAULT_FONT_FAMILY } from '../util/text'

export type ActivityConf = {
Expand Down Expand Up @@ -62,7 +61,7 @@ export const defaultConfig: ActivityConf = {
fontFamily: DEFAULT_FONT_FAMILY,
}

export const ACTIVITY_CONFIG_DIRECTIVE_RULES = {
export const ACTIVITY_PARAM_DIRECTIVE_RULES = {
diagramPadding: { valueType: 'size' },

curvedEdge: { valueType: 'boolean' },
Expand Down Expand Up @@ -90,12 +89,16 @@ export const ACTIVITY_CONFIG_DIRECTIVE_RULES = {
fontFamily: { valueType: 'string' },
} as const

export function getConf(configParams: ConfigParam[]) {
const globalConfig: PintoraConfig = configApi.getConfig()
const t = globalConfig.themeConfig?.themeVariables
const conf = { ...defaultConfig }
if (t) {
safeAssign(conf, {
export const configKey = 'activity'

const configurator = makeConfigurator<ActivityConf>({
defaultConfig,
configKey,
getConfigFromParamDirectives(configParams) {
return interpreteConfigs(ACTIVITY_PARAM_DIRECTIVE_RULES, configParams)
},
getConfigFromTheme(t) {
return {
actionBackground: t.primaryColor,
actionBorderColor: t.primaryBorderColor,
groupBackground: t.groupBackground,
Expand All @@ -105,9 +108,8 @@ export function getConf(configParams: ConfigParam[]) {
keywordBackground: t.textColor,
labelBackground: t.canvasBackground || t.background1,
labelTextColor: t.textColor,
})
}
safeAssign(conf, { fontFamily: globalConfig.core.defaultFontFamily }, globalConfig.activity)
safeAssign(conf, interpreteConfigs(ACTIVITY_CONFIG_DIRECTIVE_RULES, configParams))
return conf
}
}
},
})

export const getConf = configurator.getConfig
28 changes: 16 additions & 12 deletions packages/pintora-diagrams/src/activity/db.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { makeIdCounter } from '@pintora/core'
import { ConfigParam, ConfigAction } from '../util/style'
import { BaseDb } from '../util/base-db'
import { BaseDiagramIR } from '../util/ir'
import { OverrideAction, ParamAction } from '../util/style'
import { dedent } from '../util/text'

export type Action = {
Expand Down Expand Up @@ -88,15 +90,15 @@ export type Step<T extends StepValue = StepValue> = {
value: T
}

export type ActivityDiagramIR = {
export type ActivityDiagramIR = BaseDiagramIR & {
steps: Step[]
notes: Note[]
arrowLabels: ArrowLabel[]
configParams: ConfigParam[]
}

export type ApplyPart =
| ConfigAction
| ParamAction
| OverrideAction
| {
type: 'addAction'
action: Action
Expand Down Expand Up @@ -166,8 +168,7 @@ type DbApplyState = {
parentId?: string | undefined
}

class ActivityDb {
protected configParams: ConfigParam[] = []
class ActivityDb extends BaseDb {
protected steps: Step[] = []
protected notes: Note[] = []
protected arrowLabels: ArrowLabel[] = []
Expand Down Expand Up @@ -308,11 +309,14 @@ class ActivityDb {
this.arrowLabels.push(value)
break
}
case 'addConfig':
{
this.configParams.push(part)
}
case 'addParam': {
this.configParams.push(part)
break
}
case 'overrideConfig': {
this.addOverrideConfig(part)
break
}
default: {
}
}
Expand All @@ -330,15 +334,15 @@ class ActivityDb {
steps: this.steps,
notes: this.notes,
arrowLabels: this.arrowLabels,
configParams: this.configParams,
...this.getBaseDiagramIR(),
}
}

clear() {
super.clear()
this.idCounter.reset()
this.steps = []
this.notes = []
this.configParams = []
}
}

Expand Down
64 changes: 44 additions & 20 deletions packages/pintora-diagrams/src/activity/parser/activityDiagram.ne
Original file line number Diff line number Diff line change
@@ -1,22 +1,51 @@
@preprocessor typescript
@lexer lexer
@builtin "whitespace.ne"
@include "../../util/parser-grammars/config.ne"
@include "../../util/parser-grammars/comment.ne"

@{%
import * as moo from '@hikerpig/moo'
import { tv, textToCaseInsensitiveRegex, VALID_TEXT_REGEXP, COMMENT_LINE_REGEXP } from '../../util/parser-shared'
// import { tv, textToCaseInsensitiveRegex, VALID_TEXT_REGEXP, COMMENT_LINE_REGEXP } from '../../util/parser-shared'
import {
tv,
textToCaseInsensitiveRegex,
VALID_TEXT_REGEXP,
COMMENT_LINE_REGEXP,
CONFIG_DIRECTIVE,
QUOTED_WORD_REGEXP,
configLexerMainState,
configLexerConfigClauseState,
L_PAREN_REGEXP,
R_PAREN_REGEXP,
} from '../../util/parser-shared'
import type { ApplyPart } from '../db'

let lexer = moo.compile({
NEWLINE: { match: /\n/, lineBreaks: true },
SPACE: { match: / /, lineBreaks: false },
QUOTED_WORD: /\"[^"]*\"/,
SEMICOLON: /;/,
COLON: /:/,
L_PAREN: { match: /\(/ },
R_PAREN: { match: /\)/ },
L_BRACKET: { match: /\{/ },
R_BRACKET: { match: /\}/ },
START_NOTE: textToCaseInsensitiveRegex('@note'),
END_NOTE: textToCaseInsensitiveRegex('@end_note'),
COMMENT_LINE: COMMENT_LINE_REGEXP,
const COMMON_TOKEN_RULES = {
VALID_TEXT: { match: VALID_TEXT_REGEXP, fallback: true },
}

let lexer = moo.states({
main: {
NEWLINE: { match: /\n/, lineBreaks: true },
SPACE: { match: / /, lineBreaks: false },
QUOTED_WORD: QUOTED_WORD_REGEXP,
SEMICOLON: /;/,
COLON: /:/,
L_PAREN: L_PAREN_REGEXP,
R_PAREN: R_PAREN_REGEXP,
L_BRACKET: { match: /\{/ },
R_BRACKET: { match: /\}/ },
START_NOTE: textToCaseInsensitiveRegex('@note'),
END_NOTE: textToCaseInsensitiveRegex('@end_note'),
COMMENT_LINE: COMMENT_LINE_REGEXP,
...configLexerMainState,
VALID_TEXT: { match: VALID_TEXT_REGEXP, fallback: true },
},
configClause: {
...configLexerConfigClauseState,
...COMMON_TOKEN_RULES,
},
})

let yy
Expand All @@ -30,12 +59,6 @@ function extractChildren(o) {
}
%}

@preprocessor typescript
@lexer lexer
@builtin "whitespace.ne"
@include "../../util/parser-grammars/config.ne"
@include "../../util/parser-grammars/comment.ne"

start -> __ start {% (d) => d[1] %}
| "activityDiagram" document __:? {%
function(d) {
Expand Down Expand Up @@ -77,6 +100,7 @@ statement ->
| forkSentence
| noteStatement
| arrowLabelStatement
| paramClause _ %NEWLINE
| configClause _ %NEWLINE
| comment _ %NEWLINE

Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
//@ts-check
import { parse } from '../parser'
import db from '../db'
import { getConf } from '../config'
Expand All @@ -7,11 +8,11 @@ describe('componentDiagram config', () => {
db.clear()
})

it('can parse config', () => {
it('can parse param clause', () => {
const example = `
componentDiagram
@config groupBackground #000000
@config {
@param groupBackground #000000
@param {
componentPadding 20
fontFamily serif
}
Expand All @@ -21,11 +22,30 @@ describe('componentDiagram config', () => {
`
parse(example)
const ir = db.getDiagramIR()
const conf = getConf(ir.configParams)
const conf = getConf(ir)
expect(conf).toMatchObject({
groupBackground: '#000000',
componentPadding: 20,
fontFamily: 'serif',
})
})

it('can parse override clause', () => {
const example = `
componentDiagram
@config({
"component": {
"componentPadding": 4,
"textColor": "rgba(0, 0, 0, 1)"
}
})
`
parse(example)
const ir = db.getDiagramIR()
const conf = getConf(ir)
expect(conf).toMatchObject({
componentPadding: 4,
textColor: 'rgba(0, 0, 0, 1)',
})
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -245,10 +245,10 @@ componentDiagram
})
})

it('can parse config clause', () => {
it('can parse param clause', () => {
const example = stripStartEmptyLines(`
componentDiagram
@config lineWidth 3
@param lineWidth 3
`)
parse(example)
const ir = db.getDiagramIR()
Expand Down
4 changes: 2 additions & 2 deletions packages/pintora-diagrams/src/component/artist.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,9 @@ type EdgeData = {
}

const componentArtist: IDiagramArtist<ComponentDiagramIR, ComponentConf> = {
draw(ir) {
draw(ir, config) {
// console.info('[artist] component', ir)
conf = getConf(ir.configParams)
conf = getConf(ir, config)

const rootMark: Group = {
type: 'group',
Expand Down
Loading

0 comments on commit 0ca092e

Please sign in to comment.