xref: /aosp_15_r20/external/ktfmt/website/index/index.js (revision 5be3f65c8cf0e6db0a7e312df5006e8e93cdf9ec)
1/**
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* Forked from https://microsoft.github.io/monaco-editor/ */
18
19"use strict";
20
21var editor = null;
22var style = "--kotlinlang-style";
23var columnLimit = 100;
24var options = null;
25
26require.config({ paths: { vs: "node_modules/monaco-editor/min/vs" } });
27
28$(document).ready(function () {
29  require(["vs/editor/editor.main"], function () {
30    editor = monaco.editor.create(document.getElementById("editor"), {
31      value: [
32        "/**",
33        " * Formats the given Javadoc comment, which must start with /** and end with */. The output will",
34        " * start and end with the same characters.",
35        " */",
36        "class Handler : RequestHandler<APIGatewayProxyRequestEvent, String> {",
37        "    override fun handleRequest(event: APIGatewayProxyRequestEvent, context: Context?): String {",
38        "        for ((i, item) in items.withIndex()) {",
39        "            if (needDot) {",
40        "                // fillMode is bla bla",
41        "                val fillMode =",
42        "                    if (unconsumedPrefixes.isNotEmpty() && i <= unconsumedPrefixes.peekFirst()) {",
43        "                        prefixFillMode /* bla bla */",
44        "                    } else {",
45        "                        Doc.FillMode.UNIFIED",
46        "                    }",
47        '                builder.breakOp(fillMode, "", ZERO, Optional.of(nameTag))',
48        "                builder.token((item as KtQualifiedExpression).operationSign.value)",
49        "            }",
50        "            emitSelectorUpToParenthesis(item)",
51        "            if (unconsumedPrefixes.isNotEmpty() && i == unconsumedPrefixes.peekFirst()) {",
52        "                builder.close()",
53        "                unconsumedPrefixes.removeFirst()",
54        "            }",
55        "            if (i == items.size - 1 && hasTrailingLambda) {",
56        "                builder.close()",
57        "            }",
58        "            val argsIndent =",
59        "                Indent.If.make(",
60        "                    nameTag,",
61        "                    expressionBreakIndent,",
62        "                    if (trailingDereferences) expressionBreakIndent else ZERO",
63        "                )",
64        "        }",
65        "    }",
66        "}",
67      ].join("\n"),
68      language: "kotlin",
69      rulers: [columnLimit],
70      scrollBeyondLastLine: false,
71    });
72  });
73  options = editor.getOptions();
74  window.onresize = function () {
75    editor.layout();
76  };
77
78  $(".style-picker").change(function () {
79    changeStyle(this.selectedIndex);
80  });
81
82  $(".column-limit-picker").change(function () {
83    columnLimit = parseInt(this.value);
84    editor.updateOptions({'rulers': [columnLimit]});
85    reformatEditor();
86  });
87
88  $("#editorForm").submit(function (event) {
89    event.preventDefault();
90    reformatEditor();
91  });
92});
93
94function changeStyle(newStyle) {
95  style = newStyle === 0 ? "--kotlinlang-style" : undefined;
96  reformatEditor();
97}
98
99function reformatEditor() {
100    disableDemoUi();
101  $.ajax({
102    type: "POST",
103    url: "https://8uj6xa47qa.execute-api.us-east-2.amazonaws.com/ktfmt",
104    contentType: "application/json",
105    data: JSON.stringify({
106      source: editor.getValue(),
107      maxWidth: columnLimit,
108      style: style,
109    }),
110    dataType: "json",
111    error: function (xhr, errorType, errorThrown) {
112      showError(errorThrown);
113    },
114  })
115    .done(function (data) {
116      if (data.err) {
117        showError(data.err);
118      } else {
119        $("#error-message").hide();
120        editor.setValue(data.source);
121      }
122    })
123    .always(function () {
124        enableDemoUi();
125    });
126}
127
128function disableDemoUi() {
129    $('.loading.editor').show();
130    $("#editorForm :input").prop("disabled", true);
131    editor.updateOptions({ readOnly: true, language: 'text' });
132}
133
134function enableDemoUi() {
135    $("#editorForm :input").prop("disabled", false);
136    editor.updateOptions({ readOnly: false });
137    $('.loading.editor').fadeOut({ duration: 300 });
138}
139
140function showError(error) {
141  var errorMessage = $("#error-message");
142  errorMessage.text("Error: " + error);
143  errorMessage.show();
144}
145