Escher-js / SkimmedMilk

0 stars 0 forks source link

step1. initialize project #1

Closed psmuler closed 1 year ago

psmuler commented 1 year ago

ユーザーのPCで動くelectronでコードしたアプリを作ります。プロジェクトの初期化プロセスを教えてください

psmuler commented 1 year ago

Electronを使用してアプリを開発するには、まずNode.jsとnpm(Node Package Manager)がインストールされていることを確認してください。その後、以下の手順でプロジェクトを初期化できます。

  1. プロジェクトフォルダの作成: 新しいプロジェクトのディレクトリを作成し、そのディレクトリに移動します。
mkdir my-electron-app
cd my-electron-app
  1. package.jsonファイルの初期化: npmを使ってプロジェクトを初期化し、package.jsonファイルを生成します。
npm init

プロンプトに従ってプロジェクト情報を入力します。特にentry pointについては、Electronアプリのメインファイル名(通常はmain.jsまたはindex.js)を指定してください。

  1. Electronをインストール: 次に、Electronをプロジェクトの依存関係としてインストールします。
npm install electron --save-dev
  1. メインファイルの作成: 先ほど指定したメインファイル(例:main.js)をプロジェクトルートに作成します。このファイルには、Electronアプリの起動とウィンドウの作成に関するコードが入ります。

main.jsの例:

const { app, BrowserWindow } = require('electron');

function createWindow() {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
    },
  });

  win.loadFile('index.html');
}

app.whenReady().then(createWindow);

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});
  1. index.htmlファイルの作成: プロジェクトルートにindex.htmlファイルを作成し、アプリのUIを定義します。

index.htmlの例:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>My Electron App</title>
  </head>
  <body>
    <h1>Hello, Electron!</h1>
  </body>
</html>
  1. package.jsonファイルに起動スクリプトを追加: package.jsonファイルのscriptsセクションに、アプリを起動するスクリプトを追加します。
"scripts": {
  "start": "electron ."
},
  1. アプリの実行: 以下のコマンドを実行して、Electronアプリを起動します。
npm start

これで、Electronでコードされたアプリの開

psmuler commented 1 year ago

画面に"File"と書かれたボタンを用意し、押されたらローカルから読み込むファイルを選択するためのポップアップを表示しましょう。

psmuler commented 1 year ago

Electronアプリで「File」と書かれたボタンを作成し、クリックするとファイルを選択するためのポップアップが表示されるようにするには、以下の手順を実行してください。

  1. index.htmlファイルにボタンを追加:

index.htmlファイルに、"File"というテキストが表示されたボタンを追加します。

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>My Electron App</title>
  </head>
  <body>
    <h1>Hello, Electron!</h1>
    <button id="file-btn">File</button>

    <script src="renderer.js"></script>
  </body>
</html>
  1. renderer.jsファイルの作成:

プロジェクトルートにrenderer.jsというファイルを作成し、以下のコードを追加します。このファイルでは、ボタンがクリックされたときのイベントリスナーを定義します。

const { ipcRenderer } = require('electron');

const fileBtn = document.getElementById('file-btn');

fileBtn.addEventListener('click', () => {
  ipcRenderer.send('open-file-dialog');
});
  1. main.jsファイルの更新:

main.jsファイルに、ipcMainを使用して、renderer.jsからのメッセージを受信し、ファイルダイアログを開くコードを追加します。

const { app, BrowserWindow, ipcMain, dialog } = require('electron');

function createWindow() {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      enableRemoteModule: true
    },
  });

  win.loadFile('index.html');
}

app.whenReady().then(createWindow);

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});

ipcMain.on('open-file-dialog', (event) => {
  const options = {
    title: 'Select a file',
    properties: ['openFile'],
  };

  dialog.showOpenDialog(null, options).then((result) => {
    if (!result.canceled) {
      console.log('Selected file:', result.filePaths[0]);
    }
  });
});
  1. アプリの実行:

以下のコマンドでElectronアプリを起動します。

npm start

これで、「File」と書かれたボタンが表示され、クリックするとファイル選択ポップアップが表示されるようになります。選択したファイルのパスは、main.js内のconsole.logで表示されます。

psmuler commented 1 year ago

簡単なテキストエディタを導入し、先ほど読み込んだ.md形式ファイルを表示しましょう。変更を加えた後の保存機能もつけてください。以下コード内で変更がない点は必ず省略してください。

psmuler commented 1 year ago

簡単なテキストエディタを作成し、.md形式のファイルを開いて表示し、変更を加えて保存できるようにするには、以下の手順を実行してください。

  1. index.htmlファイルを更新:

テキストエディタ用の<textarea>要素と、"Save"ボタンを追加します。

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>My Electron App</title>
  </head>
  <body>
    <h1>Hello, Electron!</h1>
    <button id="file-btn">Open</button>
    <button id="save-btn">Save</button>
    <br />
    <textarea id="text-editor" rows="20" cols="80"></textarea>

    <script src="renderer.js"></script>
  </body>
</html>
  1. renderer.jsファイルを更新:

ファイルを開いてテキストエディタに表示する処理と、変更を加えた後の保存機能を追加します。

const { ipcRenderer } = require('electron');
const fs = require('fs');

const fileBtn = document.getElementById('file-btn');
const saveBtn = document.getElementById('save-btn');
const textEditor = document.getElementById('text-editor');

let currentFilePath = null;

fileBtn.addEventListener('click', () => {
  ipcRenderer.send('open-file-dialog');
});

saveBtn.addEventListener('click', () => {
  if (currentFilePath) {
    saveFile(currentFilePath);
  } else {
    ipcRenderer.send('save-file-dialog');
  }
});

ipcRenderer.on('selected-file', (event, filePath) => {
  currentFilePath = filePath;
  fs.readFile(filePath, 'utf-8', (err, data) => {
    if (err) {
      console.error(err);
      return;
    }
    textEditor.value = data;
  });
});

ipcRenderer.on('selected-save-path', (event, savePath) => {
  currentFilePath = savePath;
  saveFile(currentFilePath);
});

function saveFile(filePath) {
  const content = textEditor.value;
  fs.writeFile(filePath, content, (err) => {
    if (err) {
      console.error(err);
      return;
    }
    console.log('File saved:', filePath);
  });
}
  1. main.jsファイルを更新:

ファイルダイアログで選択したファイルをrenderer.jsに送信し、保存ダイアログを表示するコードを追加します。

const { app, BrowserWindow, ipcMain, dialog } = require('electron');

// ... (createWindow, app.whenReady, app.onのコードは省略) ...

ipcMain.on('open-file-dialog', (event) => {
  const options = {
    title: 'Select a file',
    properties: ['openFile'],
    filters: [{ name: 'Markdown', extensions: ['md'] }],
  };

  dialog.showOpenDialog(null, options).then((result) => {
    if (!result.canceled) {
      const filePath = result.filePaths[0];
      event.sender.send('selected-file', filePath);
    }
  });
});
ipcMain.on('save-file-dialog', (event) => {
  const options = {
    title: 'Save file',
    filters: [{ name: 'Markdown', extensions: ['md'] }],
  };

  dialog.showSaveDialog(null, options).then((result) => {
    if (!result.canceled) {
      const savePath = result.filePath;
      event.sender.send('selected-save-path', savePath);
    }
  });
});

これで、簡単なテキストエディタを導入し、.md形式のファイルを開いて表示し、変更を加えた後に保存できるようになりました。npm startコマンドを使ってアプリを起動し、"Open"ボタンで.mdファイルを開き、テキストエディタで編集した後、"Save"ボタンで変更を保存できます。