投稿時間:2021-12-09 00:34:49 RSSフィード2021-12-09 00:00 分まとめ(46件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
IT 気になる、記になる… フォーカルポイント、「楽天スーパーSALE」で対象製品を最大70%オフで販売するウィンタースペシャルセールを開催中 https://taisy0.com/2021/12/08/149541.html almighty 2021-12-08 14:24:11
IT 気になる、記になる… Microsoft、デザインを刷新した「Windows 11」向けの「メモ帳」アプリを発表 − Devチャネル向けに展開開始 https://taisy0.com/2021/12/08/149538.html microsoft 2021-12-08 14:09:35
ROBOT ロボスタ 掃除しながら万引き抑止も 清掃・警備・案内の3機能を持つ複合型サービスロボットオムロン「Toritoss」 https://robotstart.info/2021/12/08/moriyama_mikata-no141.html toritoss 2021-12-08 14:45:53
python Pythonタグが付けられた新着投稿 - Qiita python+opencvで画像処理の勉強3 領域に基づく濃淡変換(空間フィルタリング) https://qiita.com/tanaka_benkyo/items/2b4460f1cc0ed6a685eb この処理は以下のようにつのフィルタで表すことができて、これをラプラシアンフィルタと呼びます。 2021-12-08 23:44:47
python Pythonタグが付けられた新着投稿 - Qiita 数値流体力学7~時間陽解法~ https://qiita.com/vardia/items/7a72953183f065a7dd8c qnjqnjfracDeltatDeltaxBigtildefnjtildefnjBigtagこの空間微分項をRjと書くことで、qnjqnjDeltatRjqntagこの式のように、Rjがすべて時間ステップnで評価され、離散化式全体で時間ステップnの項が一つしかない時間積分法を時間陽解法といいます。 2021-12-08 23:21:29
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) webブラウザの操作について https://teratail.com/questions/372925?rss=all VBAによるIE操作で、これを自動化して利用してきたのですがIEが今後利用できなくなるということで別の方法をご存じの方がおりましたら、ご教示いただきたくご質問させていただきました。 2021-12-08 23:32:33
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) Storage link は貼られているが読み込めない #vscode #laravel https://teratail.com/questions/372924?rss=all Storagelinkは貼られているが読み込めないvscodelaravelstoragenbsplinkは貼っているのですがpublic下のstorageをクリックするとこちらが出てきます。 2021-12-08 23:12:18
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) PythonのDGLのグラフ分類でエッジの特徴量を利用する方法について https://teratail.com/questions/372923?rss=all PythonのDGLのグラフ分類でエッジの特徴量を利用する方法について前提・実現したいことグラフのエッジの特徴量を学習に利用するにはどのようなネットワークの設定にすればいいか教えてほしいです。 2021-12-08 23:03:11
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) GASのエラーの解決方法について https://teratail.com/questions/372922?rss=all GASのエラーの解決方法について前提・実現したいことここに質問の内容を詳しく書いてください。 2021-12-08 23:02:39
Linux Ubuntuタグが付けられた新着投稿 - Qiita Dockerでrootとuserを切り替えてコンテナに入る https://qiita.com/Nahuel/items/d11d169ba7c40b413e6b 2021-12-08 23:59:33
AWS AWSタグが付けられた新着投稿 - Qiita AWSにおけるterraform管理の勘所 https://qiita.com/instant_baby/items/74a6e7ca860a3f00c2f1 全部terraaformで管理する必然性があるのであれば致し方なしですが、このつはコードを作成するその時間に対してGUIでの作業量が非常に少ないのでこれらはterraformで管理するか否かの線引がいるかなと感じています。 2021-12-08 23:37:03
AWS AWSタグが付けられた新着投稿 - Qiita Amazon RDS Custom for Oracle作成の手引き(その3:RDS Customの作成) https://qiita.com/asahide/items/caa50bfe9b3c4eb09207 ストレージがioかgpか、と、削除保護が有効になっているかどうか、の二点DBインスタンス識別子認証情報マスターユーザ名パスワード、RDSの時には重要でしたが、RDSCustomですとOSにrootログインできるため、assysdba接続も可能となり、あまり重要ではなくなりましたDBインスタンスクラスm、rインスタンスのlargeVCPUxlargeVCPUが選択可能ストレージgp、ioが選択可能ストレージ割当GiBGiBプロビジョンドIOPSioのみ選択可能、IOPSIOPSVirtualPrivateCloud作成する対象のVPCを選択サブネットグループ事前に作成してあるサブネットグループが選択可能パブリックアクセスVPC外部から接続したい場合には「あり」だが、そうでない場合には「なし」になるVPCセキュリティグループ既存のセキュリティグループを利用するか、新規に作成するか既存のVPCセキュリティグループRDSに適用したいセキュリティグループを選択するアベイラビリティゾーンサブネットグループに入っているAZが選択可能データベースポートDBへ接続するためのポート、デフォルトはだが後でも変更可能インスタンスプロファイルAWSRDSCustomで始まる必要がある、事前準備にて作成済AWSKMSキーインスタンスストレージ等の暗号化キー、CEV作成時のキーと同じである必要はないRDSカスタムオートメーションモード「完全なオートメーションモード」のみが選択可能最初のデータベース名DB名バックアップ保持期間通常のRDSと同様、日で設定可能ですバックアップウィンドウ選択ウィンドウにすると、バックアップウィンドウを設定できますメンテナンスウィンドウ選択ウィンドウにすると、メンテナンスウィンドウを設定できます、Customでは基本的にはユーザ側でメンテナンスを選択できるため、大きな意味はないと認識してます削除保護「削除保護の有効化」チェックボックスをオンにすると、削除保護がEnableになります作成されたRDSCustomforOracle上記の手順を実施すると、画面がダッシュボードに切り替わり、該当のデータベースが「作成中」となります。 2021-12-08 23:06:59
Docker dockerタグが付けられた新着投稿 - Qiita Dockerでrootとuserを切り替えてコンテナに入る https://qiita.com/Nahuel/items/d11d169ba7c40b413e6b 2021-12-08 23:59:33
Git Gitタグが付けられた新着投稿 - Qiita よく使うgitコマンドまとめ https://qiita.com/mmaumtjgj/items/7867da95ca14e686a106 gitpulloriginブランチ名リモートブランチの変更を取り込むために使うコマンド。 2021-12-08 23:40:42
技術ブログ Developers.IO Kinesis Data FirehoseのJSON形式のレコードをJSON Lines形式に変換して出力する(Node.js) https://dev.classmethod.jp/articles/convert-records-in-json-format-from-kinesis-data-firehose-to-json-lines-format-and-output-them-nodejs/ amazonkinesisdatafirehose 2021-12-08 14:55:25
技術ブログ Developers.IO [セッションレポート] グラフデータベースAmazon Neptuneの事例紹介~LexisNexis社~ #reinvent #DAT202 https://dev.classmethod.jp/articles/real-world-use-cases-with-graph-databases/ amazonneptune 2021-12-08 14:20:15
海外TECH MakeUseOf How to Manage Your Notifications on GOG Galaxy https://www.makeuseof.com/how-to-manage-gog-galaxy-notifications/ galaxy 2021-12-08 14:47:04
海外TECH MakeUseOf Travel Photography: 6 Tips to Take Better Photos While Abroad https://www.makeuseof.com/travel-photography-tips-better-photos-abroad/ Travel Photography Tips to Take Better Photos While AbroadThere s more to travel photography than just snapping popular sites We re going to give you some tips for your next shoot abroad 2021-12-08 14:30:12
海外TECH MakeUseOf How to Make a Web Directory in WordPress https://www.makeuseof.com/make-web-directory-wordpress/ wordpress 2021-12-08 14:15:12
海外TECH DEV Community How we build an open source app for animal shelters https://dev.to/azisk/how-we-build-an-open-source-app-for-animal-shelters-91e How we build an open source app for animal sheltersHi we have been building an open source application for animal shelters for the past year and we have found great value in GitHub Actions The application has separate Back end and Front end repos and they both utilise GitHub Actions notably The application had been started as part of Kayak WeCanCode Academy event in Kaunas to teach the local community in Lithuania to code and at the same time create software for the common good This software for animal shelters is meant to help document homeless and already in shelter animals as well as to ease the adoption of these animals Lately both repositories have been losing traction since summer resulting in only very few developers that also barely find time to build this great software However I hope that winning a prize in this event will bring back the enthusiasm to continue building it My WorkflowWhen we started this work we thought we would have it built long ago Like with all software estimation right However this open source application still needs some work to reach the minimum viable product MVP stage and I will guide it until it actually reaches the MVP and then we can hand it out to shelters to be tested and gather the feedback When we started these repositories I had had never used GitHub Actions and even now they seem to be shockingly useful Both Back end and Front end repos use GitHub Actions to test and to deploy the code I mostly worked on the Back end repo thus I will mostly share my excitement in Back end repo using GitHub Actions Unabashed I am proud of our decision to always nuke and redeploy the database on deployment to simplify the database changes This allows us to have the same structure database across local dev prod environments as well as local database within GitHub Actions Only the entries can differ the database description language DDL stays the same and it is all described in SQL file I must mention that we chose to always redeploy the database to ease the development and have all DDL in one file without any migration amendments but this is definitely not safe for a working application We are using this path only until we reach the MVP Later on we would not like to redeploy the database and lose all the production entries that users have already entered To this I would like to add that I am also extremely proud of our approach to Dockerize this Back end application together with a PostgreSQL database This allows us to spin up the very same code application with a local database within GitHub Actions It makes sure our tests run on the newest and robust code and database changes when making a pull request To sum up it ensures the very same database and code across all environments local dev prod and even a local one in GitHub Actions Docker containers I am very fond of the GitHub Actions that allow to spin up Docker containers together with a database It is also tremendous to see the caching of libraries inside GitHub Actions Furthermore both repos use Github Actions to deploy and to test the code Back end repo deploys to Heroku while Front end repo deploys to GitHub Pages All Back end workflows can be found here All Front end workflows can be found here Submission Category Maintainer Must Haves DIY Deployments YAML files and RepositoriesBack End deployment to Heroku name Syncon schedule cron UTC time GMT workflow dispatch jobs repo sync runs on ubuntu latest steps uses actions checkout v with persist credentials false name repo sync uses repo sync github sync v with source repo source branch main destination branch prod github token secrets GITHUB TOKEN deploy heroku runs on ubuntu latest needs repo sync steps name Trigger heroku deploy prod uses benc uk workflow dispatch v with workflow Deploy Heroku prod ref prod token secrets PERSONAL TOKEN deploy database runs on ubuntu latest needs repo sync steps name Trigger database deploy prod uses benc uk workflow dispatch v with workflow Nuke amp Redeploy Database prod ref prod token secrets PERSONAL TOKEN Back end pull request testing and linting name Pull request checkson pull requestjobs integration tests name Integration Tests runs on ubuntu latest steps uses actions checkout v name Copying test env file uses canastro copy file action master with source github workflows test database env target database env name Creating common env file uses canastro copy file action master with source github workflows test common env target common env run docker compose pull name Pulling pull only docker images uses satackey action docker layer caching v name Caching docker image continue on error true run docker compose up build d name Building containers name Waiting for backend uses nevn wait for response v with url http localhost status responseCode timeout interval name Running tests run docker exec pets back gis backend npm run test name Dump api logs uses jwalton gh docker logs v if failure lint name Lint runs on ubuntu latest steps uses actions checkout v name Setting up node module cache id node modules uses actions cache v with path node modules key hashFiles package json node modules name Installing node modules if steps node modules outputs cache hit true run npm install name Running lint run npm run check lintBack end Repo pets oss pets back Pet Information System Back end Pet Information System Back EndProduction endpoint Development endpoint Interactive API dev environment only Development guide contentsA PrerequisitesB SetupB with Docker recommended B without DockerC DebugD TestE Log DB queriesF Obtaining Cloudinary API keyG Common issuesA PrerequisitesNodeJS gt v IDE is up to your preference but VS Code is recommended only if running with docker Docker Docker Compose B Setup with docker recommended Install npm libraries with npm install command if not installed previously Copy and rename database env sample to database env POSTGRES USER POSTGRES PASSWORD POSTGRES DB can be adjusted to your liking but the default configuration will work as well Copy and rename common env sample to common envCreate a cloudinary account and replace the CLOUDINARY URL variableorSet CLOUDINARY DISABLED trueMake sure Docker is running Run docker compose up dB Setup without dockerDownload the latest… View on GitHubFront end deployment to GitHub Pages name Github pageson push branches mainjobs install name Install with Cache setup runs on ubuntu latest steps uses actions checkout v name Setup Node uses actions setup node v with node version x name Get yarn cache id yarn cache run echo set output name dir yarn cache dir name Cache dependencies uses actions cache v with path steps yarn cache outputs dir key runner os yarn hashFiles yarn lock restore keys runner os yarn run yarn no progress non interactive uses actions cache v id cache build with path key github sha testUnit name Test Unit runs on ubuntu latest needs install steps uses actions cache v id restore install with path key github sha run yarn test lint runs on ubuntu latest needs install steps uses actions cache v id restore install with path key github sha run yarn lint testsPass name Thank you runs on ubuntu latest needs testUnit lint steps run exit publishRelease name Build and publish release runs on ubuntu latest needs testsPass environment github pages env REACT APP GRAPHQL URL secrets REACT APP GRAPHQL URL REACT APP AUTH DOMAIN secrets REACT APP AUTH DOMAIN REACT APP AUTH CLIENT ID secrets REACT APP AUTH CLIENT ID REACT APP AUTH AUTH AUDIENCE secrets REACT APP AUTH AUTH AUDIENCE steps uses actions cache v id restore install with path key github sha run yarn build name Deploy uses peaceiris actions gh pages v with github token secrets GITHUB TOKEN publish dir build cname app petbook ltFront end pull request testing and linting name integrate on pull requestjobs test pull request runs on ubuntu latest steps uses actions checkout v run yarn no progress non interactive run yarn run lint run yarn run test run yarn run buildFront end Repo pets oss pets front Pets Information System Front end pets frontPets Information System Front endLive site is available at SetupBefore starting the setup choose what actions you will do with the code changes If you will keep it as a local copy make a repository clone If you will contribute to the project make a repository fork and read the Contribution guideline The project codebase is optimized for using Visual Studio Code which can be downloaded and used with the most of popular OS Install Prettier and ESLint extensions as these are mandatory for project codebase consistency Get your local copy of the repository by cloning or forking If not yet installed get Node JS gt v and npm Run node v in your terminal to check the actual Node version If you need to be able using various Node versions for your projects consider installing and using Node version manager… View on GitHub Additional Resources InfoBoth Back end and Front end repos are used by this still in development application We built and are still building this software as a team and I would like to thank and mention all the epic contributors 2021-12-08 14:49:43
海外TECH DEV Community Being a Tech Lead https://dev.to/trikoder/being-a-tech-lead-4l9 Being a Tech LeadI ve been the tech lead of my team at Trikoder for just over a year now days but who s counting I think this is a good time to look back at what this role means to me the things I ve learned and mistakes I made My backgroundEver since I started programming back in I sort of have known that “writing code and solving problems with software is the thing I ll do As I grew older and more experienced I ve slowly come to realize that well writing software is only one part of the equation and there s a bit more to it Turns out the “people stuff is quite important and necessary even when dealing with computers all day Joining TrikoderIn the summer of I joined Trikoder as an external contributor on the Njuskalo hr platform As part of the Common Base Technology CBT team I ve took part in work that enabled us to internationalize the Njuskalo hr platform and launch bolha com on the same code as well as undertook some bigger refactors and rewrites to lessen the burden of technical debt and legacy code on other teams We still have a lot of work ahead of us as plus years of shipping fast tends to leave a lot of “baggage behind What do I do as a tech lead I ve been the tech lead of this small team for the past year and mostly through trail and error I ve been figuring out what does this role expect from me I have good support both from my team my team lead and from the company in general so it s been a great learning experience so far A thing I learned over the years is that one of the reasons “legacy code happens is due to a communication breakdown between the business people that need the software to solve a particular problem and the software people that write the software This is why I believe the position of a tech lead is a unique one We can help the business understand why delivering new features takes as long as it takes or why is it necessary to do some seemingly unrelated code maintenance But communication is a two way street so we also need to ensure that the developers can understand the business side of things how it s not financially viable to halt producing new features for several months to rewrite that ugly piece of code someone else wrote or how this project might not be the best place to try out the latest and shiniest new technology I see my main role as a tech lead to be a bridge in the communication between business and development Through regular communication with the other teams I try to understand what parts of the platform should we focus on next when it comes to dealing with technical debt and legacy code Then together with the leader of my team we try to come up with a strategy and goals that will get us buy in from the business Within the team itself I do my best to guide the team towards good technical and technological choices To make sure the code we write and don t write is the best it can be under the current circumstances that it s aligned with both the needs of the business as well as with the overall architecture While I love nothing more than getting “into the zone and delivering code I ve come to realize that that part of the job is gone I ve seen this mistake made by other tech leads and then sadly made it myself As a tech lead I can t let myself focus too much on any single problem because then I don t see what else is going on in my team I might miss out on an important decision being made or someone might decide to not reach out to me for advice as they don t want to disturb me I see myself now as an enabler ーmy work is to enable the other programmers on my team to shine Enable them to learn to grow to get into the zone to make an impact Even enable them to fail And this is where I think I ve come full circle as a programmer When I was starting out I was always volunteering for the tasks that no one else wanted the boring tasks the non important but still have to be done tasks I ve started to pick up those tasks again so that my team can focus on the important things Self retrospectives are weirdAm I doing it right I think so It feels right I ll probably make a few more mistakes along the way but that s how we learn I ve been fighting this direction of my career for a long time as I didn t want to bother with “management Now that I see and understand what the position of a tech lead brings to the table I m going all in Until next time take care my friend 2021-12-08 14:44:30
海外TECH DEV Community Lenra's automatic management of dependencies https://dev.to/lenradevelopers/lenras-automatic-management-of-dependencies-i28 Lenra x s automatic management of dependencies My WorkflowHow do you manage with all versions of your dependencies between your huge projects My answer here What really is the issue At Lenra we have several Git projects that often require modifying the link versions in the dependency files But doing it manually slows down the release process and wastes too much time for our development teams who can t focus on the features The solution was to develop some GitHub Actions in a workflow executed at each release of a new version of a dependency to modify the file that links to it in each project using it How it works Define the shape of your projectsWe will start by presenting our Git projects in the following form for some evident purposes of dependencies Repo A gt Repo B Repo CRepo B gt Repo CAs you can see in the example directory we have Git repositories that depend on each other In our example repository B needs repository A to compile And as it is quite tedious to always have to manually edit the right dependency files this action will take care of it if it is well configured If we continue our exploration the C repository also requires the A repository in addition to the B repository Projects of a certain size can have pretty complex mesh links which can be a source of errors Understanding links between each workflowWhen you publish a new release on the repository A this action will automatically create a Pull Request on the repository B and C to update the correct files and change its own link in dependancy file s And now when you merge the PR on the repository B and create a new release it will update the PR on the repository C to add this changes Now we can accept changes on the repository C to update its version of A and B How to use it Using the previous example you need to trigger the action on the source repository I ll name it github workflows on release yml This file must call the Action that will populate the release on the requested repositories To do it we need to define this step in your job name create pr uses lenra io create or update pr action utils trigger workflow v with target ref steps extract tag outputs target ref target repository github repository owner repo B github repository owner repo C target workflow create or update pr yml params version steps get version outputs tag origin repo a release notes steps get version outputs release notes token secrets WORKFLOW GITHUB TOKEN I use a custom GitHub Token because action running the default GitHub secret secrets GITHUB TOKEN can t trigger any other workflow so that won t make things appends As you can see this step will trigger a custom workflow defined in another repository chooses from target repository target ref and target workflow And you can customize some information during this execution as parameters using the params field you can add everything you need on the remote execution but that need to fit the input declaration This workflow must be run on each release so be sure that you ll use the following declaration at the top of the file on release types published Now this first step is defined you need to create the remote workflow to receive this event and update the file you need So I ll call this new file github workflows create or update pr yml on the remote repository name create pr uses lenra io create or update pr action v with name Update dependencies token secrets WORKFLOW GITHUB TOKEN script steps setup yq outputs yq binary eval dependencies github event inputs origin git ref github event inputs version i project yaml git add project yaml RELEASE NOTES github event inputs release notes RELEASE TYPE RELEASE NOTES git commit m RELEASE TYPE Upgrade github event inputs origin to github event inputs version RELEASE NOTES On this step you need to use the create or update pr GitHub Action we ve already defined and make the change you want on the script field Don t forget to commit it but you didn t need to push it the action will do anything else for you Here I update the yaml file and change the dependency version using the yq command And that all you can now focus on your work Go deeperThis can be awesome to use in your projects with sementic release to make releases even faster and erase errors of dependency managements Of course you can ask for new features on the GitHub Action repository or contribute yourself by submitting a new pull request Now you can test it by publishing theses repositories on your own account organization to see how it works Don t forget to create the WORKFLOW GITHUB TOKEN secret in the settings of each repository Submission Category Maintainer Must Haves Yaml File or Link to Code lenra io create or update pr action A simple but powerful GitHub Action to link workflows and manage dependencies between projects actionshackathon Create or update PR ActionA simple but powerful GitHub Action to link workflows and manage dependencies between projects Usage To learn accurately how to use it you must see the guide hereQuick Example Call Create or update PR GitHub action name create pr uses lenra io create or update pr action v with The name of the PR to be created name Update dependecies The token used to create the PR I didn t use the secrets GITHUB TOKEN here because this token can t trigger workflow event if we push something or create a PR token secrets WORKFLOW GITHUB TOKEN Write a little script called just before the PR creation or update This example will upgrade the version inside of the pubspec yaml and publish it in a new PR script Update the requested dependency version in the pubspec yaml file steps setup yq outputs yq binary eval… View on GitHub Additional Resources InfoAny needed resources is in the GitHub repository of the action you can use it from the GitHub Marketplace and any contribution are welcome This project is under MIT Licence Collaborators Lenra team 2021-12-08 14:37:32
海外TECH DEV Community Create Hello World Discord Bot with discord.js https://dev.to/kojikanao/create-hello-world-discord-bot-with-discordjs-56dn Create Hello World Discord Bot with discord jsA couple of days ago I created a new Discord server This is the first time to create it to communicate with school alumni I just tested discord js since I may need to create a bot for the Discord server to do something In this post I will show you how to create a Hello World bot that I post hello and a bot replies world to a channel Discord developer portal discord js Step Setup a botdiscordpy has a good page for this step Step Create a project discord js requires node yarn init y if you use npm npm init yinstall packagesIf you would like to use js skip yarn add D npm install D In addition dotenv is optional If you want to test discord js quickly you won t need to install dotenv and you will need to hardcode the Token yarn add discord js dotenv yarn add D typescript ts node for npm npm install discord js dotenv npm install D typescript ts node Step Write a hello world botif you use js you need to use require instead of import envTOKEN xxxxxxx your token xxxxxxxxximport DiscordJS Intents from discord js import dotenv from dotenv dotenv config const client new DiscordJS Client intents Intents FLAGS GUILDS Intents FLAGS GUILD MESSAGES console log Starting client on ready gt console log the bot is online client on messageCreate message gt console log messageCreate get author info const authorId message author id const authorName message author username console log author authorName if message content hello message reply content world client login process env TOKEN Step Try a botrun the bot ts node index ts if you use js node index jsPost something to a channel If you post hello the bot replies world At the same time you can see your account name and your account id in your terminal 2021-12-08 14:25:40
海外TECH DEV Community How to Create a Dark Mode Component in React https://dev.to/alexeagleson/how-to-create-a-dark-mode-component-in-react-3ibg How to Create a Dark Mode Component in ReactAll code from this tutorial is available in this repository Table of ContentsLive DemoPrerequisitesInitialize the ProjectAdding StylesAdding the Toggle ButtonCreating the DarkMode ComponentAdding Tests Optional Adding DarkMode to the AppSetting Preferred Colour SchemeWrapping UpProviding users with a dark mode for your web application has become an expectation and there are many ways to accomplish it Typically this is most efficiently done by taking advantage of the power of CSS variables In this tutorial we are going to show how to bundle the entire dark mode feature into a single lt DarkMode gt component that you can take with you and place inside any application This component will not only persist your choice of settings through a page close or refresh it will also respect the user s prefers color scheme setting in their browser Pretty cool So let s dive into it Live DemoBefore we start we ll begin by taking a look a demo of the final product so you know what to expect from this tutorial Once you have completed it you will have your own lt DarkMode gt component that you can drop into any application to achieve this functionality PrerequisitesI ll presume that you have a basic familiarity with React You do not need to be an expert In fact we don t have a single stateful variable or any hooks or lifecycle methods The goal here as it should always be is to minimize complexity We don t need them for this feature We will be using Create React App for this tutorial as it is an extremely easy way to quickly and easy establish a React application template that you can build on If you choose not to use CRA you should still be able to follow along with this tutorial We will be writing pure CSS but in order to copy the examples exactly you would need to have webpack setup with a CSS loader to support the import syntax for CSS files If you are not using webpack you can simply use a lt link gt element for your CSS files in your index html rather than importing them We will also be using Typescript as is the default for every web project I built these days If you are not super familiar with Typescript you should still be able to follow along thee amount of explicit typing in these examples is minimal Lastly I have included a section on adding tests for your component using React Testing Library This section is optional Initialize the ProjectIf you are using CRA then run the following command if you have your own existing project then disregard npx create react app dark mode example template typescript Adding StylesWhen the application loads it will determine the dark light setting in the following order of priority User s previous toggle settingUser s browser preferencesLight modeWe ll begin by creating the CSS that handles dark mode src DarkMode css root font color background color eee link color cornflowerblue data theme dark font color eee background color link color lightblue body background color var background color color var font color a color var link color The root selector matches the root element representing the DOM tree Anything you place here will be available anywhere in the application This is where will will create the CSS variables that hold the colours for our light theme Here we set the colours for our dark theme Using the attribute selector we target any element with a data theme dark attribute on it This is a custom attribute that we will be placing ourselves on the lt html gt element We set the background colour and text color of our application This will always be the value of the background color and font color variables The value of those variables will change depending on when the data theme dark attribute is set due to the cascade The dark values are set after the root values so if the selector applies the initial light value of those variables will be overwritten with the dark values Notice I have also added a custom link colour here which changes based on the value of the theme You can add as many custom colours as you want here and have them all be controlled by your light dark toggle Try adding some more yourself Adding the Toggle ButtonNext we will create a custom checkbox input to look like a toggle switch based on this example I won t comment on how this CSS works as it s not in the scope of this tutorial and not relevant to dark light mode The styles below are simply to override the look of the default HTML checkbox Add them below the above code in src DarkMode csssrc DarkMode css Custom Dark Mode Toggle Element toggle theme wrapper display flex flex direction row align items center gap px toggle theme wrapper span font size px toggle theme position relative display inline block height px width px toggle theme input display none slider background color ccc position absolute cursor pointer bottom left right top transition s slider before background color fff bottom px content height px left px position absolute transition s width px input checked slider before transform translateX px input checked slider background color cornflowerblue slider round border radius px slider round before border radius Creating the DarkMode ComponentNow we will create our DarkMode component To start we are just going to focus on the structure of the component itself no events or functions src DarkMode tsximport DarkMode css const DarkMode gt return lt div className toggle theme wrapper gt lt span gt ️ lt span gt lt label className toggle theme htmlFor checkbox gt lt input type checkbox id checkbox gt lt div className slider round gt lt div gt lt label gt lt span gt lt span gt lt div gt export default DarkMode The lt input gt element will be handling the state of our colour theme When it is checked then dark mode is active when it is not checked then light mode is active If you render this component you should have a nice looking custom toggle button without any functionality To make our toggle switch work we have to attack some Javascript functions to the onChange event of the input that fires when the checkbox is toggled We also need to decide which mode we are going to show by default when the page or application is first loaded There is a lot to unpack here there will be explanations for what is happening with the numbered comments below the example src DarkMode tsximport DarkMode css import ChangeEventHandler from react const setDark gt localStorage setItem theme dark document documentElement setAttribute data theme dark const setLight gt localStorage setItem theme light document documentElement setAttribute data theme light const storedTheme localStorage getItem theme const prefersDark window matchMedia amp amp window matchMedia prefers color scheme dark matches const defaultDark storedTheme dark storedTheme null amp amp prefersDark if defaultDark setDark const toggleTheme ChangeEventHandler lt HTMLInputElement gt e gt if e target checked setDark else setLight const DarkMode gt return lt div className toggle theme wrapper gt lt span gt ️ lt span gt lt label className toggle theme htmlFor checkbox gt lt input type checkbox id checkbox onChange toggleTheme defaultChecked defaultDark gt lt div className slider round gt lt div gt lt label gt lt span gt lt span gt lt div gt export default DarkMode We create functions called setDark and setLight which do exactly what the names describe We want these to be as simple as possible When we invoke them we expect the app to switch to either light or dark mode This is how we handle persistance Using localStorage will allow us to save a value and have it persist even after the user closes the app or reloads the page Every time light or dark mode is set we save that value in the theme property of localStorage This is where we set the data theme dark or light value on the lt html gt DOM element This is what actually updates the colours in our app When that attribute is added then the data theme dark selector from our CSS becomes active and the dark colour variables are set and vice versa The section under comment is where the initial state is established when the page is loaded before the actual toggle switch has been used storedTheme gets the value from localStorage if it exists prefersDark checks a media query for the user s browser settings for prefers color scheme Lastly defaultDark is meant to check both of those and decide whether to default to dark mode based on the rules of priority we established at the beginning of this tutorial If it evaluates to true we set the app to dark mode before the component even renders Note the reason we can do this is we are targeting the lt html gt attribute which will already exist This is the event handler function we have written to capture the change event that occurs when a user clicks the checkbox If the box is checked we enable dark mode otherwise light mode We place the event handler we just created onto the onChange attribute so it fires every time the checkbox changes We also use the defaultDark boolean value we established to determine if the checkbox is enabled by default Adding Tests Optional Before we add this component to our app we can write a few tests to ensure it works as we expect it to Create React App comes prepackaged with React Testing Library It will automatically pick up any test tsx files you create src DarkMode test tsximport React from react import render screen fireEvent from testing library react import DarkMode from DarkMode test renders dark mode component gt render lt DarkMode gt const inputElement screen getByRole checkbox as HTMLInputElement expect inputElement toBeInTheDocument test toggles dark mode gt render lt DarkMode gt const inputElement screen getByRole checkbox as HTMLInputElement expect inputElement checked toEqual false fireEvent click inputElement expect inputElement checked toEqual true expect document documentElement getAttribute data theme toBe dark A simple test to ensure the component renders The input has a role of checkbox so we would expect to be able to find the element by that role A test to ensure that the component actually activates dark mode when the checkbox is toggledUse testing library s fireEvent function we can simulate a click on our input We assert before clicking that it should not be checked then after clicking it should be checked This component by design does have side effects and that s what this final assertion is aiming to detect Although the component is only a small container for an input it is designed to apply the data theme attribute to the root lt html gt element That element can be accessed directly with the Javascript variable document documentElement We check here that the dark value is applied to the attribute after the element is clicked If using the default CRA setup or you have custom configured it to do so we can run our tests with npm run testAnd get our results Adding DarkMode to the AppBelow I have simply imported and added lt DarkMode gt to the default App template created when you run Create React App src App tsximport React from react import logo from logo svg import App css import DarkMode from DarkMode function App return lt div className App gt lt header className App header gt lt DarkMode gt lt img src logo className App logo alt logo gt lt p gt Edit lt code gt src App tsx lt code gt and save to reload lt p gt lt a className App link href target blank rel noopener noreferrer gt Learn React lt a gt lt header gt lt div gt export default App Lastly we need to update the default CSS included with the CRA setup otherwise some of the color background color values will overwrite our theme variables The below example is the default version of App css with the color values commented out You can delete them entirely if you like src App css App text align center App logo height vmin pointer events none media prefers reduced motion no preference App logo animation App logo spin infinite s linear App header background color c min height vh display flex flex direction column align items center justify content center font size calc px vmin color white App link color dafb keyframes App logo spin from transform rotate deg to transform rotate deg If you followed along with everything you ll be treated to a very function app with your own custom lt DarkMode gt component Setting Preferred Colour SchemeWe mentioned that this app supports the user s browser configuration for preferred colour scheme but we didn t actually explain how you can set that value Unfortunately browsers do not make it easy but it can be achieved with the following steps in either Chrome or Firefox FirefoxType about config into your navigation barIf it doesn t already exist create a value called ui systemUsesDarkTheme and set it as a NumberSe the number as for dark or for light ChromeOpen developer tools F Click the ellipsis icon at the upper right of the toolsClick More Tools gt RenderingUnder Emulate CSS Media select prefers color scheme dark Chrome is a bit trickier so here is a screenshot showing where to find it Wrapping UpI hope you enjoyed this tutorial and learned something from it You might have picked up on the fact that although this was written from a React perspective nearly all the code we are working with would work just as well independently of React Try it yourself the next time you are working with vanilla HTML CSS or even a different framework You ll find that this code can be reused anywhere with very few modifications needed Please check some of my other learning tutorials Feel free to leave a comment or question and share with others if you find any of them helpful How to Analyze and Improve your Create React App Production Build How to Create and Publish a React Component LibraryHow to use IndexedDB to Store Local Data for your Web App Running a Local Web ServerESLintPrettierBabelReact amp JSXWebpack The BasicsWebpack Loaders Optimizations amp Bundle AnalysisFor more tutorials like this follow me eagleson alex on Twitter 2021-12-08 14:21:35
Apple AppleInsider - Frontpage News Best deals Dec. 8: $299 iPad Pro Magic Keyboard in white, $999 M1 MacBook Pro, more! https://appleinsider.com/articles/21/12/08/best-deals-dec-8-299-ipad-pro-magic-keyboard-in-white-999-m1-macbook-pro-more?utm_medium=rss Best deals Dec iPad Pro Magic Keyboard in white M MacBook Pro more Wednesday s best deals include big Netgear router discounts off a Samsung K monitor off a Sabrent TB M SSD and Sony XM true wireless earbuds Best deals for December The internet has a plethora of deals each day but many deals aren t worth pursuing In an effort to help you sift through the chaos we ve hand curated some of the best deals we could find on Apple products tech accessories and other items for the AppleInsider audience Read more 2021-12-08 14:44:11
Apple AppleInsider - Frontpage News The best notes apps for iPhone and iPad https://appleinsider.com/articles/21/12/08/the-best-notes-apps-for-iphone-and-ipad?utm_medium=rss The best notes apps for iPhone and iPadWhether you need to jot down a phone number figure out your shopping list or capture crucial meeting details a notes or note taking app can keep you on track Apple NotesAll of the apps listed here are more than good at the most important parts of the job They let you start a new note extremely quickly meaning you get that thought or that detail down while it s still fresh Read more 2021-12-08 14:38:16
Apple AppleInsider - Frontpage News Apple reportedly allowing 'looser' adherence to ad privacy rules & requirements https://appleinsider.com/articles/21/12/08/apple-reportedly-allowing-looser-adherence-to-ad-privacy-rules-requirements?utm_medium=rss Apple reportedly allowing x looser x adherence to ad privacy rules amp requirementsCertain big tech app developers are claiming that they are still able to derive user level details leading to a report that claims that Apple must not be enforcing App Tracking Transparency fully Apple has been criticized for how its own apps allegedly do not have to follow the company s App Tracking Transparancy ATT privacy rules Now however a new report tries to claim that Apple may not be enforcing them for anyone In a report headlined Apple reaches quiet truce over iPhone privacy changes the Financial Times claims that Apple has made an unacknowledged shift that lets companies follow a looser interpretation of it privacy rules Read more 2021-12-08 14:35:22
Apple AppleInsider - Frontpage News Satechi launches new Thunderbolt 4 dock, two USB-C hubs https://appleinsider.com/articles/21/12/08/satechi-launches-new-thunderbolt-4-dock-two-usb-c-hubs?utm_medium=rss Satechi launches new Thunderbolt dock two USB C hubsSatechi s lastest Mac accessories include an all new Thunderbolt dock as well as the new USB C Multimedia Adapter M plus a USB C Multiport MX Adapter Satechi Thunderbolt DockThe Thunderbolt dock is designed as a perfect fit to the recent Thunderbolt enabled Macs such as the latest generation MacBook Pro Read more 2021-12-08 14:37:58
Apple AppleInsider - Frontpage News How to free up iPhone storage without deleting your apps or photographs https://appleinsider.com/articles/21/12/08/how-to-free-up-iphone-storage-without-deleting-your-apps-or-photographs?utm_medium=rss How to free up iPhone storage without deleting your apps or photographsIf you re running low on iPhone storage you don t have to permanently delete your precious images or app data Here s how to squeeze more space to use within iOS It s a frequent occurrence for iPhone owners who have smaller capacity smartphones fighting the constant battle to have enough storage space available for their data or to install a new app Though it s not as much of a problem now as a few years ago thanks to better access to cloud storage services and generally larger capacity options it s still a problem to some users This is particularly true for those with older iPhone models handed down as other family members upgrade theirs to newer versions You don t have a choice in how much storage you get to play with so you ve got to work with what you ve got Read more 2021-12-08 14:19:25
Apple AppleInsider - Frontpage News How to recover deleted files on Mac with 4DDiG Mac Data Recovery Software https://appleinsider.com/articles/21/12/08/how-to-recover-deleted-files-on-mac-with-4ddig-mac-data-recovery-software?utm_medium=rss How to recover deleted files on Mac with DDiG Mac Data Recovery SoftwareIf you ve ever wiped an important file by accident and need to get it back quickly here s how to recover deleted Mac files using DDiG Mac Data Recovery Software People generate so much data in their lives ranging from important files like legal documents and account spreadsheets to personal memories such as photographs as well as others that are only temporarily valuable or useful While it is usually a good practice to empty the trash every so often on your Mac to save space typically to get rid of useless files sometimes things can go wrong Read more 2021-12-08 14:20:09
海外TECH Engadget Meta will let workers return to the office as late as June https://www.engadget.com/meta-allows-return-to-office-deferrals-141013788.html?src=rss Meta will let workers return to the office as late as JuneMeta now has a more firm timeframe for a full return to the office but it s also giving workers a chance to stay at home for a while longer In a statement to The Wall Street Journal the Facebook parent company said US offices would fully reopen at the end of January but that an quot office deferral program quot will let staff in the US and Canada delay that return for three to five months They can return as late as June if they aren t yet comfortable with in person work but don t want to commit to a long term remote position Human resources VP Janelle Gale said Meta would still quot prioritize health and safety quot at offices for the employees who come back in January However the social media firm also accepted that others quot aren t quite ready quot to appear The move came just days after Google further delayed its return to office plans and at the same time as Lyft said it would no longer require a return in February An increase in COVID cases and uncertainty about the Omicron variant has cast doubt on the safety of requiring every in office worker to return even if there are strict mask and vaccination requirements Simply put it might be a long while before companies can demand office work without facing significant resistance 2021-12-08 14:10:13
海外TECH Engadget YouTube TV is finally coming back to Roku after a prolonged dispute https://www.engadget.com/you-tube-is-finally-coming-back-to-roku-after-after-a-protracted-feud-140010882.html?src=rss YouTube TV is finally coming back to Roku after a prolonged disputeYouTube TV is finally back on Roku streaming devices following a dispute between the two parties that has dragged on since April of this year Both parties agreed to a deal for YouTube TV and the main YouTube app which could have also disappeared if the feud wasn t settled nbsp quot Roku and Google have agreed to a multi year extension for both YouTube and YouTube TV quot a Roku spokesperson said in a statement quot This agreement represents a positive development for our shared customers making both YouTube and YouTube TV available for all streamers on the Roku platform quot Roku originally pulled YouTube TV because it said that Google made anti competitive demands like more prominent placements for the apps and requiring Roku to use certain chips Google retorted that Roku s claims were quot baseless quot and that it was focused on quot ensuring a high quality and consistent experience for viewers quot nbsp Both Roku and Google said recently that the main YouTube app could also disappear from Roku devices if a deal wasn t reached by December th ーa loss that would have been felt far more acutely by Roku owners That generated some negative press that may have brought extra clarity to the negotiations There are no details on how the contract was resolved but the YouTube app is now safe and you should see the YouTube TV app back on your Roku device soon nbsp 2021-12-08 14:00:54
Cisco Cisco Blog From despair to hope: How technology was used for good in Lebanon https://blogs.cisco.com/csr/from-despair-to-hope-how-technology-was-used-for-good-in-lebanon From despair to hope How technology was used for good in LebanonCisco s Maha Akkari shares more about Cisco s collaborative efforts in Lebanon and how we used technology for good to help during a humanitarian crisis 2021-12-08 14:00:56
金融 RSS FILE - 日本証券業協会 インターネット取引に関する調査結果について https://www.jsda.or.jp/shiryoshitsu/toukei/interan.html 調査結果 2021-12-08 16:00:00
金融 RSS FILE - 日本証券業協会 株主コミュニティの統計情報・取扱状況 https://www.jsda.or.jp/shiryoshitsu/toukei/kabucommunity/index.html 株主コミュニティ 2021-12-08 15:30:00
金融 金融庁ホームページ 会計監査の在り方に関する懇談会(令和3事務年度)(第3回)議事要旨について公表しました。 https://www.fsa.go.jp/singi/kaikeikansanoarikata/gijiyousi/20211104.html 会計監査 2021-12-08 16:00:00
金融 ニュース - 保険市場TIMES au損保、女性が選ぶ自転車保険利用率第1位を獲得 https://www.hokende.com/news/blog/entry/2021/12/09/000000 au損保、女性が選ぶ自転車保険利用率第位を獲得最重視は掛け金の安さ株式会社こどもりびんぐは月日、同社が展開するWebコンテンツ「ウーマンリサーチ」が実施した「自転車保険」に関する調査の結果を発表した。 2021-12-09 00:00:00
ニュース BBC News - Home PMQs: Boris Johnson sorry for offence caused by aides joking about lockdown party https://www.bbc.co.uk/news/uk-politics-59580640?at_medium=RSS&at_campaign=KARANGA authority 2021-12-08 14:23:37
ニュース BBC News - Home Ministers considering move to Covid Plan B - source https://www.bbc.co.uk/news/uk-59579077?at_medium=RSS&at_campaign=KARANGA covid 2021-12-08 14:31:32
ニュース BBC News - Home Covid: Pfizer says booster shot promising against Omicron https://www.bbc.co.uk/news/world-59582006?at_medium=RSS&at_campaign=KARANGA variant 2021-12-08 14:48:26
ニュース BBC News - Home Germany's Olaf Scholz takes over from Merkel as chancellor https://www.bbc.co.uk/news/world-europe-59575773?at_medium=RSS&at_campaign=KARANGA merkel 2021-12-08 14:15:50
ニュース BBC News - Home Bipin Rawat: India's top general dies in helicopter crash https://www.bbc.co.uk/news/world-asia-india-59576082?at_medium=RSS&at_campaign=KARANGA tamil 2021-12-08 14:08:11
ニュース BBC News - Home Boss says sorry for 'blundered' mass Zoom firing https://www.bbc.co.uk/news/business-59573146?at_medium=RSS&at_campaign=KARANGA meeting 2021-12-08 14:54:38
ニュース BBC News - Home Tottenham return 13 positive Covid-19 tests - with eight players included https://www.bbc.co.uk/sport/football/59576387?at_medium=RSS&at_campaign=KARANGA Tottenham return positive Covid tests with eight players includedTottenham manager Antonio Conte says that eight players and five members of staff have tested positive for Covid at the club 2021-12-08 14:54:27
北海道 北海道新聞 仏、サウジ記者殺害で誤認拘束 男性は同姓同名の別人 https://www.hokkaido-np.co.jp/article/620740/ 同姓同名 2021-12-08 23:14:00
北海道 北海道新聞 NY円、113円後半 https://www.hokkaido-np.co.jp/article/620736/ 外国為替市場 2021-12-08 23:02:00

コメント

このブログの人気の投稿

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2020-12-01 09:41:49 RSSフィード2020-12-01 09:00 分まとめ(69件)