Repository: maxogden/elementary-electron Branch: master Commit: 7e678a5508ba Files: 31 Total size: 24.5 KB Directory structure: gitextract_k9f45znx/ ├── .gitignore ├── bin/ │ └── elementary-electron ├── exercises/ │ ├── cat_annotation/ │ │ ├── exercise.js │ │ ├── problem.en.md │ │ ├── problem.ja.md │ │ └── problem.ko.md │ ├── cat_picture/ │ │ ├── exercise.js │ │ ├── problem.en.md │ │ ├── problem.ja.md │ │ └── problem.ko.md │ ├── hello_world/ │ │ ├── exercise.js │ │ ├── problem.en.md │ │ ├── problem.ja.md │ │ └── problem.ko.md │ ├── installing/ │ │ ├── exercise.js │ │ ├── problem.en.md │ │ ├── problem.ja.md │ │ └── problem.ko.md │ └── save_pdf/ │ ├── exercise.js │ ├── problem.en.md │ ├── problem.ja.md │ └── problem.ko.md ├── i18n/ │ ├── en.json │ ├── ja.json │ └── ko.json ├── index.js ├── lib/ │ ├── checkAll.js │ ├── fsCheck.js │ └── pkgDependencyCheck.js ├── package.json └── readme.md ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ .DS_Store node_modules ================================================ FILE: bin/elementary-electron ================================================ #!/usr/bin/env node require('../index.js').execute(process.argv.slice(2)) ================================================ FILE: exercises/cat_annotation/exercise.js ================================================ var path = require('path') var checkAll = require('../../lib/checkAll.js') var fsCheck = require('../../lib/fsCheck.js') module.exports = function () { var problem = {} problem.requireSubmission = false problem.problem = {file: path.join(__dirname, 'problem.{lang}.md')} problem.verify = function (args, cb) { checkAll([ fsCheck(path.join('.', 'index.js')), fsCheck(path.join('.', 'node_modules', 'cat-picture')), fsCheck(path.join('.', 'node_modules', 'lightning-image-poly')) ], '', '{{exercise.cat_annotation.fail}}', cb) } return problem } ================================================ FILE: exercises/cat_annotation/problem.en.md ================================================ # Cat Annotation Now we're going to add a feature: draw polygon regions on the image! This could be useful for labeling objects or defining regions on a map. Add the following line to the `` section of your `index.html`, which adds an empty `div` element to hold our visualization. **Make sure** this comes **before** the ` ``` Then, use your text editor to create a new file in your directory called `index.js` with this line of code in it: ``` require('cat-picture') ``` Now when you run your app with `electron app.js` you should see a cat! When you think you are done with this challenge, run `elementary-electron verify` ================================================ FILE: exercises/cat_picture/problem.ja.md ================================================ # 猫の写真 これで作業をする土台が完成したので、新しい機能を実装することができます。 これから追加する新しい機能、それは「猫の写真を描画する」です。 この新しい機能を実装するのに、0からコードを書いても良いです。しかし、一般的なプログラミングのタスクと同様に他の誰かが既にコードを書いてくれているようです。Node.js は開発者に作成したコードのまとまりをパッケージ化して簡単に再利用する方法を提供しており、そのようなパッケージ(Node.js からは "modules" と呼ばれています)を作成・ダウンロード・インストールを行うための `npm` と呼ばれるプログラムも提供しています。もしあなたが R 言語に精通しているならば、`install.packages()` コマンドに非常に近いものといえば分かりやすいかもしれません。 それでは本題に戻ります。輝く猫の写真をアプリに追加しましょう。これを作るのに、`cat-picture` と呼ばれるモジュールを npmjs.org からインストールして使ってみましょう。このモジュールは、ウェブページに猫の写真を追加するためのものです。 この `cat-picture` モジュールをダウンロード・インストールするのに、`npm` コマンドを使います。しかし、その作業をする前に、このアプリケーションは何をするためのものか、Node.js にもう少し情報を伝えてみましょう。これを行うベストな方法は、_あなたのモジュール_ を作成することです! 自分のモジュールを作成するには、私たちのモジュールに関するいくつかの詳細、例えば依存している他のモジュールのリストなどを含んだ `package.json`というファイルを作成する必要があります。そして、`npm` は私たちのかわりにこれを行ってくれます! `npm init`コマンドを実行してみてください。このコマンドを実行すると、いくつかの質問が表示されるので回答してください。また、 答えがわからない場合は "enter" で飛ばすとデフォルトの回答がセットされます。 このコマンドが完了すると、コマンドを実行したディレクトリで `package.json` という名前のファイルが生成されます。チェックしてみてください!エディタで `package.json` を開いてみましょう。 次に、このコマンドを実行してみてください: `npm install cat-picture --save` この一連の流れは、`cat-picture` モジュールを `node_modules` という名前のフォルダにダウンロードし、cat-picture を `package.json`に追加するというものです。もし今 `package.json` をエディタで改めて開いてみると `cat-picture` の記述を確認することができるでしょう。 さて、モジュールのインストールが完了したので、いよいよアプリケーションで実際に使ってみましょう。まずは、 `index.html` ファイルを作成し、下記の一行を `` の中、かつ `

