1+ import CommonplaceNotesPlugin from '../main' ;
2+ import { Logger } from './logging' ;
3+ import { PathUtils } from './path' ;
4+ import { NoticeManager } from './notice' ;
5+
6+ export class TemplateManager {
7+ private plugin : CommonplaceNotesPlugin ;
8+ private readonly DEFAULT_TEMPLATE_URL = 'https://raw.githubusercontent.com/zachmueller/commonplace-notes/main/templates/local-template.html' ;
9+
10+ constructor ( plugin : CommonplaceNotesPlugin ) {
11+ this . plugin = plugin ;
12+ }
13+
14+ async ensureLocalTemplate ( ) : Promise < boolean > {
15+ const templatePath = this . plugin . profileManager . getLocalTemplateHtmlPath ( ) ;
16+
17+ // Check if template already exists
18+ if ( await this . plugin . app . vault . adapter . exists ( templatePath ) ) {
19+ Logger . debug ( 'Local template file already exists' ) ;
20+ return true ;
21+ }
22+
23+ // Try to download default template
24+ Logger . info ( 'Local template not found, attempting to download default template from GitHub' ) ;
25+
26+ try {
27+ const { success, error } = await NoticeManager . showProgress (
28+ 'Downloading default template from GitHub' ,
29+ this . downloadDefaultTemplate ( templatePath ) ,
30+ 'Successfully downloaded default template' ,
31+ 'Failed to download template from GitHub'
32+ ) ;
33+
34+ return success ;
35+ } catch ( error ) {
36+ Logger . error ( 'Failed to download default template:' , error ) ;
37+ NoticeManager . showNotice ( 'Failed to download HTML template.' ) ;
38+ return false ;
39+ }
40+ }
41+
42+ private async downloadDefaultTemplate ( templatePath : string ) : Promise < void > {
43+ // Ensure template directory exists
44+ const templateDir = this . plugin . profileManager . getTemplateDir ( ) ;
45+ await PathUtils . ensureDirectory ( this . plugin , templateDir ) ;
46+
47+ // Download the template
48+ const response = await fetch ( this . DEFAULT_TEMPLATE_URL ) ;
49+
50+ if ( ! response . ok ) {
51+ throw new Error ( `HTTP ${ response . status } : ${ response . statusText } ` ) ;
52+ }
53+
54+ const templateContent = await response . text ( ) ;
55+
56+ // Validate that it looks like an HTML template
57+ if ( ! templateContent . includes ( '{{NOTES_JSON}}' ) ) {
58+ throw new Error ( 'Downloaded file does not appear to be a valid template' ) ;
59+ }
60+
61+ // Write to local file
62+ await this . plugin . app . vault . adapter . write ( templatePath , templateContent ) ;
63+ Logger . info ( `Downloaded default template to ${ templatePath } ` ) ;
64+ }
65+ }
0 commit comments