GASを使って、シンプルな縦書きテキストエディタを作成しよう。
GAS(Google Apps Script)とJavaScriptを使って、シンプルなテキストエディタを作成する。
![](https://assets.st-note.com/img/1719328032057-vNSeLNI4Dj.png?width=1200)
以下、コード.gsの中身
function doGet(e) {
const template = HtmlService.createTemplateFromFile('index');
const htmlOutput = template.evaluate();
htmlOutput.setTitle('シンプルな縦書きテキストエディタ');
return htmlOutput;
}
function saveTextToUserProperty(text) {
const userProperties = PropertiesService.getUserProperties();
userProperties.setProperty('savedText', text);
}
function getTextFromUserProperty() {
const userProperties = PropertiesService.getUserProperties();
return userProperties.getProperty('savedText') || '';
}
続いて、index.htmlの中身
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>シンプルな縦書きテキストエディタ</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
font-family: serif;
width: 95%;
padding: 0 20px;
}
#editor {
writing-mode: vertical-rl;
text-orientation: upright;
border: none;
outline: none;
padding: 25px;
width: 100%;
height: 20.8em;
overflow: auto;
font-size: 20px;
letter-spacing: 0.02em;
font-kerning: normal;
line-height: 2.5;
hanging-punctuation: last allow-end;
background-color: #f5f5f5;
}
</style>
</head>
<body>
<div id="editor" contenteditable="true">
<!-- 縦書きの日本語テキストをここに入力します -->
</div>
<script>
document.addEventListener('DOMContentLoaded', (event) => {
google.script.run.withSuccessHandler((text) => {
var editor = document.getElementById('editor');
editor.innerText = text;
placeCaretAtEnd(editor);
}).getTextFromUserProperty();
});
function saveText() {
var textToSave = document.getElementById('editor').innerText;
google.script.run.saveTextToUserProperty(textToSave);
}
function placeCaretAtEnd(el) {
el.focus();
if (typeof window.getSelection != "undefined" && typeof document.createRange != "undefined") {
var range = document.createRange();
range.selectNodeContents(el);
range.collapse(false);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (typeof document.body.createTextRange != "undefined") {
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.collapse(false);
textRange.select();
}
}
setInterval(saveText, 5000); // 5秒ごとにテキストを保存
</script>
</body>
</html>
機能は、5秒ごとに編集中のテキストを自動保存する。
※保存先は、gasのユーザープロパティとする。
また、機能とは言えないが、webアプリを開いたとき、テキスト編集エリアの最後にカーソルが移動するようになっている。
この記事が気に入ったらサポートをしてみませんか?