` の _あと_ に追加してみてください: ``` ``` 完了したら、同じディレクトリに `index.js` を追加し、エディタで開いて下記の一行を追加してみてください: ``` require('cat-picture') ``` これで、`electron app.js` を実行してアプリを開くと、猫の写真を見ることができます! このチャレンジが完了したら、`elementary-electron verify` を実行してください。 ================================================ FILE: exercises/cat_picture/problem.ko.md ================================================ # 고양이 사진 이제 새로운 기능들을 추가할 작업대가 만들어졌습니다. 그럼 첫 번째 기능을 추가해볼까요? 고양이 사진을 그려봅시다. 기능을 추가하기 위해 아예 처음부터 만드는 방법도 있습니다만, 여타 다른 프로그래밍 작업처럼, 누군가가 우리가 필요로 하는 기능을 이미 만든 경우가 많습니다. Node.js는 개발자가 자신이 작성한 프로그램을 패키지화해서 재사용을 쉽게 하도록 해줍니다. 또한 `npm`이라는 프로그램을 제공하여 그러한 프로그램(Node는 이걸 "modules"라고 부릅니다)들을 만들고, 내려받고, 설치하게 해줍니다. R을 사용해보신 적이 있다면 `npm`은 `install.packages()`와 비슷하다고 생각하시면 됩니다. 자 이제 본론으로 돌아와서 아름다운 고양이 사진을 앱에 추가해봅시다. 그러려면 `cat-picture`라는 모듈을 npmjs.org로부터 설치할 필요가 있습니다. 이 모듈은 웹 페이지에 고양이 사진을 추가하는 단순한 프로그램입니다. `cat-picture` 모듈을 설치하기 위해 `npm`이라는 명령어를 사용할것입니다. 이 작업을 하기 전에, 지금 만들고 있는 앱은 무엇을 하는 프로그램인지에 대해 Node.js에 알려줘야 합니다. 가장 좋은 방법은 실제로 _당신이 직접_ 모듈을 작성하는 것입니다. 모듈을 작성하려면 `package.json`이라는 파일을 만들면 됩니다. 이 파일에 우리가 만든 모듈에 대해서, 그리고 우리의 모듈이 의존하고 있는 모듈들의 리스트를 작성해야 합니다. 고맙게도 `npm`은 이 작업을 우리 대신 해줍니다! `npm init`을 실행해보세요. 몇 가지 질문에 응답해야 합니다. 뭐라고 답을 해야 할지 모르겠다면 그냥 엔터를 입력해서 디폴트로 설정하세요. `npm init`의 실행이 완료되면, 현재 디렉터리에 `package.json`이라는 파일이 생길 것입니다. 텍스트 에디터로 내용을 확인해보세요. 이제 다음 명령어를 실행해보세요. `npm install cat-picture --save` 그러면 `cat-picture` 모듈이 `node_modules`라는 폴더에 저장되고, `package.json`에도 모듈 이름이 표시될 것입니다. `package.json`을 텍스트 에디터로 열어보면, `cat-picture` 모듈이 언급되어 있을 것입니다. 이제 모듈을 설치했으니 우리의 앱에서 사용해 봅시다. 다음 코드를 `index.html`의 `` 태그 안에 작성하세요. 단 `

