File size: 2,525 Bytes
4ffe709
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
server <- function(input, output, session) {
  # Reactive variable to store the original file content
  originalFileContent <- reactiveVal()
  
  # Observe file upload
  observeEvent(input$file1, {
    req(input$file1)
    # Read the file content
    fileContent <- readLines(input$file1$datapath)
    # Store the original file content
    originalFileContent(fileContent)
    # Update Ace editor with file content
    updateAceEditor(session, "code", value = paste(fileContent, collapse = "\n"), theme = "monokai")
  })
  
  # Function to generate YAML header
  generate_yaml <- function() {
    yaml_header <- c(
      "---",
      paste0("author: ", input$author),
      paste0("date: ", if(input$date_type == 'custom') {input$date} else {'"`r Sys.Date()`"'}),
      paste0("description: ", input$description),
      "format:",
      "  html:",
      paste0("    highlight-style: ", input$highlight_style),
      paste0("    theme: ", input$theme),
      paste0("    toc: ", ifelse(input$toc, "true", "false")),
      "    code-fold: true",
      paste0("    file: ", tools::file_path_sans_ext(input$file1$name), ".", tools::file_ext(input$file1$name)),
      paste0("    title: ", input$title),
      paste0('    subtitle: "', input$subtitle, '"')
    )
    
    if (input$`toc-float`) {
      yaml_header <- c(yaml_header,
                       "    toc_float:",
                       "      collapsed: true",
                       "      smooth_scroll: true")
    }
    
    yaml_header <- c(yaml_header, "---")
    
    return(yaml_header)
  }
  
  
  # Observe generate button
  observeEvent(input$generate, {
    # Generate YAML header
    yaml_header <- generate_yaml()
    # Combine YAML header and original file content
    new_fileContent <- c(yaml_header, originalFileContent())
    # Update Ace editor with new file content
    updateAceEditor(session, "code", value = paste(new_fileContent, collapse = "\n"))
  })
  
  # Download handler
  output$Download <- downloadHandler(
    
    filename = function() {
      paste(tools::file_path_sans_ext(input$file1$name), ".", tools::file_ext(input$file1$name), sep = "")
    },
    content = function(file) {
      # Generate YAML header
      yaml_header <- generate_yaml()
      # Combine YAML header and original file content
      new_fileContent <- c(yaml_header, originalFileContent())
      # Write the new file content to the file
      writeLines(new_fileContent, file)
    }
  )
}