| 29 | import { Schema as WebWorkerOptions } from './schema'; |
| 30 | |
| 31 | function addSnippet(options: WebWorkerOptions): Rule { |
| 32 | return (host: Tree, context: SchematicContext) => { |
| 33 | context.logger.debug('Updating appmodule'); |
| 34 | |
| 35 | if (options.path === undefined) { |
| 36 | return; |
| 37 | } |
| 38 | |
| 39 | const fileRegExp = new RegExp(`^${options.name}.*\\.ts`); |
| 40 | const siblingModules = host |
| 41 | .getDir(options.path) |
| 42 | .subfiles // Find all files that start with the same name, are ts files, |
| 43 | // and aren't spec or module files. |
| 44 | .filter((f) => fileRegExp.test(f) && !/(module|spec|config|routes)\.ts$/.test(f)) |
| 45 | // Sort alphabetically for consistency. |
| 46 | .sort(); |
| 47 | |
| 48 | if (siblingModules.length === 0) { |
| 49 | // No module to add in. |
| 50 | return; |
| 51 | } |
| 52 | |
| 53 | const siblingModulePath = `${options.path}/${siblingModules[0]}`; |
| 54 | const logMessage = 'console.log(`page got message: ${data}`);'; |
| 55 | const workerCreationSnippet = ` |
| 56 | if (typeof Worker !== 'undefined') { |
| 57 | // Create a new |
| 58 | const worker = new Worker(new URL('./${options.name}.worker', import.meta.url)); |
| 59 | worker.onmessage = ({ data }) => { |
| 60 | ${logMessage} |
| 61 | }; |
| 62 | worker.postMessage('hello'); |
| 63 | } else { |
| 64 | // Web Workers are not supported in this environment. |
| 65 | // You should add a fallback so that your program still executes correctly. |
| 66 | } |
| 67 | `; |
| 68 | |
| 69 | // Append the worker creation snippet. |
| 70 | const originalContent = host.readText(siblingModulePath); |
| 71 | host.overwrite(siblingModulePath, originalContent + '\n' + workerCreationSnippet); |
| 72 | |
| 73 | return host; |
| 74 | }; |
| 75 | } |
| 76 | |
| 77 | const webWorkerSchematic: RuleFactory<WebWorkerOptions> = createProjectSchematic( |
| 78 | (options, { project }) => { |