` 태그의 _뒤에_ 와야 하는 것에 주의하세요. ``` ``` 텍스트 에디터를 사용해서, 현재 디렉터리에 `index.js`라는 파일을 만들고 다음 코드를 작성하세요. ``` require('cat-picture') ``` 이제 `electron app.js`으로 앱을 실행하세요. 고양이가 보일 겁니다! 위의 과정을 완료하셨다면 `elementary-electron verify`를 실행해주세요. ================================================ FILE: exercises/hello_world/exercise.js ================================================ var path = require('path') var checkAll = require('../../lib/checkAll.js') var fsCheck = require('../../lib/fsCheck.js') module.exports = function () { var problem = {} problem.requireSubmission = false problem.problem = {file: path.join(__dirname, 'problem.{lang}.md')} problem.verify = function (args, cb) { checkAll([ fsCheck(path.join('.', 'index.html')), fsCheck(path.join('.', 'app.js')) ], '{{exercise.hello_world.success}}', '{{exercise.hello_world.fail}}', cb) } return problem } ================================================ FILE: exercises/hello_world/problem.en.md ================================================ # Hello World Let's set up a simple electron application. First, create a new empty folder and do the rest of these steps inside that new folder. Using a text editor (such as TextEdit, Notepad, etc.), create a file called `index.html` in the folder you just created with the following contents: ```

Hello World

``` Then create a file (in the same folder) called `app.js` with the following contents: ``` var electron = require('electron') electron.app.on('ready', function () { var mainWindow = new electron.BrowserWindow({width: 600, height: 800, webPreferences: { nodeIntegration: true, enableRemoteModule: true }}) mainWindow.loadURL('file://' + __dirname + '/index.html') }) ``` Finally, run `electron app.js` in your terminal. You should see an application open that displays Hello World! When you think you are done with this challenge, run `elementary-electron verify` ================================================ FILE: exercises/hello_world/problem.ja.md ================================================ # ハローワールド シンプルな electron のアプリケーションを作ってみましょう。 最初に、空のフォルダを作り、下記の手順を作ったフォルダの中で実施していきましょう。 テキストエディタ(TextEdit, Notepadなど)を使って、以下の内容の `index.html` をフォルダの中に作成してください: ```

Hello World

``` 次に、以下の内容の `app.js`というファイルを(同じフォルダ内に)作成します: ``` var electron = require('electron') electron.app.on('ready', function () { var mainWindow = new electron.BrowserWindow({width: 600, height: 800, webPreferences: { nodeIntegration: true, enableRemoteModule: true }}) mainWindow.loadURL('file://' + __dirname + '/index.html') }) ``` 最後に、ターミナルで `electron app.js` を実行してください。Hello World が表示されたアプリケーションが開いているはずです。 この課題が完了したら `elementary-electron verify` を実行してください。 ================================================ FILE: exercises/hello_world/problem.ko.md ================================================ # 헬로 월드 간단한 electron 앱을 만들어 봅시다. 먼저, 새로운 폴더를 만들고 그 폴더에서 앞으로의 작업을 진행해 주세요. 텍스트 에디터(TextEdit, Notepad 등)를 사용해서 방금 만든 폴더에 `index.html`을 만들고, 다음 내용을 작성하세요. ```

Hello World

