返回 slidev
projects.ts
根目录 / packages / vscode / src / projects.ts
1 import type { LoadedSlidevData } from '@slidev/parser/fs'
2 import type { ComputedRef, EffectScope, Ref, ShallowRef } from 'reactive-vscode'
3 import type { SlidevServer } from './composables/useDevServer'
4 import type { DetectedServerState } from './composables/useServerDetector'
5 import { existsSync } from 'node:fs'
6 import { debounce, slash } from '@antfu/utils'
7 import { load } from '@slidev/parser/fs'
8 import { basename, dirname } from 'pathe'
9 import { isMatch } from 'picomatch'
10 import { computed, effectScope, extensionContext, markRaw, onScopeDispose, ref, shallowReactive, shallowRef, useDisposable, useFileSystemWatcher, useVscodeContext, watch, watchEffect } from 'reactive-vscode'
11 import { FileSystemError, Uri, window, workspace } from 'vscode'
12 import { useServerDetector } from './composables/useServerDetector'
13 import { config } from './configs'
14 import { findShallowestPath } from './utils/findShallowestPath'
15 import { logger } from './views/logger'
16
17 export interface SlidevProject {
18 readonly scope: EffectScope
19 readonly entry: string
20 readonly userRoot: string
21 readonly data: LoadedSlidevData
22 readonly port: Ref<number | null>
23 readonly server: ShallowRef<SlidevServer | null>
24 readonly detected: ComputedRef<DetectedServerState | null>
25 }
26
27 export const projects = shallowReactive(new Map<string, SlidevProject>())
28 export const slidevFiles = computed(() => [
29 ...projects.values(),
30 ].flatMap(p => Object.keys(p.data.markdownFiles)))
31 export const activeEntry = ref<string | null>(null)
32 export const activeProject = computed(() => activeEntry.value
33 ? projects.get(activeEntry.value)
34 : undefined)
35 export const activeData = computed(() => activeProject.value?.data)
36
37 export function useProjects() {
38 useFileSystemWatcher(() => config.include, {
39 async onDidCreate(uri) {
40 const path = slash(uri.fsPath)
41 if (!isMatch(path, config.exclude))
42 await addProject(path)
43 },
44 onDidChange: false,
45 async onDidDelete(uri) {
46 removeProject(slash(uri.fsPath))
47 },
48 })
49
50 rescanProjects()
51 watch(() => [config.include, config.exclude], debounce(200, rescanProjects))
52
53 // In case all the projects are removed manually, and the user may not want to disable the extension.
54 const everHadProjects = ref(false)
55 watchEffect(() => {
56 if (projects.size > 0)
57 everHadProjects.value = true
58 })
59
60 // Save active project to workspace state
61 watchEffect(() => {
62 if (activeEntry.value)
63 extensionContext.value!.workspaceState.update('slidev:activeProject', activeEntry.value)
64 })
65
66 // Auto set active project
67 watch(() => [
68 ...projects.keys(),
69 activeEntry.value,
70 ], () => {
71 if (!activeEntry.value) {
72 const previous = extensionContext.value!.workspaceState.get('slidev:activeProject', null)
73 if (previous && projects.has(previous)) {
74 activeEntry.value = previous
75 return
76 }
77 const firstKind = findShallowestPath(
78 [
79 ...projects.keys(),
80 ].filter(path => basename(path) === 'slides.md'),
81 )
82 if (firstKind) {
83 activeEntry.value = firstKind
84 return
85 }
86 const secondKind = findShallowestPath(projects.keys())
87 if (secondKind) {
88 activeEntry.value = secondKind
89 }
90 }
91 }, { immediate: true })
92
93 useVscodeContext('slidev:enabled', () => {
94 const forceEnabled = config['force-enabled']
95 const enabled = forceEnabled ?? everHadProjects.value
96 logger.info(`Slidev ${enabled ? 'enabled' : 'disabled'}.`)
97 return enabled
98 })
99 useVscodeContext('slidev:hasActiveProject', () => !!activeEntry.value)
100
101 onScopeDispose(() => {
102 for (const project of projects.values()) {
103 project.scope.stop()
104 }
105 projects.clear()
106 })
107 }
108
109 let scanningProjects = false
110 export const scannedProjects = ref(false)
111 export async function rescanProjects() {
112 if (scanningProjects)
113 return
114 scanningProjects = true
115 try {
116 const entries = new Set<string>()
117 for (const glob of config.include) {
118 (await workspace.findFiles(glob, config.exclude))
119 .forEach(file => entries.add(file.fsPath))
120 }
121 for (const entry of entries) {
122 await addProject(slash(entry))
123 }
124 for (const project of projects.values()) {
125 if (!existsSync(project.entry)) {
126 removeProject(project.entry)
127 }
128 }
129 }
130 finally {
131 scanningProjects = false
132 scannedProjects.value = true
133 }
134 }
135
136 export async function addProject(entry: string) {
137 if (projects.has(entry))
138 return projects.get(entry)!
139
140 const { getDetected } = useServerDetector()
141
142 const scope = effectScope(true)
143 const data = shallowRef<LoadedSlidevData>(await loadProject(entry))
144 const project: SlidevProject = {
145 scope,
146 entry,
147 userRoot: dirname(entry),
148 get data() {
149 return data.value
150 },
151 server: shallowRef(null),
152 port: ref(null),
153 detected: computed(() => getDetected(project)),
154 }
155
156 scope.run(() => {
157 // Handle changes. VSCode already debounces rapid changes itself.
158 let pendingReload: Promise<LoadedSlidevData> | null = null
159 useDisposable(workspace.onDidChangeTextDocument(async ({ document }) => {
160 const path = slash(document.uri.fsPath)
161 if (data.value?.watchFiles[path]) {
162 const thisReload = pendingReload = loadProject(entry)
163 const newData = await thisReload
164 if (pendingReload === thisReload) { // still the latest
165 data.value = newData
166 pendingReload = null
167 }
168 }
169 }))
170
171 useDisposable(workspace.onDidCloseTextDocument(async (document) => {
172 const path = slash(document.uri.fsPath)
173 if (path !== entry) {
174 return
175 }
176 try {
177 await workspace.fs.stat(document.uri)
178 }
179 catch (err) {
180 if (err instanceof FileSystemError && err.code === 'FileNotFound') {
181 removeProject(entry)
182 }
183 }
184 }))
185
186 onScopeDispose(() => {
187 projects.get(entry)?.server.value?.scope.stop()
188 })
189 })
190
191 projects.set(entry, project)
192 return project
193 }
194
195 export function removeProject(entry: string) {
196 const project = projects.get(entry)
197 if (!project)
198 return
199 if (activeEntry.value === entry)
200 activeEntry.value = null
201 project.scope.stop()
202 projects.delete(entry)
203 }
204
205 async function loadProject(entry: string) {
206 const userRoot = dirname(entry)
207 return markRaw(await load({
208 userRoot,
209 roots: [userRoot],
210 }, entry, async (path: string) => {
211 const document = workspace.textDocuments.find(d => slash(d.uri.fsPath) === path)
212 if (document) {
213 return document.getText()
214 }
215 const buffer = await workspace.fs.readFile(Uri.file(path))
216 return (new TextDecoder('utf-8')).decode(buffer)
217 }))
218 }
219
220 const ignoredEntries = new Set<string>()
221 export async function askAddProject(entry: string, message: string) {
222 if (projects.has(entry) || ignoredEntries.has(entry))
223 return
224 if (!workspace.getWorkspaceFolder(Uri.file(entry))) {
225 return
226 }
227 const result = await window.showInformationMessage(`${message}\nDo you want to add ${entry} as a Slidev project?`, 'Yes', 'No')
228 if (result === 'Yes') {
229 await addProject(entry)
230 }
231 else {
232 ignoredEntries.add(entry)
233 }
234 }
235
235 lines TYPESCRIPT