投稿時間:2022-03-29 00:37:38 RSSフィード2022-03-29 00:00 分まとめ(42件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
js JavaScriptタグが付けられた新着投稿 - Qiita 【chrome拡張機能】teratailで不快なユーザをブロックする https://qiita.com/mineralwater/items/5a6e016633bf00e4ea24 【chrome拡張機能】teratailで不快なユーザをブロックするはじめにはじめまして最近teratailを使い始めたのですが、意味のない質問を連投しているすごく鬱陶しいユーザがいて不快な気持ちになりました。 2022-03-28 23:19:09
Ruby Rubyタグが付けられた新着投稿 - Qiita タグ付け機能 https://qiita.com/washogo/items/8133f80c1497b5e5fc48 既にlessonに関連付けされているタグを取得し、nameカラムを配列に格納する。 2022-03-28 23:17:58
Ruby Railsタグが付けられた新着投稿 - Qiita タグ付け機能 https://qiita.com/washogo/items/8133f80c1497b5e5fc48 既にlessonに関連付けされているタグを取得し、nameカラムを配列に格納する。 2022-03-28 23:17:58
海外TECH MakeUseOf What Is an Apple HomePod mini? Why You Need One https://www.makeuseof.com/what-is-apple-homepod-mini/ apple 2022-03-28 15:00:14
海外TECH MakeUseOf Forgot Your Android Passcode? 5 Ways to Get Back In https://www.makeuseof.com/tag/forgot-android-passcode/ android 2022-03-28 14:45:14
海外TECH MakeUseOf How to Create Your First Windows Forms (Winforms) Application in Visual Studio https://www.makeuseof.com/create-your-first-windows-forms-winforms-application-in-visual-studio/ forms 2022-03-28 14:45:13
海外TECH MakeUseOf 7 Beginner-Friendly LED Cosplay Projects https://www.makeuseof.com/beginner-friendly-led-cosplay-projects/ beginner 2022-03-28 14:30:13
海外TECH MakeUseOf How to Change the Default Drag-and-Drop File Action in Windows 11 and 10 https://www.makeuseof.com/windows-11-10-change-drag-drop-action/ doesn 2022-03-28 14:15:14
海外TECH DEV Community Own Your Tracks... MQTT to Pulsar from Phones https://dev.to/tspannhw/own-your-tracks-mqtt-to-pulsar-from-phones-556o Own Your Tracks MQTT to Pulsar from Phones OwnTracks to Apache PulsarOwnTracks is a cool and open source app for iphone and android phones for sending out location data to a server of your request You can send HTTP or MQTT Let s pick MQTT and send it to our Pulsar server For a no code ingest of Location Data Maps of Travel Configure MQTT Settings Runs persistent public default owntracks Fuser FBCBD AF EE BD CBCBC root pulsar opt demo apache pulsar bin pulsar client consume persistent public default owntracks Fuser FBCBD AF EE BD CBCBC s owntrax n T pulsar client io INFO org apache pulsar client impl ConnectionPool id xe L R localhost Connected to server T pulsar client io INFO org apache pulsar client impl ConsumerStatsRecorderImpl Starting Pulsar consumer status recorder with config topicNames persistent public default owntracks Fuser FBCBD AF EE BD CBCBC topicsPattern null subscriptionName owntrax subscriptionType Exclusive subscriptionMode Durable receiverQueueSize acknowledgementsGroupTimeMicros negativeAckRedeliveryDelayMicros maxTotalReceiverQueueSizeAcrossPartitions consumerName null ackTimeoutMillis tickDurationMillis priorityLevel maxPendingChunkedMessage autoAckOldestChunkedMessageOnQueueFull false expireTimeOfIncompleteChunkedMessageMillis cryptoFailureAction FAIL properties readCompacted false subscriptionInitialPosition Latest patternAutoDiscoveryPeriod regexSubscriptionMode PersistentOnly deadLetterPolicy null retryEnable false autoUpdatePartitions true autoUpdatePartitionsIntervalSeconds replicateSubscriptionState false resetIncludeHead false keySharedPolicy null batchIndexAckEnabled false ackReceiptEnabled false poolMessages true maxPendingChuckedMessage T pulsar client io INFO org apache pulsar client impl ConsumerStatsRecorderImpl Pulsar client config serviceUrl pulsar localhost authPluginClassName null authParams null authParamMap null operationTimeoutMs lookupTimeoutMs statsIntervalSeconds numIoThreads numListenerThreads connectionsPerBroker useTcpNoDelay true useTls false tlsTrustCertsFilePath tlsAllowInsecureConnection false tlsHostnameVerificationEnable false concurrentLookupRequest maxLookupRequest maxLookupRedirects maxNumberOfRejectedRequestPerConnection keepAliveIntervalSeconds connectionTimeoutMs requestTimeoutMs initialBackoffIntervalNanos maxBackoffIntervalNanos enableBusyWait false listenerName null useKeyStoreTls false sslProvider null tlsTrustStoreType JKS tlsTrustStorePath tlsTrustStorePassword tlsCiphers tlsProtocols memoryLimitBytes proxyServiceUrl null proxyProtocol null enableTransaction false socksProxyAddress null socksProxyUsername null socksProxyPassword null T pulsar client io INFO org apache pulsar client impl ConnectionPool id xbae L R localhost Connected to server T pulsar client io INFO org apache pulsar client impl ClientCnx id xbae L R localhost Connected through proxy to target broker at T pulsar client io INFO org apache pulsar client impl ConsumerImpl persistent public default owntracks Fuser FBCBD AF EE BD CBCBC owntrax Subscribing to topic on cnx id xbae L R localhost consumerId T pulsar client io INFO org apache pulsar client impl ConsumerImpl persistent public default owntracks Fuser FBCBD AF EE BD CBCBC owntrax Subscribed to topic on localhost consumer T pulsar client io INFO com scurrilous circe checksum CrccIntChecksum SSE CRCC provider initialized got message key null properties content type location acc alt batt bs BSSID d cd a conn w lat lon m p SSID FiOS QHWR G t u tid tst vac vel got message key null properties content type location acc alt batt bs BSSID d cd a conn w lat lon m p SSID FiOS QHWR G t u tid tst vac vel got message key null properties content type location acc alt batt bs BSSID d cd a conn w lat lon m p SSID FiOS QHWR G t u tid tst vac vel got message key null properties content type location acc alt batt bs BSSID d cd a conn w lat lon m p SSID FiOS QHWR G t u tid tst vac vel got message key null properties content type location acc alt batt bs BSSID d cd a conn w created at lat lon m p SSID FiOS QHWR G t t tid tst vac vel T pulsar timer INFO org apache pulsar client impl ConsumerStatsRecorderImpl persistent public default owntracks Fuser FBCBD AF EE BD CBCBC owntrax ebed Prefetched messages Consume throughput received msgs s Mbit s Ack sent rate ack s Failed messages batch messages Failed acks got message key null properties content type location acc alt batt bs BSSID d cd a conn w lat lon m p SSID FiOS QHWR G t u tid tst vac vel got message key null properties content type location acc alt batt bs BSSID d cd a conn w lat lon m p SSID FiOS QHWR G t u tid tst vac vel Not Map Source 2022-03-28 14:26:00
海外TECH DEV Community BlurImageLoading... https://dev.to/shameerchagani/blurimageloading-13i1 BlurImageLoading Hey guys I have created this cool project using HTML CSS and JavaScript Shows percentage loading and as the percentage gets closer to the image starts showing up If you want to know how i ve create it comment below for the codepen Link 2022-03-28 14:24:43
海外TECH DEV Community Great Came Changer https://dev.to/bullrocks929/great-came-changer-4b00 Great Came ChangerChelsea s request for a closed door FA Cup tie is bizarreMiddlesbrough has spoken out against Chelsea s request to play their FA Cup game behind closed doors calling the request “bizarre and without merit The refusal of the request for this match is quite controversial and a strong topic to bring up The FA has not yet decided whether to approve or reject Chelsea s request about it Chelsea originally requested for sanctions against owner Roman Abramovich to be lifted so that their fans could buy tickets however there has been no decision from the FA on whether this will be approved or not yet“Chelsea FC recognizes that an outcome in which Middlesbrough was relegated to the Championship would have a huge impact on both Middlesbrough and Chelsea s fans who have already bought tickets for the game but we believe this is the fairest way of proceeding in the current circumstances Chelsea wrote in their request More News 2022-03-28 14:23:04
海外TECH DEV Community Using Ionic Framework VS Code Extension To Add Capacitor To Vite ReactJS Project https://dev.to/aaronksaunders/using-ionic-framework-vs-code-extension-to-add-capacitor-to-vite-reactjs-project-2799 Using Ionic Framework VS Code Extension To Add Capacitor To Vite ReactJS ProjectSimple video walkthrough as I try to utilize the Ionic VS Code Extension to add native functionality to a Vite ReactJS Application I wanted to show how you can create native applications from web applications using Ionic Framework Capacitor A Visual Studio Code Extension for Ionic Ionic Blog I think this is important to show that Ionic has a ReactJS Component Library that I am using in the React Application and a tool Capacitor that I am using to create the native application This video shows that the two are separate and that you don t have to start with an Ionic Project to get to a native application In fact you don t need to use any of the Ionic Framework UI Components to deploy a web application to a native device you only need Capacitor Some ObservationsI did find some interesting challenges and observations which I have listed below and will add to the project s github issues How to debug on a native device You can debug on the web but connecting to a native device through the extension would be a game changer IMHOCould not configure the build directory through the UI There are some options to configure but not the build directory Adding this would make it easier to onboard non ionic projectsWhy do I always have to specify the device when running the app This is just another point to make the process seamless I should be able to set a default device to use based on the platform instead of being forced to select it every timeWhy does sync fail it is missing some property This is an issue was displaying an error message and breaking the development flowCan we integrate build and run on device into one command I think I am looking for this because live reload was not integrated into the tool 2022-03-28 14:20:44
海外TECH DEV Community Deep dive into the CSS :where() function https://dev.to/logrocket/deep-dive-into-the-css-where-function-2457 Deep dive into the CSS where functionWritten by Pelumi Akintokun️The CSS where function is the newest kid on the pseudo class block It takes in a list of selectors as arguments and minifies them allowing you to write less code and at the same time style them all together In this tutorial we ll introduce the where pseudo class function and show how it can be used in production We ll discuss stacking specificity and forgiving in relation to the where function and we ll also look at some specific use cases Let s dive in What is CSS where According to MDN where is a CSS functional pseudo class selector that takes in a list of selectors as an argument and applies the given styles to any element from that list where is very useful for making a long selector list shorter In CSS when multiple elements have the same style rules applied to them at the same time we often end up writing a long list of selectors separated by commas Here s an example in which we apply the same style to all lt a gt tags found inside a header main element and footer element header a hover main a hover footer a hover color green text decoratíon underline There are only three elements that we are selecting in the above code snippet but with a larger number of elements and selectors the code will begin to look untidy and may become difficult to read and understand This is where the where pseudo class function comes into play Here s how the above example would look using the where function where header main footer a hover color red text decoratíon underline Let s take a closer look at how this code works When the browser gets to the code snippet the code directs the browser to look for header main and footer selectors and target all the anchor tags in those selectors Then when a user hovers over any of those anchor tags the browser should apply the specified styles in this case red and underline This pseudo class function gives us the luxury of writing a long selector list in such a way that is shorter and more readily understandable Combining dividing and stacking the where functionWith the where function we can group elements in several ways and combinations We can place the where function at the beginning middle or end of the selector Here s an example with multiple selectors and styles first list header a hover main a hover footer a hover color green text decoratíon underline second list article header gt p article footer gt p color gray third list dark theme button dark theme a dim theme button dim theme a color purple Here s the same code rewritten with the where function first list at the beginning where header main footer a hover color red text decoratíon underline second list in the middle article where header footer gt p color gray third list at the end dark theme where button a color purple In the first list we specify that the red and underline styles should be applied to the header main and footer elements on hover In the second list we specify that the article header and footer elements should be styled with gray We divided the third list into two where functions for better clarity In this list we specify that the button and a element should be styled with the dark theme dim theme and purple Now let s further simplify the functions in the above list at the end dim theme where button a color purple Next we ll even further reduce these functions morphing them into one where function stacked where dark theme dim theme where button a color purple This strategy for reducing a complex selector list is referred to as stacking Specificity and the where functionSpecificity is what browsers look at to determine what CSS property values or styles should applied to a particular element The specificity of the CSS where function is always zero Therefore any element that is targeted with this function automatically gets a specificity of zero as well This gives us the power to easily nullify the style of any element we want while reducing its specificity to zero Here s an example with HTML ordered lists lt div gt lt h gt First list no class lt h gt lt ol gt lt li gt List Item lt li gt lt li gt List Item lt li gt lt ol gt lt div gt lt div gt lt h gt Second list with class lt h gt lt ol class second list gt lt li gt List Item lt li gt lt li gt List Item lt li gt lt ol gt lt div gt lt div gt lt h gt Third list with class lt h gt lt ol class third list gt lt li gt List Item lt li gt lt li gt List Item lt li gt lt ol gt lt div gt In the above code snippet there are three ordered lists with two items in each list The second and third lists have a given class whereas the first list does not Without any styling we can see that each list is ordered numerically Now let s add some styling where ol class list style type none In the above snippet we use the where pseudo class function to select all lt ol gt tags that have a class applied Below we see that the second and third lists which both have a class were targeted with the where function and had their list style type removed Now let s add some additional styling where ol class list style type none second list list style type disc Targeting only the second list using its class name we can see that it is now displayed with bullet points while the third list still has no list style type You might be wondering “But isn t that how it s supposed to be seeing as the new styling is written below the where function styling No it s not and we ll see that in a moment Let s see what happens when we move the code we just added to the top of the code block and move the where function portion to the bottom second list list style type disc where ol class list style type none Notice that the styling still doesn t change Remember the where function has zero specificity Regardless of whether the new code is placed before or after the where function snippet the specificity of the element targeted with where will become zero and its stylings will be nullified To illustrate this further let s add the second list s stylings to the third list following the where function in the code second list list style type disc where ol class list style type none third list list style type disc Both the second and third list are displayed with bullet points irrespective of code placement Now let s look at how the CSS where function will react if one of the elements is targeted with an invalid selector Forgiving and the where functionCSS is generally considered to be non forgiving with regard to selector lists If a browser does not recognize just one selector in a list the entire list of selectors will be considered invalid and their styling will not be applied But this is not the case with the where pseudo class function If an element in a where function is targeted with an invalid selector that element will not get any styling The rest of the elements will still get styled The where function will just skip over the invalid selector to the next valid selector This is why where is known as a forgiving selector In the below example unsupported is an invalid selector for many browsers The below code above will be parsed correctly and will still match the valid selector even in browsers that don t support the unsupported selector where valid unsupported However the following code will be ignored in browsers that don t support the unsupported selector even if they support the valid selector valid unsupported Special use cases for the where functionThe where function can be a useful tool in some special use cases but there are also some instances in which it should be avoided Nearly all setbacks that occur when using the where pseudo class function come down to specificity Because where has zero specificity we need to be very careful about where and when to use this function First let s look at a few use cases in which where can be particularly helpful Improving CSS resetA CSS reset refers to loading a set of style rules prior to any other styles in order to clear the browser s inbuilt styles CSS resets are usually placed at the top or start of the CSS stylesheet so that they load first Developers often use them to remove the default stylings given by the browser to several elements initially before they start actually styling their elements and websites CSS resets can also help remove inconsistencies between different browsers CSS resets are temporary stylings that would change later on in the styling process But depending on the simplicity or complexity of the selectors of an element or group of elements used in the CSS reset it may be difficult to override the initial stylings later on in the code For example let s say we target all anchor tags on the website and style them in green Then we later decide to style all footer anchor tags in gray The new gray color style does not get applied due to the complexity of its selection in the CSS reset The selector in the reset has a higher order of specificity than the selector used later in the code to target just the footer anchor tags so the gray color style is not applied Now if we add the where pseudo class function to the CSS reset this automatically gives all elements in the reset a specificity of zero This makes it easier for us to change the styles later on without having to worry about specificity conflicts Removing stylingThe where function can be useful if we want to remove or nullify the styles or reduce the specificity of an element or set of elements The change will occur at the point that we place it in our code almost like a “mini reset MinifyingShorter code is easier to read and debug A good rule of thumb is to examine any code that has more than two commas or three list items to see if it could be minified using the where function This is also a helpful strategy for combinations of two or more selectors for example section gt header gt p gt a Now let s look at a use case in which the where function should be avoided Maintaining stylingIf it is important to ensure that the styling or specificity of an element or set of elements does not change at any point in the future do not use the where pseudo class The styling and specificity of any element targeted with this selector will be nullified ConclusionThe CSS where pseudo class function is very useful for improving CSS resets removing styling at any point in our code and making our code easier to read and debug In this article we demonstrated how the where function can be used in production and examined several use cases What are your thoughts on this new CSS selector Can you think of any other instances in which it would be useful Is your frontend hogging your users CPU As web frontends get increasingly complex resource greedy features demand more and more from the browser If you re interested in monitoring and tracking client side CPU usage memory usage and more for all of your users in production try LogRocket LogRocket is like a DVR for web and mobile apps recording everything that happens in your web app or site Instead of guessing why problems happen you can aggregate and report on key frontend performance metrics replay user sessions along with application state log network requests and automatically surface all errors Modernize how you debug web apps ーStart monitoring for free 2022-03-28 14:15:29
海外TECH DEV Community Flexbox: flex-grow, flex-shrink y flex-basis 🎨 https://dev.to/duxtech/flexbox-flex-grow-flex-shrink-y-flex-basis-o96 Flexbox flex grow flex shrink y flex basis ÍndiceIntroducciónEl shorthand flexflex grow para rellenar el espacio sobranteflex shrink para rellenar el espacio faltanteflex basis para establecer el ancho base de los itemsConclusionesReferencias Introducción Flexbox ya es un estándar al momento de posicionar elementos y maquetar nuestras app y páginas web como bien sabes existen propiedades flex que se pueden aplicar a nuestro flex container como bien hay otras que se aplican a los flex items Desde hace algún tiempo me tenía muy confundido el uso del shorthand flex gracias a esa duda este pequeño post existe El shorthand flex La propiedad flex nos sirve para escribir propiedades propias de los flex item en una sola línea flex grow para rellenar el espacio sobrante Se aplica a un flex item Acepta valores enteros escalares sin unidad de medida Valor por defecto flex grow permite repartir el espacio sobrante de un flex container entre todos los flex items Un hack útil para calcular cuánto crecerán los flex items sería x EspacioSobrante ∑grow x EspacioSobrante sum growx EspacioSobrante ∑growDonde x es el espacio que se debe adicionar a cada flex item por unidad de grow que haya en la regla css Imagina un escenario como el siguiente Tenemos flex items de px x px donde el flex container tiene un ancho de px entonces nos sobran px para poder repartir como queramos Acáentra flex grow al rescate En el código siguiente vemos a flex grow en acción Cada flex item tiene la propiedad flex grow con sus respectivos valores Ahora apliquemos nuestro hack x px px x px pxx px pxLa sumatoria de los flex grow es por que adicionamos todos los valores de todos los flex items Por cada unidad de flex grow debemos adicionar px de esta manera sabremos cual es el nuevo ancho de todos los flex items Podemos resumir la operación en la siguiente tabla itemsflex growadicciónTOTALitem pxpxitem pxpxitem pxpxitem pxpxitem pxpxDe esta manera flex grow sirve para rellenar el espacio sobrante de flex container entre todos sus flex items flex shrink para rellenar el espacio faltante Se aplica a un flex item Acepta valores enteros escalares sin unidad de medida Valor por defecto flex shrink permite repartir el espacio faltante de un flex container entre todos los flex items Esta propiedad es la contraria a flex grow y por eso mismo el funcionamiento es muy similar Imagina un escenario como el siguiente Tenemos flex items de px x px donde el flex container tiene un ancho de px el ancho total de los flex items es de px pero el contenedor solo es de px ¿Quéocurre entonces Por defecto el navegador intentarátratar de acomodar los flex items dentro del flex container de una manera proporcional esto haráque cada item ya no mida px de ancho como establecimos en el código pero ¿que pasa si queremos que algunos flex items en particular ocupen más o menos espacio Acáentra en acción flex shrink Pese a que en el código indicamos que el ancho de cada item sea de px el navegador recalcula este ancho para que no desborden su contenedor entonces hace px entre por que es la cantidad de los items y restamos px px px eso medirácada item para el navegador antes de aplicar flex shrink Puedes ver el código a continuación Se puede usar la misma fórmula que vimos con flex grow pero teniendo en cuenta el espacio que falta ya no el que sobra x EspacioFaltante ∑shrink x EspacioFaltante sum shrinkx EspacioFaltante ∑shrinkEl contenedor mide px y la suma de todos los items es de px entonces tendríamos un déficit de px que debemos acomodar La suma de flex shrink de todos los items es de x px px x px pxx px pxFinalmente debemos restar px a px ancho original por unidad de flex shrink Podemos resumir la operación en la siguiente tabla itemsflex shrinkadicciónTOTALitem px pxpxitem px pxpxitem px pxpxitem pxpxFinalmente el ejemplo se ve así flex basis para establecer el ancho base de los items Se aplica a un flex item Acepta los mismos valores y unidades que width px etc Valor por defecto auto respeta el width y height si están establecidos flex basis establece el ancho base de un item si mantenemos el valor en auto respetara el ancho y alto previamente establecidos si existe si escribimos un flex basis con valores específicos siempre sobre escribirávalores de ancho y alto Al inicio de este post empezamos hablando de el atajo flex que resume en una línea todas estas propiedades dejaremos esto para otro post Por ahora conocer esto es más que suficiente Conclusionesflex grow se usa cuando tenemos espacio de sobra en el flex container en otras palabras cuando él anchos de los items es menor al de su contenedor repartiendo dicho espacio como el programador quiera flex shrink reparte el espacio faltante del contenedor entre sus items en otras palabras cuando el contenedor es más pequeño que el anchos de todos sus items flex basis establece el ancho base de los items ReferenciasLearn CSSGuía completa de flexboxPosiblemente los siguientes artículos sean de tu interés ES Promesas en JavaScript Cristian Fernando・Oct ・ min read javascript webdev beginners spanish Logical Nullish Assignment en JavaScript Cristian Fernando・Mar ・ min read javascript webdev spanish Local Storage API en JavaScript Cristian Fernando・Aug ・ min read javascript html webdev spanish 2022-03-28 14:14:05
海外TECH DEV Community Vue.js + Google Places: Autocomplete Multiple Input Fields https://dev.to/hirajatamil/vuejs-google-places-autocomplete-multiple-input-fields-2jo4 Vue js Google Places Autocomplete Multiple Input FieldsSometimes you would want to add place autocomplete functionality to more than one input field The typical example would be finding a travel distance between two locations In that case the user will have two input fields with the autocomplete feature enabled on them Let s see how to instantiate the autocomplete object for a single input field Place Autocomplete For a Single Input FieldIn your vue template define the input field with the ref attribute lt input type text placeholder Origin ref origin gt Inside the mounted function instantiate the Autocomplete object by passing the Input field DOM element using the ref attribute which is more efficient than using the traditional id mounted const autocomplete new google maps places Autocomplete this refs origin Pretty straight forward If it does not work for you make sure to add the Places Javascript library to the index html file lt script src key YOUR API KEY gt lt script gt Also make sure to enable both the Maps JavaScript API amp Places API libraries in the Google Cloud Console website if you haven t done so already Place Autocomplete for Multiple Input FieldsLet s add another input field for destination lt input type text placeholder Origin ref origin gt lt input type text placeholder Destination ref destination gt As you know when we add a ref attribute with a value to an HTML element in the vue template it will be added to the this refs Javascript object Let s loop through this refs object and access input DOM elements dynamically mounted for let ref in this refs console log this refs ref Now instantiate the Autocomplete object for each input field inside the loop mounted for let ref in this refs const autocomplete new google maps places Autocomplete this refs ref Attach a Click Event To Autocomplete ObjectsTo get a user selected address we need to attach a place changed event to the Autocomplete object mounted for let ref in this refs const autocomplete new google maps places Autocomplete this refs ref autocomplete addListener place changed gt const place autocomplete getPlace console log place There you have it 2022-03-28 14:12:04
海外TECH DEV Community Utilizando views SQL no Ruby on Rails https://dev.to/stephann/utilizando-views-sql-no-ruby-on-rails-342h Utilizando views SQL no Ruby on Rails IntroduçãoNa maior parte do tempo o desenvolvedor Rails quando precisa de alguma informação do banco de dados usa a API do Active Record pra fazer suas consultas mas às vezes isso não ésuficiente para trazer os dados desejados e énecessário escrever código SQL puro na aplicação Geralmente isso significa que a informação écomplexa demais pra ser obtida apenas as instruções básicas SELECT WHERE JOIN ou então significa que ela évolátil o bastante pra não virar uma tabela fixa no banco de dados Por exemplo os vendedores com o maior volume de negociações no ano uma listagem com os produtos do mercantil mais vendidos em diferentes momentos do dia ou o ticket médio dos clientes por faixa etária Para dificultar ainda às vezes énecessário permitir que esses dados sejam ordenados filtrados e paginados o que pode adicionar mais complexidade ainda para a consulta Uma forma de simplificar essas dores éabstrair essas consultas utilizando as views do banco de dados que são basicamente tabelas virtuais ou seja os não estão persistidas no disco mas fornecem algumas facilidades das tabelas tradicionais Com isso ao invés de lidar sempre com uma consulta complexa do SQL pode ser usado apenas o nome da view para pegar as informações pretendidas E como a view se comporta como uma tabela épossível mapear um modelo do ActiveRecord para uma view do banco de dados com apenas algumas modificações simples e éisso que vou mostrar nesse artigo Pra facilitar e também apresentar uma biblioteca que pode ser desconhecida pra alguns vou utilizar a gem scenic para gerenciar as views da aplicação Rails mas éopcional quem não puder ou não quiser adicionar essa dependência no projeto tudo pode ser feito tranquilamente sem ela Quem for seguir SEM a scenic ficam as dicas A criação de views éfeita nas migrations utilizando o comando execute por exemplo class CreateMinhaView lt ActiveRecord Migration def up execute lt lt SQL CREATE OR REPLACE VIEW public minha view SQL end def down execute DROP VIEW public minha view endendE para armazená las corretamente no dump do schema énecessário mudar o seu formato para sql láno application rb assim module MeuApp class Application lt Rails Application config active record schema format sql endendVale ressaltar que estarei utilizando o PostgreSQL como banco de dados talvez para outros bancos de dados sejam necessárias algumas modificações no que vou ensinar E quando eu me referir a views nesse artigo serão sempre as views do banco de dados e não as views html do projeto ContextoO problema que vamos solucionar éo seguinte Nossa aplicação éum quadro de estatísticas que serve para registrar as conquistas dos jogadores de uma comunidade de e sports A modelagem ésimples éa seguinte Teremos o modelo Player com o atributo nome que representaráo jogador da comunidade O modelo Trophy servirápara representar os troféus que os jogadores poderão obter e teráo atributo de pontuação que éo valor a ser contabilizado na classificação geral Por exemplo ºLugar no Torneio Semanal pontosºLugar Torneio Semanal pontosºLugar Torneio Mensal pontosºLugar Torneio Mensal pontosE por fim teremos o modelo Achievement que servirápara registrar as conquistas dos jogadores ou seja nele serárepresentado o jogador e qual troféu ele ganhou Para criar essa estrutura que descrevi crie uma nova aplicação Rails e execute esses comandos no terminal bundle exec rails g model player namebundle exec rails g model trophy title points integerbundle exec rails g model achievement player references trophy referencesbundle exec rails db create db migrateAgora vamos preencher com alguns dados falsos para termos com o que testar No arquivo db seeds rb coloque o seguinte código e depois execute um bundle exec rails db seed Playersplayer a Player create name Jogador A player b Player create name Jogador B player c Player create name Jogador C player d Player create name Jogador D Trophiestropy gold estadual Trophy create title Ouro Torneio Estadual points tropy silver estadual Trophy create title Prata Torneio Estadual points tropy gold nacional Trophy create title Ouro Torneio Nacional points tropy silver nacional Trophy create title Prata Torneio Nacional points Player A achievements x Gold Nacional x Gold Estadual Total points tropy gold estadual tropy gold estadual tropy gold nacional tropy gold nacional each do trophy Achievement create player player a trophy trophy end Player B achievements x Gold Estadual x Silver Estadual Total points tropy gold estadual tropy silver estadual each do trophy Achievement create player player b trophy trophy end Player C achievements x Silver Estadual Total points tropy silver estadual tropy silver estadual tropy silver estadual each do trophy Achievement create player player c trophy trophy end Player D achievements x Gold Nacional x Silver Nacional x Gold Estadual Total points tropy gold nacional tropy silver nacional tropy silver estadual each do trophy Achievement create player player d trophy trophy end ProblemaCom nossa estrutura montada e com alguns dados fictícios criados nos deparamos com a necessidade de mostrar um ranking uma classificação geral de todos os jogadores da comunidade em uma tela Para resolver essa consulta com a API do ActiveRecord poderia ser feito algo assim players Player select lt lt SQL players name sum trophies points as total points SQL joins achievements trophy group players id order total points DESC players each do player puts player name puts player total points puts end No console apareceria Jogador A Jogador D Jogador B Jogador C Perceba que esse código faz um select utilizando SUM joins um group e uma ordenação Não éláum código muito bonito de se ver espalhado pela aplicação e também não émuito fácil manter Supondo que a comunidade de jogadores seja enorme e precise fazer uma paginação ou a consulta evolua para algo mais personalizado que precise de algum filtro esse código pode ficar mais complexo ainda Para ajudar a organizar isso vamos transferir essa consulta para uma view do banco de dados Instalando a gem scenicPara ajudar a gerenciar as views sql vou utilizar a gem scenic Ela traz a vantagem de poder utilizar as views sem a necessidade de alterar o formato do schema rb para structure sql De quebra fornece um versionamento dessas views facilitando o acompanhamento das modificações e as reversões pra versões anteriores Outro ponto positivo éque todo o código da estrutura da view éarmazenado em arquivos sql facilitando o realce da sintaxe e a execução do código em terminais ou outras ferramentas de banco de dados Para instalar a scenic no nosso projeto primeiro adicione gem scenic no arquivo Gemfile e depois execute um bundle install para finalizar a instalação Criando a view no banco de dadosPara gerar uma view com a scenic énecessário executar o comando no console bundle exec rails g scenic view ranking itemsEsse comando cria um arquivo na pasta db migrations chamado de TIMESTAMP create ranking items rb com o seguinte conteúdo class CreateRankingItems lt ActiveRecord Migration def change create view ranking items endendE também écriado o arquivo db views ranking items v sql sem nada escrito nele Énele que vamos colocar o código que cria nossa view SELECT players id AS player id players name AS player name sum trophies points AS total pointsFROM playersINNER JOIN achievements ON achievements player id players idINNER JOIN trophies ON trophies id achievements trophy idGROUP BY players idORDER BY sum trophies points DESC Perceba que não coloquei nenhum CREATE OR REPLACE VIEW que são os comandos SQL relacionados a criação ou substuição da view pois a scenic jáentende que uma view deve ser criada com o nome ranking items através do create view ranking items que estána migração gerada Para finalizar e criar a view no banco de dados execute um bundle exec rails db migrate Com isso se vocêfor no terminal psql ou no seu SGBD poderáconferir o resultado que a view estágerando com a consulta SELECT FROM ranking items Criando o modeloAgora éa hora de mapear a view que criamos no banco de dados para um modelo do ActiveRecord Não émuito diferente de criar um modelo que aponta para uma tabela física mas tem algumas diferenças Na pasta app models crie um arquivo chamado ranking item rb e coloque o seguinte conteúdo class RankingItem lt ApplicationRecord protected def readonly true endendÉnecessário sobrescrever o método protegido readonly para informar ao Rails e aos demais desenvolvedores que utilizando esse modelo não épermitido inserir atualizar ou apagar informações no banco de dados e se alguém tentar fazer essas ações receberáa exceção avisando ActiveRecord ReadOnlyRecord RankingItem is marked as readonly Sem essa configuração os métodos create update save destroy e afins lançarão erros de sintaxe do SQL não muito claros Antes de prosseguir sóuma dica útil para quem não quer ou não pode seguir o padrão de nomeação das views de acordo com o nome do modelo Existe a possibilidade de configurar o modelo para informar qual o nome da view que ele deve buscar os dados Por exemplo supondo que sua view teve que ser criada com o nome dbviews ranking vocêteráque fazer assim no modelo class RankingItem lt ApplicationRecord self table name dbviews ranking resto do códigoendPronto agora se abrir o console do rails com o bundle exec rails c o modelo poderáser utilizado normalmente boa parte da API do ActiveRecord serácompatível RankingItem first gt lt RankingItem player id player name Jogador A total points gt RankingItem all gt lt ActiveRecord Relation lt RankingItem gt gt r RankingItem find by player name Jogador A r total points gt RankingItem where total points gt size gt RankingItem limit offset gt lt ActiveRecord Relation lt RankingItem gt gt Outra vantagem éque posso também usar as associações do Rails para integrar com outros modelos Por exemplo um ranking item pertence a um player Étotalmente possível adicionar um belongs to player na classe RankingItem e acessar o jogador dessa forma r RankingItem firstr player gt lt Player id name Jogador A created at Quase pronto mas acho que seria bom mostrar a posição do jogador na classificação e percebi que a view que criei não foi criada com essa coluna Como fazer isso Modificando views jáexistentesA scenic também auxilia quando uma view precisa ter sua estrutura alterada O comando éo mesmo que éutilizado para criar a view ou seja bundle exec rails g scenic view ranking items Isso geraráum arquivo de migração chamado TIMESTAMP update ranking items to version rb com o seguinte conteúdo class UpdateRankingItemsToVersion lt ActiveRecord Migration def change update view ranking items version revert to version endendA diferença aqui éque ao invés do create view que foi gerado na primeira vez que executamos o comando agora tem um update view a próxima versão que deveráser utilizada quando a migração for executada e qual a versão deverávoltar em caso de reversão dessa migração Esse update view faráum DROP VIEW e criaráuma nova jáatualizada mas nem sempre épossível por conta de dependências entre views Se um dia passar por essa situação e desejar utilizar um CREATE OR REPLACE VIEW troque o update view por replace view O comando também gerou o arquivo db views ranking items v sql jápreenchido com o código da primeira versão Na nova versão vou adicionar a coluna rank utilizando a função RANK do SQL que representaráa posição do jogador e também deixarei de ordenar pela soma dos pontos e passarei a ordenar pela nova coluna rank A v ficaráassim SELECT RANK OVER ORDER BY sum trophies points DESC AS rank players id AS player id players name AS player name sum trophies points AS total pointsFROM playersINNER JOIN achievements ON achievements player id players idINNER JOIN trophies ON trophies id achievements trophy idGROUP BY players idORDER BY rank Execute o bundle exec rails db migrate e vocêterásua view atualizada Se fizer o select na tabela veráo novo campo com a posição do jogador Mas e se a consulta da nossa view fosse tão complexa em tabelas enormes quantidades de registros que não fosse possível utilizar uma view comum e fosse necessária uma view materializada O scenic também tem opções pra esses casos Materializando a viewCaso vocêprecise de uma view materializada os comandos para gerá la são os mesmos que eu passei atéagora com a diferença que a flag ー materialized deveráestar presente Por exemplo rails g scenic view nome da view materialized Para atualizar os dados da view materializada a scenic disponibiliza o método Scenic database refresh materialized view Então épossível vocêcriar um método de classe no seu modelo para facilitar o uso fica assim class MeuModelo lt ApplicationRecord def self refresh Scenic database refresh materialized view nome da view materializada concurrently false cascade false end protected def readonly true endend ConclusãoÉisso apresentei mais uma solução que vale sempre a pena ter em mãos para quando situações como as apresentadas surgirem no dia a dia Lembrando sempre que nem sempre essa éa melhor opção para solucionar todos os problemas às vezes faz mais sentido criar uma tabela física mesmo ou então usar o padrão Query Objects que falarei posteriormente sobre ele aqui no blog 2022-03-28 14:12:02
海外TECH DEV Community Create reactive pages without any JavaScript!! https://dev.to/dhravya/create-reactive-pages-without-any-javascript-6o7 Create reactive pages without any JavaScript Single page applications by themselves are pretty easy to make But making something complex with modals carousels multiple pages etc is a painful thing to do For example if you have a portfolio website and a small about section a small projects section Everything crammed into one page looks messy so you want to make them into different pages or atleast as modals This would require some javascript and CSS pain that most beginners won t wanna go throughOne of my friends ADI experienced this and called me on discord explaining the problem We both worked out the solution to make the entire process much simpler loadless jsLoadless allows you to create multi page applications but with only one HTML file It s syntax is very easy to use no javascript knowledge required even for customisation worrying about size Don t The library file is only BThere is also functionality to do custom animations on page change and we ve also made many animations like animate left animate right fadein fadeout and many more to come OK but how do I use it Using it is veryyy easy use the CDN linkJust paste this script in the header of your HTML file lt script src main dist loadless min js defer gt lt script gt Creating pagesYou can creating a page by giving the page a data page page id and the trigger to show that page will be data loadless btn page id This will make all the other sister divs which are pages and under the parent disappear note to use the animations you have to also import an optional CSS file from here main dist animations css Here s an example lt a data loadless btn href hello gt Click here to say Hello lt a gt lt br gt lt a data loadless btn two href world gt Click here to say world lt a gt lt div data loadless parent gt lt div id hello data page data animate left gt Hello lt div gt lt div id world data page two data animate fadein gt World lt div gt lt div gt another div lt div gt lt div gt Here I have given it an href so that the page is linkable the possibilities for this are endless this makes so many things easier for beginner web developers Here s an example where ADI used loadless in his portfolio For any help join our discord server We re working on more animations documentation website and much more Support us by ing the project on GitHub loadless loadless Create popups modals page transitions and create pages that do not reload the browser without writing javascript or CSS LoadLessLoadless is a javascipt library that allows you to make reactive SinglePage Applications without ever reloading the pageWhy Loadless Create pages that do not load or refresh the page without writing any javascript code Modals and popups that normally require DOM manipulation can now be created very easily right in HTML Use transitions and animations to load pages without writing CSS Loadless can be customized to meet your needs Easy setup you just need to add CDN links one optional CSS animations file SetupAdd this script tag in your HTML s header make sure to defer it lt script src main dist loadless min js defer gt lt script gt If you want to make the best out of loadless link this CSS cdn It s optional though and the library would work even without it lt link rel stylesheet href main dist animations css gt Usage… View on GitHubAny feedback for the same would be greatly appreciated This blog if you liked it Save this blog if you want to use it later Follow me on My twitter and if you REALLY liked this blog and please follow me here on dev to followers possible 2022-03-28 14:10:50
海外TECH DEV Community Automated Accessibility Testing https://dev.to/thawkin3/automated-accessibility-testing-5b93 Automated Accessibility TestingAs more and more companies focus on making their apps accessible a question that often comes up is “How do we make sure we don t let things slip We ve done all this work to remediate our app but how do we make sure we don t dig ourselves back into a hole six months later and end up in a similar situation that we are in now How do we keep things accessible There are a few solutions The first is education and training Everyone in the company needs to be an accessibility advocate and understand accessibility best practices The second is better organizational processes Companies should include accessibility audits in natural checkpoints throughout the software development lifecycle like when UX provides design mockups to the engineering team or when the engineering team is code complete on a new feature The third is automated testing and that s what I d like to focus on today DisclaimerAs a brief disclaimer before we begin I want to emphasize that when it comes to accessibility there is no adequate alternative to good manual testing with a mouse keyboard and screen reader Ask any accessibility consultant and they will tell you the same thing The hangup is that engineers are often dissatisfied with that answer Engineers like to automate everything Manual testing sounds tedious and it doesn t scale And you would be right Those are fair concerns So let s take a look at some of the automated tools we have available and examine their benefits as well as their drawbacks Automated Accessibility ToolsThere are several good tools that can assist us in our accessibility efforts Some of the common tools that I ve used are ESLint plugins like eslint plugin jsx ay tools from Deque like the axe DevTools Chrome extension or the axe Monitor web crawler and CI tools like Google Lighthouse or GitLab CI CD with Pay The thing to know about all of these tools is that they are all static analysis checkers Static analysis checkers examine the code whether that be the JavaScript source code or the built HTML on the web page and then report possible violations based on a set of rules And here s the kicker these static analysis checkers can only catch about of accessibility issues in your app Yes you read that number correctly Why is that number so low To get a better understanding of why we should look at the kinds of things that these tools are good at identifying as well as the things that they are bad at identifying What Static Analysis Checkers Are Good at IdentifyingStatic analysis checkers are good at identifying invalid usages of HTML For instance they ll catch when you use an anchor tag lt a gt without an href attribute Maybe you ve put a click handler on the anchor tag to make it function more like a button which would be invalid The static analysis checker would report a violation and let you know that you should either use a lt button gt element with a click handler or else provide a valid href attribute for your lt a gt element if you really intended for it to be a link As another example static analysis checkers can identify when you ve used heading elements lt h gt through lt h gt in the wrong order The rule is that heading levels can only increase by one so you can t have an lt h gt element followed by an lt h gt element If the static analysis checker sees this in your app it will report a violation As a third example a static analysis checker could also identify if you incorrectly nest elements in a list The direct descendants of lt ul gt or lt ol gt elements need to be lt li gt elements so if you have something like a lt div gt as a child of your lt ul gt or lt ol gt list container the static analysis checker will complain Static analysis checkers are also good at identifying bad uses of roles and interaction handlers A common mistake that I frequently see is someone using a lt div gt element with a click handler rather than a lt button gt element The problem with this approach alone is that you lose a lot of the functionality that the semantic lt button gt element provides for you out of the box For instance the lt button gt element responds to clicks as well as Enter and Space key presses and it correctly communicates its role “button to screen readers A static analysis checker looking at your source code like eslint plugin jsx ay will report these violations and let you know that if you have a click handler you will also need an accompanying keyboard interaction handler as well as an appropriate role on your element Finally static analysis checkers that run against the rendered app in your browser are also great at catching color contrast issues when the color contrast ratio for any given foreground background combination falls below the required threshold As a quick review these are some of the main things that static analysis checkers are good at identifying Invalid usages of HTMLBad use of roles and interaction handlersColor contrast issues What Static Analysis Checkers Are Bad at IdentifyingNow let s talk about what static analysis checkers are bad at identifying The short answer is that they will be bad at identifying things that have technically correct source code but that provide a poor user experience for humans For example let s consider the tab order of a page For most Western languages that read left to right the tab order on the page will generally go left to right top to bottom You might have a column layout on your page in which case the tab order would go down one column before moving along to the next column When tabbing through a page you may sometimes encounter the tab focus moving to an element that you didn t expect maybe skipping a few other buttons or just going somewhere completely unrelated This is disorienting to a human but isn t something that a static analysis checker would be able to catch Only a human can tell what tab order makes sense or not Another example would be unhelpful aria labels A static analysis checker will be good at telling you when a label is missing like for an icon only button that doesn t have an aria label But a static analysis checker won t be able to tell you if the aria label is helpful or makes sense You could type some nonsense characters as the aria label value to get past the static analysis checker but it won t be helpful to your users Third static analysis checkers can t identify keyboard traps These are unintentional focus traps where a keyboard only user cannot escape without using their mouse You might encounter a keyboard trap when interacting with popup content like a modal or a tooltip or a dropdown menu A keyboard only user needs to be able to get into and out of keyboard traps so if they can t escape that s an issue Fourth static analysis checkers can t identify when there is missing alternative functionality on the page to accommodate all users Take drag and drop behavior for example Drag and drop functionality is inherently inaccessible because it requires the use of the mouse and fine motor control to move the mouse pointer from one specific position to another This isn t a problem on its own but you do need to provide alternative methods to accomplish the same task So for something like using drag and drop functionality to reorder items in a list you might also provide keyboard controls to allow keyboard only users to press the Enter key to activate “reorder mode and then use the arrow keys to move items up or down in the list Static analysis checkers can t possibly know when you have sufficient alternative methods for accomplishing any given task Fifth static analysis checkers can t identify areas where semantic HTML usages could be improved For example maybe you ve built a table out of lt div gt elements Visually it looks like a table but it won t have the same navigation behavior for screen reader users and it won t be communicated as a table for screen reader users Static analysis checkers won t complain because the actual HTML code you ve written is technically correct without any invalid syntax The static analysis checker doesn t know that you ve intended for this to represent a table Similarly you might have a list of items on the page that are built using paragraph lt p gt elements rather than lt ul gt lt ol gt and lt li gt elements Or maybe you have a dialog modal but that is missing all the required accompanying modal markup like aria modal true role dialog and an aria label providing a title for the modal Screen readers will see technically correct HTML built will not know your intent behind the type of widgets or information you are trying to convey Again as a quick review these are some of the main things that static analysis checkers are bad at identifying Confusing tab orderUnhelpful aria labelsKeyboard trapsMissing alternative functionalityAreas where semantic HTML could be improved Humans vs ComputersSo we have a dilemma here As engineers we want to be able to automate our accessibility testing But the tools that we have at our disposal are not sufficient on their own to give us confidence that our app is in fact accessible What do we do about this The key here is to understand that computers are good at some things and humans are good at some things Computers are fast don t need rest and can execute instructions flawlessly even when we as humans give them incorrect instructions Humans on the other hand are better at higher level thinking and reasoning When it comes to auditing the accessibility of our app we can take a step back and ask “Does this make sense Can I use this Does what we ve built provide a good user experience So rather than competing why not let humans and computers work together to provide the best of both worlds As humans we can decide what criteria are important what is worth testing and what the expected behavior should be We can codify those requirements as automated tests Computers can then run our tests and we can include these tests in a continuous integration CI pipeline to prevent accessibility regressions in our app Let s look at a couple examples Example ModalFor our first example let s imagine that we re building a modal We can find guidance for how we can build accessible modals through the Web Content Accessibility Guidelines WCAG as well as the WAI ARIA Authoring Practices docs Our modal criteria will look like this Modal is opened when the trigger button is clicked​Modal has appropriate aria markup aria modal true role dialog aria label ​Focus is sent to the first focusable item inside the modal when it opens​Focus is trapped inside the modal​Modal is closed when the Close button is clicked and focus is returned to the trigger button​Modal is closed when the Escape key is pressed and focus is returned to the trigger button​Modal is closed when anywhere outside the modal is clicked and focus is returned to the trigger button​Our next questions would naturally be at what level should we test this criteria and how can we write these tests When writing accessibility tests the correct level to test them will almost always be as unit tests You don t need to write an end to end test to verify that your modal has the correct aria markup Unit tests will suffice So how can we write unit tests for these criteria Using the same tools you already do for your other unit tests I primarily work in React so my tools of choice are Jest as my test framework with React Testing Library and the User Event library as my test libraries React Testing Library is great for rendering and interacting with components User Event is a companion library that helps make testing user interactions even simpler It s great for testing things like tab behavior or firing events that the document is listening for Example Clickable Div ButtonLet s consider another example We discussed clickable lt div gt elements earlier in this article and some of the functionality you have to re implement on your own if you choose to use an element other than the semantic lt button gt element Our acceptance criteria for this button will look like this Click handler is called on click​Click handler is called on Enter keypress​Click handler is called on Space keypress​Click handler is not called on any other keypress​Element has role button attributeSo where and how can we test for these criteria Your answer should be the same as last time We can write unit tests for this using our test framework and libraries of choice Key TakeawaysWe ve covered a lot of info here today If there is anything you remember from this article I hope it will be these points Static analysis checkers on their own are not sufficient tools to ensure that your app is accessible It s important to do manual exploratory testing to validate that humans can actually use your app with a mouse keyboard and or screen reader We can take those findings from our manual testing fix the bugs and write automated tests to prevent regressions Thanks for reading and thank you for being an accessibility advocate 2022-03-28 14:09:44
海外TECH DEV Community The Verginia Engineer https://dev.to/virginiaenginee/the-verginia-engineer-12j6 The Verginia EngineerFeature Article Sump pump installation costNovember A sump pump is one of the best ways to eliminate basement flooding and moisture Although they can be installed outside or indoors they are usually located inside at the lowest point in your crawlspace or basement floor These areas are more susceptible to mold and mildew Sump pump prices can vary depending on many factors Let s dive into the details Guest Article Four Things That Do Not Change for Recruiting and Hiring During A CrisisJanuary As you think about your strategy to keep the hiring engines on and bring in the talent your organization needs for the future here are four key elements of the experience…By Jeremy EskenaziNews Formation Of Sorba Engineering AnnouncedJanuary Firm will offer civil engineering expertise under the new banner of Sorba Engineering Biological Ceramics Hidden Strengthening Mechanism ExposedJanuary New insights into building stronger and tougher ceramics by studying the shells of bivalve mollusks Bernard M Gordon Prize for Innovation in Engineering and Technology Education AwardedJanuary Biennial prize acknowledges new modalities and experiments in education that develop effective engineering leaders Rees Scholarship Foundation Awards In ScholarshipsJanuary Scholarships awarded to students seeking to become technicians in the HVACR and water heating industry AHRI to Host New Refrigerant WebinarJanuary Panel will discuss AL refrigerant behavior in a structure fire More News 2022-03-28 14:09:33
海外TECH DEV Community Getting started with Floating UI https://dev.to/logrocket/getting-started-with-floating-ui-250a Getting started with Floating UIWritten by Nefe James️ IntroductionFloating elements are elements that float on top of the UI without disrupting the flow of content Tooltips are examples of floating element they are short messages that appear on a page when a user hovers over a specific area We can use tooltips to create user onboarding flows send updates and reminders to our users provide more information about a feature and more Popper has long been one of the most popular JavaScript libraries for creating floating elements However a new player is in town its successor Floating UI Floating UI comes with several upgrades It is cross platform compatible and can be used in React and React Native applications It is smaller than Popper Popper weighs kb and Floating UI is bytes It is also tree shakeable by default while Popper is not Floating UI is not just an alternative to Popper but an upgrade with several benefits In this article we will learn about Floating UI and how we can use it to create floating elements About Floating UIFloating UI is an extensible low level library for creating interactive elements like tooltips popovers dropdowns menus and more Floating UI exposes primitives which we can use to position a floating element next to a given reference element It also supports the web React React Native WebGL Canvas and more Getting startedRun the command below to install Floating UI npm install floating ui domWe can also load Floating UI through a CDN using ESM or UMD format like so lt script type module gt import as FloatingUIDOM from floating ui dom lt script gt The computePosition functionThe computePosition function is the heart of Floating UI It computes the coordinates needed to position the floating element next to its given reference element which is the element that triggers the floating element Let s build a basic tooltip to see how computePosition works We start by setting up the HTML lt DOCTYPE html gt lt html lang en gt lt body gt lt button id button aria describedby tooltip gt My button lt button gt lt div id tooltip role tooltip gt My tooltip oltip with more content lt div gt lt script src index js type module gt lt body gt lt html gt Next we style the tooltip and set its position to absolute so it floats and doesn t disrupt the flow of the other content tooltip color fff background font size rem padding px px border radius px position absolute box shadow px px rgba px px rgba button border radius px border none outline none font size rem cursor pointer padding px px color fff background rgb Having set up the structure and styling for the tooltip let s work on the functionality import computePosition from floating ui dom const button document querySelector button const tooltip document querySelector tooltip computePosition button tooltip then x y gt Do things with x and y Object assign tooltip style left x px top y px The button is the reference element and the tooltip is the floating element We can change the placement of the tooltip to different positions like so computePosition button tooltip placement top start then x y gt other code below There are core positions we can place elements left start left and left end top start top and top end right start right and right end bottom start bottom and bottom endThe default position of a floating element is bottom MiddlewareMiddleware is a piece of code that runs between the call of computePosition and its eventual return to modify or provide data to the consumer It alters the placement and behavior of floating elements Middleware is how every single feature beyond the basic placement positioning is implemented Floating UI provides several middlewares offset places spacing between the reference element and the floated element shift shifts the floated element to ensure its entire content is always in view It also ensures that the element does not overflow outside the viewport by handling clipping and overflow issues flip modifies the coordinates for us such that the bottom placement automatically positions the floating element at the bottom if it is too close to the top of the viewport and vice versa size handles the resizing of the floated element autoPlacement automatically chooses the placement of the floated element by selecting the position with the most space available inline improves positioning for inline reference elements that span over multiple lines such as hyperlinksLet s extend the behavior of the basic tooltip with some of these middlewares computePosition button tooltip placement top middleware offset flip shift padding then x y gt other code below Above we use offset to add a px spacing between the tooltip and the button Besides fixing content clipping issues the shift middleware accepts an options object where we define the spacing between the tooltip and the edge of the viewport We set the spacing to px The order in which we arrange the middlewares is important offset must always be at the beginning of the array Showing tooltips on hoverCurrently the tooltip is always visible However it should only show when we hover over the button Let s set up that functionality function setUpTooltip computePosition button tooltip placement top middleware offset flip shift padding then x y gt Object assign tooltip style left x px top y px function showTooltip tooltip style display block setUpTooltip function hideTooltip tooltip style display none Above we move the tooltip logic into a function setUpTooltip so we can call that function when we want the tooltip to show We also create two functions hideTooltip and showTooltip hideTooltip sets the tooltip s display to none showTooltip sets the tooltip s display to block and class setUpTooltip We want to call hideTooltip when we hover away from the button and call showTooltip when we hover over the button mouseenter showTooltip mouseleave hideTooltip forEach event listener gt button addEventListener event listener Here we attach the event listeners and the functions to the button With this the tooltip will only appear on hover We have the final code for the tooltip below import computePosition flip shift offset from floating ui dom const button document querySelector button const tooltip document querySelector tooltip function setUpTooltip computePosition button tooltip placement top middleware offset flip shift padding then x y gt Object assign tooltip style left x px top y px function showTooltip tooltip style display block setUpTooltip function hideTooltip tooltip style display none mouseenter showTooltip mouseleave hideTooltip focus showTooltip blur hideTooltip forEach event listener gt button addEventListener event listener Using Floating UI with ReactWe can easily integrate Floating UI into React applications First we have to install the React library into a React application like so npm install floating ui react domFloating UI provides a useFloating Hook we can use in React applications Let s use this Hook to set up the basic tooltip in React import useFloating shift offset flip from floating ui react dom export default function App const x y reference floating strategy useFloating placement right middleware offset flip shift padding return lt gt lt button ref reference gt Button lt button gt lt div id tooltip ref floating style top y left x gt Tooltip lt div gt lt gt The useFloating Hook accepts all of computePosition s options meaning we can define the placement of a tooltip and add middleware ConclusionIn this article we have learned about floating UI how it works its different features and how to integrate it into React applications While Floating UI offers a few benefits over Popper one thing I would have loved to see is a demo showing how to conditionally display tooltips on hover for React Sadly the documentation does not cover that Also there is little or no developer content or support available as this is a new library So while Floating UI is a great new tool these are things we should take into account when working with it LogRocket Full visibility into your web appsLogRocket is a frontend application monitoring solution that lets you replay problems as if they happened in your own browser Instead of guessing why errors happen or asking users for screenshots and log dumps LogRocket lets you replay the session to quickly understand what went wrong It works perfectly with any app regardless of framework and has plugins to log additional context from Redux Vuex and ngrx store In addition to logging Redux actions and state LogRocket records console logs JavaScript errors stacktraces network requests responses with headers bodies browser metadata and custom logs It also instruments the DOM to record the HTML and CSS on the page recreating pixel perfect videos of even the most complex single page and mobile apps Try it for free 2022-03-28 14:08:33
Apple AppleInsider - Frontpage News Apple Maps teams hiking around UK cities with camera-laden backpacks https://appleinsider.com/articles/22/03/28/apple-maps-teams-hiking-around-uk-cities-with-camera-laden-backpacks?utm_medium=rss Apple Maps teams hiking around UK cities with camera laden backpacksApple is making Apple Maps more accessible to pedestrians in the UK by sending out workers wearing data collecting backpacks to go where its fleet of mapping cars cannot reach Mapping services like Apple Maps typically rely on data collected from a modified vehicle traveling along roads but the approach means pedestrianized areas sometimes get left out In the UK Apple is working to improve Apple Maps for pedestrians by collecting more data away from the cars Starting from Monday and continuing through until May Apple is sending out employees in areas of London Birmingham and Manchester to collect more data for Apple Maps reports Bloomberg The effort will focus on areas where cars cannot easily access an area but pedestrians have free rein to walk through Read more 2022-03-28 14:52:52
Apple AppleInsider - Frontpage News Ad industry worried about expansion of Apple's iPhone privacy features https://appleinsider.com/articles/22/03/28/ad-industry-worried-about-expansion-of-apples-iphone-privacy-features?utm_medium=rss Ad industry worried about expansion of Apple x s iPhone privacy featuresAd industry experts are concerned about the future expansion of Apple s privacy features on iPhone including the recently released Private Relay and Hide My Email iPhone privacyApple released both features as part of its iOS software update bringing new privacy protections months after releasing App Tracking Transparency ーa privacy mechanism that has pummeled the mobile advertising industry s revenue Read more 2022-03-28 14:48:04
Apple AppleInsider - Frontpage News Matter is delayed, MotionBlinds availability & more on the HomeKit Insider podcast https://appleinsider.com/articles/22/03/28/matter-is-delayed-motionblinds-availability-more-on-the-homekit-insider-podcast?utm_medium=rss Matter is delayed MotionBlinds availability amp more on the HomeKit Insider podcastOn the latest episode of the HomeKit Insider podcast your hosts touch on how the upcoming unifying standard Matter has been delayed once more the expansion of Eve MotionBlinds availability and we also discuss the Apple Studio Display HomeKit InsiderThis past week the Connectivity Standards Alliance has announced that unprecedented interest has forced a subsequent delay in Matter Matter is intended to unify the smart home allowing devices intended for multiple platforms to work together seamlessly ーincluding Apple s HomeKit Read more 2022-03-28 14:13:46
Apple AppleInsider - Frontpage News Samsung's $700 Smart Monitor M8 borrows Apple's multi-colored iMac style https://appleinsider.com/articles/22/03/28/samsungs-700-smart-monitor-m8-borrows-apples-multi-colored-imac-style?utm_medium=rss Samsung x s Smart Monitor M borrows Apple x s multi colored iMac styleSamsung has opened up preorders for its Smart Monitor M a screen with a minimalist appearance that is available in a range of colors a design choice echoing Apple s inch iMac Samsung Smart Monitor MInitially launched in January the M is a inch smart monitor that offers a few more features than the typical computer display Instead it performs double duty as a smart TV with it able to stream content independently of whatever device is connected to it Read more 2022-03-28 14:14:52
Apple AppleInsider - Frontpage News Top 7 Amazon deals for the week of March 28: Apple AirPods, Mac mini, TurboTax, iPad Air & more on sale https://appleinsider.com/articles/22/03/28/top-5-amazon-deals-for-the-week-of-march-28-airpods-mac-mini-turbotax-more-on-sale?utm_medium=rss Top Amazon deals for the week of March Apple AirPods Mac mini TurboTax iPad Air amp more on saleWeekly deals on Apple products high end audio equipment gaming gear and even tax software are going on now at Amazon with cash discounts of up to off We ve rounded up our favorites on March Save on Apple AirPods TurboTax software for Mac and audio equipmentBargain hunters can check out Amazon s daily deals on this dedicated sale page but we re highlighting our own top picks below Read more 2022-03-28 14:06:16
海外TECH Engadget HP buys Poly, the company formerly known as Plantronics https://www.engadget.com/hp-buys-poly-plantronics-142337041.html?src=rss HP buys Poly the company formerly known as PlantronicsPlantronics now Poly s long independent streak is coming to an end Reutersreports HP is acquiring Poly in an all cash deal worth billion including debt HP said the purchase would bolster its quot hybrid work quot offerings such as headsets and videoconferencing hardware The computing giant didn t say if Poly would still operate as a distinct brand or retain its CEO we ve asked HP for comment but the deal is expected to close by the end of Don t expect this to lead to HP branded consumer headphones or earbuds When Plantronics rebranded as Poly the company was already transitioning from personal audio to work oriented products like meeting room speakers and videoconferencing cameras Only a handful of items such as the Voyager headphone range are designed with home use at least partly in mind As it stands HP already targets everyday users with its gaming focused HyperX brand Whatever HP s intentions the buyout closes an important chapter in audio history Plantronics was one of the first companies to produce Bluetooth headsets and developed an early reputation as a go to brand for hands free calling However its attempts at competing with consumer heavyweights like Apple Bose and Sony never really panned out While Plantronics created well made headphones and earbuds that sometimes undercut the competition on price it never reached the level of hype that helped its rivals succeed The acquisition of Polycom and the subsequent Poly rebrand was in a sense an acknowledgment that Plantronics strength was in the office rather than at home It s also no secret that Poly had entertained buyers In Plantronics had been in talks with Logitech about a possible deal That fell through but it was already clear the firm was open to a merger The HP move might represent a happy ending in that light even if Poly is losing its independence in the process 2022-03-28 14:23:37
Cisco Cisco Blog Next-Generation Enterprise Campus Network Virtualization with BGP EVPN VXLAN https://blogs.cisco.com/networking/next-generation-enterprise-campus-network-virtualization-with-bgp-evpn-vxlan Next Generation Enterprise Campus Network Virtualization with BGP EVPN VXLANCisco remains laser focused on listening executing and delivering world class solutions to our customers on their path to digital network transformation And if you are ready we are here to help Reach out to your Cisco sales team to start your BGP EVPN VXLAN journey 2022-03-28 15:00:40
海外TECH CodeProject Latest Articles Deploying Models at Scale on Azure - Part 1: Deploying XGBoost Models https://www.codeproject.com/Articles/5328263/Deploying-Models-at-Scale-on-Azure-Part-1-Deployin endpoints 2022-03-28 14:04:00
海外科学 NYT > Science Bobcats With a Taste for Python Eggs Might Be the Guardians of Florida’s Swamp https://www.nytimes.com/2022/03/28/science/bobcat-python-eggs.html Bobcats With a Taste for Python Eggs Might Be the Guardians of Florida s SwampCameras captured the wild feline purloining a Burmese python s eggs giving hope that the state s native species are responding to a voracious invasive predator 2022-03-28 14:17:33
海外科学 NYT > Science Cancer Patients Are at High Risk of Depression and Suicide, Studies Find https://www.nytimes.com/2022/03/28/health/cancer-patients-depression-suicide.html Cancer Patients Are at High Risk of Depression and Suicide Studies FindTwo new studies of millions of people around the world suggest that doctors should be thinking more about cancer patients mental health experts said 2022-03-28 15:00:11
金融 RSS FILE - 日本証券業協会 J-IRISS https://www.jsda.or.jp/anshin/j-iriss/index.html iriss 2022-03-28 15:44:00
ニュース BBC News - Home P&O Ferries P&O given deadline to reemploy sacked workers https://www.bbc.co.uk/news/business-60895833?at_medium=RSS&at_campaign=KARANGA previous 2022-03-28 14:57:21
ニュース BBC News - Home School-run mum admits climate protest driving charge https://www.bbc.co.uk/news/uk-england-essex-60900298?at_medium=RSS&at_campaign=KARANGA october 2022-03-28 14:52:49
ニュース BBC News - Home Schools White Paper includes higher maths and English targets https://www.bbc.co.uk/news/education-60846684?at_medium=RSS&at_campaign=KARANGA poorer 2022-03-28 14:53:58
ニュース BBC News - Home Sale of Banksy anti-war artwork raises funds for Kyiv hospital https://www.bbc.co.uk/news/uk-england-bristol-60904770?at_medium=RSS&at_campaign=KARANGA children 2022-03-28 14:07:18
ニュース BBC News - Home First England women's football captain honoured with plaque https://www.bbc.co.uk/news/uk-england-lancashire-60902638?at_medium=RSS&at_campaign=KARANGA women 2022-03-28 14:18:12
ニュース BBC News - Home Oscars fashion: Red carpet in pictures https://www.bbc.co.uk/news/entertainment-arts-60896370?at_medium=RSS&at_campaign=KARANGA hollywood 2022-03-28 14:55:25
北海道 北海道新聞 NY株、反落 https://www.hokkaido-np.co.jp/article/662378/ 週明け 2022-03-28 23:34:00
北海道 北海道新聞 <マイク>コロナ後見据えた販売戦略を 日本農業法人協会、紺野専務 https://www.hokkaido-np.co.jp/article/662376/ 日本農業法人協会 2022-03-28 23:29:00
北海道 北海道新聞 中米エルサルバドルで殺人急増 非常措置適用、憲法停止も https://www.hokkaido-np.co.jp/article/662375/ 殺人事件 2022-03-28 23:24:00
北海道 北海道新聞 ロシア独立系紙が活動停止 編集長がノーベル平和賞 https://www.hokkaido-np.co.jp/article/662361/ 活動停止 2022-03-28 23:08:00
北海道 北海道新聞 G7、ルーブル払い拒否で一致 ロシアとの天然ガス取引で https://www.hokkaido-np.co.jp/article/662371/ 天然ガス 2022-03-28 23:08:00

コメント

このブログの人気の投稿

投稿時間:2021-06-17 22:08:45 RSSフィード2021-06-17 22:00 分まとめ(2089件)

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

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