Skip to content

Commit

Permalink
feat: add reset function for observer
Browse files Browse the repository at this point in the history
  • Loading branch information
Nnigmat committed Sep 2, 2021
1 parent 3805120 commit 1284f83
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 4 deletions.
15 changes: 14 additions & 1 deletion packages/core/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,14 @@
"@babel/code-frame": "7.14.5",
"change-case": "4.1.2",
"css-color-function": "1.3.3",
"deepcopy": "^2.1.0",
"deepmerge": "4.2.2",
"yaml": "1.10.2"
},
"devDependencies": {
"@types/babel__code-frame": "7.0.3"
},
"files": ["lib"]
"files": [
"lib"
]
}
19 changes: 19 additions & 0 deletions packages/core/src/internal/__tests__/observer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,25 @@ describe('ThemekitObserver', () => {
],
})
})

test('should reset tokens on reset', async () => {
const onWatch = jest.fn()
const compile = createCompiler(simple.context)
const observer = new ThemekitObserver(simple.options, compile)
observer.watch(onWatch)
observer.update('token1', 'value-1-updated')
observer.reset()
await wait(100)
expect(onWatch).toBeCalledTimes(3)
expect(onWatch).toHaveBeenLastCalledWith({
css: [
{
content: 'token1:value-1,token2:value-2',
destination: 'tokens.css',
},
],
})
})
})

function wait(delay: number) {
Expand Down
12 changes: 10 additions & 2 deletions packages/core/src/internal/observer.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,21 @@
import { compile } from '../index'
import { CompileResult, CompileOptions } from '../compiler'
import { TokenValue } from '../types'
import { RawToken, TokenValue } from '../types'
import deepcopy from 'deepcopy'

export type Watcher = (payload: CompileResult) => void
type Compile = typeof compile

export class ThemekitObserver {
private originalTokens: RawToken[]
private options: CompileOptions
private compile: Compile
private watchers: Set<Watcher> = new Set()

constructor(options: CompileOptions, _compile: Compile = compile) {
this.compile = _compile
this.options = options
this.options = deepcopy(options)
this.originalTokens = deepcopy(options.tokens)
this.run(options)
}

Expand All @@ -29,6 +32,11 @@ export class ThemekitObserver {
this.run(this.options)
}

reset() {
this.options.tokens = deepcopy(this.originalTokens)
this.run(this.options)
}

private run(options: CompileOptions) {
setImmediate(() => {
this.emit(this.compile(options))
Expand Down

0 comments on commit 1284f83

Please sign in to comment.