Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Playground refactor #106

Merged
merged 4 commits into from
Jan 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
"jotai",
"jscodeshift",
"jsxs",
"keyval",
"lebab",
"Minifier",
"outro",
Expand Down
3 changes: 3 additions & 0 deletions packages/playground/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,16 +43,19 @@
"@vueuse/core": "^10.6.1",
"@vueuse/integrations": "^10.6.1",
"@wakaru/ast-utils": "workspace:*",
"@wakaru/shared": "workspace:*",
"@wakaru/unminify": "workspace:*",
"@wakaru/unpacker": "workspace:*",
"assert": "^2.1.0",
"codemirror": "^6.0.1",
"fflate": "^0.8.1",
"idb-keyval": "^6.2.1",
"jotai": "^2.6.0",
"jotai-vue": "^0.1.0",
"os": "^0.1.2",
"sortablejs": "^1.15.0",
"splitpanes": "^3.1.5",
"threads-es": "^1.0.0",
"vue": "^3.3.9",
"vue-codemirror": "^6.1.1",
"vue-router": "4.2.5"
Expand Down
7 changes: 4 additions & 3 deletions packages/playground/src/App.vue
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<script setup lang="ts">
import Header from './components/Header.vue'
import SideBar from './components/SideBar.vue'
import Main from './Main.vue'
</script>

<template>
Expand All @@ -9,9 +10,9 @@ import SideBar from './components/SideBar.vue'

<div>
<SideBar />
<main style="height: calc(100vh - 4rem); padding-left: 16rem;">
<router-view :key="$route.path" />
</main>
<Suspense>
<Main />
</Suspense>
</div>
</div>
</template>
11 changes: 11 additions & 0 deletions packages/playground/src/Main.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<script setup lang="ts">
import { prepare } from './atoms/module'

await prepare()
</script>

<template>
<main style="height: calc(100vh - 4rem); padding-left: 16rem;">
<router-view :key="$route.path" />
</main>
</template>
249 changes: 249 additions & 0 deletions packages/playground/src/atoms/module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,249 @@
import {
delMany as delIdbMany,
get as getIdb,
getMany as getIdbMany,
keys as keysIdb,
set as setIdb,
setMany as setIdbMany } from 'idb-keyval'
import { atom, getDefaultStore } from 'jotai/vanilla'
import { KEY_FILE_PREFIX, KEY_MODULE_MAPPING, KEY_MODULE_META } from '../const'
import { unminify } from '../worker'
import { enabledRuleIdsAtom, prettifyRules } from './rule'
import type { ImportInfo } from '@wakaru/ast-utils/imports'
import type { ModuleMapping, ModuleMeta } from '@wakaru/shared/types'

export type ModuleId = number | string

export interface CodeModule {
id: ModuleId

/** Whether the module is the entry module */
isEntry: boolean

code: string

transformed: string

/** A list of import meta */
import: ImportInfo[]

/** A map of exported name to local identifier */
export: Record<string, string>

/**
* A map of top-level local identifier to a list of tags.
* A tag represents a special meaning of the identifier.
* For example, a function can be marked as a runtime
* function, and be properly transformed by corresponding
* rules.
*/
tags: Record<string, string[]>
}

export type CodeModuleWithName = CodeModule & { name: string }

export function getDefaultCodeModule(moduleId: ModuleId = -1): CodeModule {
return {
id: moduleId,
isEntry: false,
code: '',
transformed: '',
import: [],
export: {},
tags: {},
}
}

export function getModuleDefaultName(module: CodeModule) {
return module.isEntry ? `entry-${module.id}.js` : `module-${module.id}.js`
}

const _moduleMappingAtom = atom<ModuleMapping>({})
export const moduleMappingAtom = atom(
get => get(_moduleMappingAtom),
(_get, set, newMapping: ModuleMapping) => {
set(_moduleMappingAtom, newMapping)
setIdb(KEY_MODULE_MAPPING, newMapping)
},
)

const _modulesAtom = atom<CodeModule[]>([])
export const modulesAtom = atom(
(get) => {
const modules = get(_modulesAtom)
const moduleMapping = get(moduleMappingAtom)

const moduleWithNames = modules.map((mod) => {
const mappedName = moduleMapping[mod.id]
if (mappedName) return { ...mod, name: mappedName }

return { ...mod, name: getModuleDefaultName(mod) }
})

return [
...moduleWithNames.filter(mod => mod.isEntry).sort((a, b) => +a.id - +b.id),
...moduleWithNames.filter(mod => !mod.isEntry).sort((a, b) => +a.id - +b.id),
]
},
(get, set, adds: CodeModule[], updates: CodeModule[], deletes: ModuleId[], skipSync = false) => {
const modules = get(_modulesAtom)
const newModules = [...modules, ...adds].filter(mod => !deletes.includes(mod.id))
updates.forEach((mod) => {
const idx = newModules.findIndex(m => m.id === mod.id)
if (idx !== -1) newModules[idx] = mod
})
set(_modulesAtom, newModules)

if (adds.length > 0) {
const moduleMapping = get(moduleMappingAtom)
const newModuleMapping = { ...moduleMapping }

let changed = false
adds.forEach((mod) => {
if (moduleMapping[mod.id]) return
changed = true
newModuleMapping[mod.id] = getModuleDefaultName(mod)
})
if (changed) {
set(moduleMappingAtom, newModuleMapping)
}
}

if (!skipSync) {
setIdbMany([...adds, ...updates].map(mod => [`${KEY_FILE_PREFIX}${mod.id}`, mod]))
delIdbMany(deletes.map(modId => `${KEY_FILE_PREFIX}${modId}`))
}
},
)