``` 같은 폴더에 `app.js`라는 파일을 만들고 다음 내용을 작성하세요. ``` var electron = require('electron') electron.app.on('ready', function () { var mainWindow = new electron.BrowserWindow({width: 600, height: 800, webPreferences: { nodeIntegration: true, enableRemoteModule: true }}) mainWindow.loadURL('file://' + __dirname + '/index.html') }) ``` 마지막으로, `electron app.js`를 터미널에서 실행하세요. Hello World가 출력되는 앱이 보이실 겁니다. 위의 과정을 완료하셨다면 `elementary-electron verify`를 실행해주세요. ================================================ FILE: exercises/installing/exercise.js ================================================ var path = require('path') var which = require('which') var chalk = require('chalk') module.exports = function () { var problem = {} problem.requireSubmission = false problem.problem = {file: path.join(__dirname, 'problem.{lang}.md')} problem.verify = function (args, cb) { which('electron', function (err, resolvedPath) { if (err) { return cb(null, false, chalk.green('{{ee.fail}}') + ' {{exercise.installing.fail}}') } cb(null, true, chalk.green('{{ee.success}}') + ' {{exercise.installing.success}}') }) } return problem } ================================================ FILE: exercises/installing/problem.en.md ================================================ # Installing You have to install `electron` into your command line environment. Run `npm install electron -g` If you receive an EACCES error read this guide: https://docs.npmjs.com/getting-started/fixing-npm-permissions When you think you are done with this challenge, run `elementary-electron verify` ================================================ FILE: exercises/installing/problem.ja.md ================================================ # インストール まずは `electron` を、 あなたのコマンドライン環境にインストールしてみましょう。 `npm install electron -g` を実行してください。 もし `EACCES` というエラーが表示された場合は、 こちらのガイドを読んでみて下さい: https://docs.npmjs.com/getting-started/fixing-npm-permissions 完了したら `elementary-electron verify` を実行してください。 ================================================ FILE: exercises/installing/problem.ko.md ================================================ # electron 설치 먼저 `electron`을 커맨드 라인 환경에 설치해 봅시다. `npm install electron -g`를 실행해주세요. 만약 `EACCES`라는 에러가 발생한다면 다음 가이드를 읽어주세요. https://docs.npmjs.com/getting-started/fixing-npm-permissions 위의 과정을 완료하셨다면 `elementary-electron verify`를 실행해주세요. ================================================ FILE: exercises/save_pdf/exercise.js ================================================ var path = require('path') var checkAll = require('../../lib/checkAll.js') var fsCheck = require('../../lib/fsCheck.js') module.exports = function () { var problem = {} problem.requireSubmission = false problem.problem = {file: path.join(__dirname, 'problem.{lang}.md')} problem.verify = function (args, cb) { checkAll([ fsCheck(path.join('.', 'annotation.pdf')) ], '{{exercise.save_pdf.success}}', '{{exercise.save_pdf.success}}', cb) } return problem } ================================================ FILE: exercises/save_pdf/problem.en.md ================================================ # Save PDF Let's make it so when you hit the `P` key it will save a PDF of your annotations. Require a couple extra modules in your `index.js`: ``` var remote = require('electron').remote var fs = require('fs') ``` Then define a function that will save the current window to a PDF. ``` function save () { remote.getCurrentWebContents().printToPDF({ portrait: true }, function (err, data) { fs.writeFile('annotation.pdf', data, function (err) { if (err) alert('error generating pdf! ' + err.message) else alert('pdf saved!') }) }) } ``` And finally set up an event listener that will call your `save()` function when you press `P`. ``` window.addEventListener('keydown', function (e) { if (e.keyCode == 80) save() }) ``` Now if you run your app and hit `P` it should save `annotation.pdf` into your project folder. When you think you are done with this challenge, run `elementary-electron verify` ================================================ FILE: exercises/save_pdf/problem.ja.md ================================================ # Save PDF 最後に、`P` キーを押したら描画したポリゴンを PDF に保存する機能を追加しましょう。 いくつかのモジュールを `index.js` 内で読み込みます: ``` var remote = require('electron').remote var fs = require('fs') ``` 次に、現在のページを保存する function を作ります。 ``` function save () { remote.getCurrentWebContents().printToPDF({ portrait: true }, function (err, data) { fs.writeFile('annotation.pdf', data, function (err) { if (err) alert('error generating pdf! ' + err.message) else alert('pdf saved!') }) }) } ``` 最後に、`P` キーが押された際に `save()` が実行されるイベントリスナーを準備します。 ``` window.addEventListener('keydown', function (e) { if (e.keyCode == 80) save() }) ``` これで、`P` キーが押されたら `annotation.pdf` として現在のフォルダに保存されるようになりました。アプリを実行してみましょう。 この課題が完了したら `elementary-electron verify` を実行してください。 ================================================ FILE: exercises/save_pdf/problem.ko.md ================================================ # PDF 저장 `P` 키를 누르면 이제까지 그린 다각형을 PDF로 저장하는 기능을 만들어 봅시다. `index.js`에서 모듈 몇 개를 읽어 들이세요. ``` var remote = require('electron').remote var fs = require('fs') ``` 그리고 현재 창을 PDF로 저장하는 함수를 만드세요. ``` function save () { remote.getCurrentWindow().webContents.printToPDF({ portrait: true }, function (err, data) { fs.writeFile('annotation.pdf', data, function (err) { if (err) alert('error generating pdf! ' + err.message) else alert('pdf saved!') }) }) } ``` 마지막으로 `P`를 누르면 방금 만든 `save()` 함수가 실행되도록, 이벤트 리스너에 등록하세요. ``` window.addEventListener('keydown', function (e) { if (e.keyCode == 80) save() }) ``` 이제 앱을 실행해서 `P` 키를 누르면 현재 폴더에 `annotation.pdf`가 저장될 것입니다. 위의 과정을 완료하셨다면 `elementary-electron verify`를 실행해주세요. ================================================ FILE: i18n/en.json ================================================ { "ee": { "success": "SUCCESS!", "fail": "FAIL!" }, "exercise": { "cat_annotation": { "success": "", "fail": "Your app has some issues." }, "cat_picture": { "success": "Your app folder looks good.", "fail": "Your app folder is missing some things!", "cant_read": "Can not access the file", "invalid_html": "Not valid html", "missing_script_tag": "Missing script tag", "missing_body_tag": "Missing body tag", "script_not_in_body": "Script not in body" }, "hello_world": { "success": "Your app looks good.\n\nWhen you type `electron app.js` it should start the Welcome to Electron application.", "fail": "Your app has some issues." }, "installing": { "success": "Found `electron` in your PATH.", "fail": "Failed to find the command `electron` in your PATH." }, "save_pdf": { "success": "You did it!\n\nFor more Electron ideas check out https://github.com/sindresorhus/awesome-electron\nFor more workshops like this check out http://nodeschool.io\n", "fail": "Your app has some issues." } } } ================================================ FILE: i18n/ja.json ================================================ { "ee": { "success": "成功!", "fail": "失敗!" }, "exercise": { "cat_annotation": { "success": "正しく描画されたようです。", "fail": "何かがうまく行っていないようです。" }, "cat_picture": { "success": "あなたのアプリのフォルダ内は良い感じです。", "fail": "あなたのアプリのフォルダ内は、何かが足りないようです!", "cant_read": "ファイルのアクセスができないようです。", "invalid_html": "html ファイルが正しくないようです。", "missing_script_tag": "script タグが抜けているようです。", "missing_body_tag": "body タグが抜けているようです。", "script_not_in_body": "script タグが body タグの中にないようです。" }, "hello_world": { "success": "あなたのアプリは正しく動作しているようです。\n\n`electron app.js` を実行すると Electron アプリケーションの世界に入ることができるでしょう。", "fail": "あなたのアプリは正しく動作していないようです。" }, "installing": { "success": "`electron` コマンドが、あなたの PATH に追加されました!", "fail": "`electron` コマンドが、あなたの PATH に追加されていないようです。" }, "save_pdf": { "success": "完成したようですね!\n\nもっと Electron に関するアイデアを見たい方はこちらを確認してみてください: https://github.com/sindresorhus/awesome-electron\n他のワークショップを見たい方はこちらへ: http://nodeschool.io\n", "fail": "何かがうまく行っていないようです。" } } } ================================================ FILE: i18n/ko.json ================================================ { "ee": { "success": "성공!", "fail": "실패!" }, "exercise": { "cat_annotation": { "success": "성공적입니다.", "fail": "뭔가 문제가 있습니다." }, "cat_picture": { "success": "현재 앱 폴더와 폴더 내의 파일들이 정상적입니다.", "fail": "현재 앱 폴더는 뭔가가 부족합니다.", "cant_read": "파일에 접근할 수 없습니다.", "invalid_html": "html 파일에 문제가 있습니다.", "missing_script_tag": "script 태그를 찾을 수 없습니다.", "missing_body_tag": "body 태그를 찾을 수 없습니다.", "script_not_in_body": "script 태그가 body 태그 내에 존재하지 않습니다." }, "hello_world": { "success": "앱이 정상입니다.\n\n`electron app.js`를 실행하면 Electron 세계로부터의 환영 메시지가 출력될 것입니다.", "fail": "앱에 문제가 있습니다." }, "installing": { "success": "`electron` 명령어가 PATH에 추가되었습니다.", "fail": "`electron` 명령어가 PATH에 추가되어있지 않습니다." }, "save_pdf": { "success": "잘하셨어요!\n\nElectron에 관해 더 알고 싶으신 분은 여길 참조하세요. https://github.com/sindresorhus/awesome-electron\n다른 워크숍에 관한 정보는 여길 참조하세요. http://nodeschool.io\n", "fail": "앱에 문제가 있습니다." } } } ================================================ FILE: index.js ================================================ #!/usr/bin/env node var elementaryElectron = require('workshopper-adventure')({ appDir: __dirname, languages: ['en', 'ja', 'ko'] }) elementaryElectron.addAll([ 'Installing', 'Hello World', 'Cat Picture', 'Cat Annotation', 'Save PDF' ]) module.exports = elementaryElectron ================================================ FILE: lib/checkAll.js ================================================ var chalk = require('chalk') module.exports = function (checks, success, error, cb) { var messages = ['Checking Requirements:'] var total = checks.length var ok = 0 messages.push('') for (var i = 0; i < checks.length; i++) { var check = checks[i] ok += check(messages) } messages.push('') if (ok === total) { messages.push(chalk.green('{{ee.success}}') + '\n\n' + success) } else { messages.push(chalk.red('{{ee.fail}}') + '\n\n' + error) } messages.push('') cb(null, ok === total, messages.join('\n')) } ================================================ FILE: lib/fsCheck.js ================================================ var chalk = require('chalk') var path = require('path') var fs = require('fs') module.exports = function appendFileCheck (file) { return function (messages) { try { fs.statSync(path.join(process.cwd(), file)) } catch (err) { messages.push(' - ' + chalk.red(file) + ' [?]') return 0 } messages.push(' - ' + chalk.green(file) + ' ✔') return 1 } } ================================================ FILE: lib/pkgDependencyCheck.js ================================================ var chalk = require('chalk') var path = require('path') module.exports = function appendDependencyCheck (pkgName) { return function (messages) { try { var pkg = require(path.join(process.cwd(), 'package.json')) } catch (e) { messages.push(chalk.red(' - No package.json!!!')) return 0 } if (Object.keys(pkg.dependencies).indexOf(pkgName) === -1) { messages.push(' - Dependency in package.json: ' + chalk.red(pkgName) + ' [?]') return 0 } messages.push(' - Dependency in package.json: ' + chalk.green(pkgName) + ' ✔') return 1 } } ================================================ FILE: package.json ================================================ { "name": "elementary-electron", "version": "1.5.2", "description": "nodeschool workshop to learn electron", "main": "index.js", "bin": { "elementary-electron": "bin/elementary-electron" }, "scripts": { "test": "standard" }, "keywords": [ "nodeschool", "workshopper", "adventure", "tutorial", "electron" ], "contributors": [ "Max Ogden (https://github.com/maxogden)", "freeman-lab (https://github.com/freeman-lab)" ], "author": "Max Ogden", "license": "ISC", "dependencies": { "chalk": "^1.1.1", "cheerio": "^0.20.0", "which": "^1.2.4", "workshopper-adventure": "^5.1.8" }, "devDependencies": { "standard": "^8.0.0" }, "repository": { "type": "git", "url": "git+https://github.com/maxogden/elementary-electron.git" }, "bugs": { "url": "https://github.com/maxogden/elementary-electron/issues" }, "homepage": "https://github.com/maxogden/elementary-electron#readme" } ================================================ FILE: readme.md ================================================ # Elementary Electron A nodeschool workshop that teaches electron. Please open issues to propose new exercises if you have some cool ideas. Run `npm install elementary-electron -g`, and then `elementary-electron` to start. ![](cool-app.png)