|
| 1 | +import { Denops, execute, group, GroupHelper } from "./deps.ts"; |
| 2 | +import { Buffer } from "./buffer.ts"; |
| 3 | +import { Component, Route } from "./router.ts"; |
| 4 | + |
| 5 | +export class DenopsApp { |
| 6 | + #appName: string; |
| 7 | + #routes: { |
| 8 | + pathRegexp: RegExp; |
| 9 | + component: Component; |
| 10 | + }[]; |
| 11 | + #denops: Denops; |
| 12 | + #commands: { |
| 13 | + name: string; |
| 14 | + path: string; |
| 15 | + }[]; |
| 16 | + |
| 17 | + constructor(appName: string, denops: Denops) { |
| 18 | + this.#appName = appName; |
| 19 | + this.#routes = []; |
| 20 | + this.#denops = denops; |
| 21 | + this.#commands = []; |
| 22 | + } |
| 23 | + |
| 24 | + setRoutes(routes: Route[]) { |
| 25 | + this.#routes = routes.map((route) => ({ |
| 26 | + pathRegexp: new RegExp( |
| 27 | + "^" + route.path.replaceAll(/\/:(\w+)/g, "/(?<$1>\\w+)") + "$", |
| 28 | + ), |
| 29 | + component: route.component, |
| 30 | + })); |
| 31 | + console.log(this.#routes); |
| 32 | + } |
| 33 | + |
| 34 | + addCommand(name: string, path: string) { |
| 35 | + this.#commands.push({ name: name, path: path }); |
| 36 | + } |
| 37 | + |
| 38 | + matchRoute(path: string): Promise<Buffer> { |
| 39 | + for (const route of this.#routes) { |
| 40 | + const matched = path.match(route.pathRegexp); |
| 41 | + |
| 42 | + if (!matched) { |
| 43 | + continue; |
| 44 | + } |
| 45 | + |
| 46 | + const pathParams = matched.groups || {}; |
| 47 | + return route.component(pathParams); |
| 48 | + } |
| 49 | + |
| 50 | + throw Error("not found"); |
| 51 | + } |
| 52 | + |
| 53 | + async initialize() { |
| 54 | + this.#denops.dispatcher = { |
| 55 | + renderContents: async (path: unknown): Promise<void> => { |
| 56 | + const buffer = await this.matchRoute( |
| 57 | + (path as string).substring(`denopsapp://${this.#denops.name}`.length), |
| 58 | + ); |
| 59 | + await buffer.render(this.#denops); |
| 60 | + }, |
| 61 | + }; |
| 62 | + |
| 63 | + this.#commands.forEach(async (cmd) => { |
| 64 | + await execute( |
| 65 | + this.#denops, |
| 66 | + `command! ${cmd.name} split denopsapp://${this.#denops.name}${cmd.path}`, |
| 67 | + ); |
| 68 | + }); |
| 69 | + |
| 70 | + await group( |
| 71 | + this.#denops, |
| 72 | + `${this.#appName}-buffer`, |
| 73 | + (helper: GroupHelper) => { |
| 74 | + helper.define( |
| 75 | + "BufReadCmd", |
| 76 | + `denopsapp://${this.#appName}/*`, |
| 77 | + `call denops#notify('${this.#denops.name}', 'renderContents', [expand('<amatch>')])`, |
| 78 | + ); |
| 79 | + }, |
| 80 | + ); |
| 81 | + } |
| 82 | +} |
0 commit comments