export function getModuleAtom(moduleId: ModuleId) {
moduleId = moduleId.toString()
return atom(
(get) => {
const modules = get(modulesAtom)
return modules.find(mod => mod.id.toString() === moduleId) || {
name: `module-${moduleId}.js`,
...getDefaultCodeModule(moduleId),
}
},
(get, set, updateValue: Partial<Exclude<CodeModule, 'id'>>) => {
const modules = get(modulesAtom)
const moduleIdx = modules.findIndex(mod => mod.id.toString() === moduleId)
if (moduleIdx === -1) return

const module = modules[moduleIdx]
const updatedModule = { ...module, ...updateValue }
set(modulesAtom, [], [updatedModule], [])
},
)
}

type ModuleAtom = ReturnType<typeof getModuleAtom>

/**
* Module Meta is a computed result of all modules.
*
* This atom is used to override the computed result. Used by shared url.
*/
const _moduleMetaOverrideAtom = atom<ModuleMeta | null>(null)
export const moduleMetaOverrideAtom = atom(
get => get(_moduleMetaOverrideAtom),
(_get, set, newMeta: ModuleMeta | null) => {
set(_moduleMetaOverrideAtom, newMeta)
setIdb(KEY_MODULE_META, newMeta)
},
)

export const moduleMetaAtom = atom<ModuleMeta>((get) => {
const moduleMetaOverride = get(moduleMetaOverrideAtom)
if (moduleMetaOverride) return moduleMetaOverride

const modules = get(modulesAtom)
const moduleMeta = modules.reduce((acc, mod) => {
acc[mod.id] = {
import: mod.import,
export: mod.export,
tags: mod.tags,
}
return acc
}, {} as ModuleMeta)

return moduleMeta
})

export const prettifyAllModulesAtom = atom(null, async (get, set) => {
const modules = get(modulesAtom)

await Promise.all(modules.map(async (mod) => {
const result = await unminify({
name: mod.name,
module: mod,
transformationRuleIds: prettifyRules,
moduleMeta: {},
moduleMapping: {},
})

if (mod.code !== result.transformed) {
set(modulesAtom, [], [{ ...mod, code: result.transformed }], [])
}
}))
})

// export const prettifyModuleAtom = atom(null, async (get, set, moduleAtom: ModuleAtom) => {
// const module = get(moduleAtom)
// const result = await unminify({
// name: module.name,
// module,
// transformationRuleIds: prettifyRules,
// moduleMeta: {},
// moduleMapping: {},
// })
// if (module.code === result.transformed) return

// set(moduleAtom, { code: result.transformed })
// })

export const unminifyModuleAtom = atom(null, async (get, set, moduleAtom: ModuleAtom) => {
const module = get(moduleAtom)
const moduleMeta = get(moduleMetaAtom)
const moduleMapping = get(moduleMappingAtom)
const transformationRuleIds = get(enabledRuleIdsAtom)

const result = await unminify({
name: module.name,
module,
transformationRuleIds,
moduleMeta,
moduleMapping,
})
if (module.code === result.transformed) return

set(moduleAtom, { transformed: result.transformed })
})

export const resetModulesAtom = atom(null, (get, set) => {
set(moduleMetaOverrideAtom, null)
set(moduleMappingAtom, {})

const modules = get(modulesAtom)
set(modulesAtom, [], [], modules.map(mod => mod.id))
})

export async function prepare() {
const keys = await keysIdb()
const moduleKeys = keys.filter(key => typeof key === 'string' && key.startsWith(KEY_FILE_PREFIX))
if (moduleKeys.length > 0) {
const moduleMapping = await getIdb(KEY_MODULE_MAPPING)
if (moduleMapping) {
getDefaultStore().set(moduleMappingAtom, moduleMapping)
}

const moduleMeta = await getIdb(KEY_MODULE_META)
if (moduleMeta) {
getDefaultStore().set(moduleMetaOverrideAtom, moduleMeta)
}

const modules = await getIdbMany(moduleKeys)
getDefaultStore().set(modulesAtom, modules, [], [], true)
}
}
6 changes: 6 additions & 0 deletions packages/playground/src/atoms/rule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,12 @@ import { atomWithStorage } from 'jotai/utils'
import { atom } from 'jotai/vanilla'
import { KEY_DISABLED_RULES, KEY_RULE_ORDER } from '../const'

export const prettifyRules = [
'un-sequence-expression1',
'un-variable-merging',
'prettier',
]

export const allRulesAtom = atom(() => transformationRules)

export const ruleOrderAtom = atomWithStorage<string[]>(KEY_RULE_ORDER, transformationRules.map(rule => rule.id))
Expand Down
2 changes: 1 addition & 1 deletion packages/playground/src/components/ShareBtn.vue
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

<template>
<button
class="absolute top-0 right-6 flex items-center p-2 text-xs font-medium rounded-lg outline-none
class="absolute top-0 right-0 flex items-center p-2 text-xs font-medium rounded-lg outline-none
text-gray-700 dark:text-gray-200
bg-gray-200 dark:bg-gray-700
hover:bg-gray-300 dark:hover:bg-gray-600"
Expand Down
Loading