1642576702
React sensor hooks that re-render on mouse position changes. useMouse
simply tracks mouse position; useMouseHovered
allows you to specify extra options:
bound
— to bind mouse coordinates within the elementwhenHovered
— whether to attach mousemove
event handler only when user hovers over the elementimport {useMouse} from 'react-use';
const Demo = () => {
const ref = React.useRef(null);
const {docX, docY, posX, posY, elX, elY, elW, elH} = useMouse(ref);
return (
<div ref={ref}>
<div>Mouse position in document - x:{docX} y:{docY}</div>
<div>Mouse position in element - x:{elX} y:{elY}</div>
<div>Element position- x:{posX} y:{posY}</div>
<div>Element dimensions - {elW}x{elH}</div>
</div>
);
};
useMouse(ref);
useMouseHovered(ref, {bound: false, whenHovered: false});
Original article source at https://github.com
#react #hook #reacthook #javascript #programming #developer
1659694200
public_activity
provides easy activity tracking for your ActiveRecord, Mongoid 3 and MongoMapper models in Rails 3 and 4.
Simply put: it can record what happens in your application and gives you the ability to present those recorded activities to users - in a similar way to how GitHub does it.
You probably don't want to read the docs for this unreleased version 2.0.
For the stable 1.5.X
readme see: https://github.com/chaps-io/public_activity/blob/1-5-stable/README.md
Here is a simple example showing what this gem is about:
Ryan Bates made a great screencast describing how to integrate Public Activity.
A great step-by-step guide on implementing activity feeds using public_activity by Ilya Bodrov.
You can see an actual application using this gem here: http://public-activity-example.herokuapp.com/feed
The source code of the demo is hosted here: https://github.com/pokonski/activity_blog
You can install public_activity
as you would any other gem:
gem install public_activity
or in your Gemfile:
gem 'public_activity'
By default public_activity
uses Active Record. If you want to use Mongoid or MongoMapper as your backend, create an initializer file in your Rails application with the corresponding code inside:
For Mongoid:
# config/initializers/public_activity.rb
PublicActivity.configure do |config|
config.orm = :mongoid
end
For MongoMapper:
# config/initializers/public_activity.rb
PublicActivity.configure do |config|
config.orm = :mongo_mapper
end
(ActiveRecord only) Create migration for activities and migrate the database (in your Rails project):
rails g public_activity:migration
rake db:migrate
Include PublicActivity::Model
and add tracked
to the model you want to keep track of:
For ActiveRecord:
class Article < ActiveRecord::Base
include PublicActivity::Model
tracked
end
For Mongoid:
class Article
include Mongoid::Document
include PublicActivity::Model
tracked
end
For MongoMapper:
class Article
include MongoMapper::Document
include PublicActivity::Model
tracked
end
And now, by default create/update/destroy activities are recorded in activities table. This is all you need to start recording activities for basic CRUD actions.
Optional: If you don't need #tracked
but still want the comfort of #create_activity
, you can include only the lightweight Common
module instead of Model
.
You can trigger custom activities by setting all your required parameters and triggering create_activity
on the tracked model, like this:
@article.create_activity key: 'article.commented_on', owner: current_user
See this entry http://rubydoc.info/gems/public_activity/PublicActivity/Common:create_activity for more details.
To display them you simply query the PublicActivity::Activity
model:
# notifications_controller.rb
def index
@activities = PublicActivity::Activity.all
end
And in your views:
<%= render_activities(@activities) %>
Note: render_activities
is an alias for render_activity
and does the same.
You can also pass options to both activity#render
and #render_activity
methods, which are passed deeper to the internally used render_partial
method. A useful example would be to render activities wrapped in layout, which shares common elements of an activity, like a timestamp, owner's avatar etc:
<%= render_activities(@activities, layout: :activity) %>
The activity will be wrapped with the app/views/layouts/_activity.html.erb
layout, in the above example.
Important: please note that layouts for activities are also partials. Hence the _
prefix.
Sometimes, it's desirable to pass additional local variables to partials. It can be done this way:
<%= render_activity(@activity, locals: {friends: current_user.friends}) %>
Note: Before 1.4.0, one could pass variables directly to the options hash for #render_activity
and access it from activity parameters. This functionality is retained in 1.4.0 and later, but the :locals
method is preferred, since it prevents bugs from shadowing variables from activity parameters in the database.
public_activity
looks for views in app/views/public_activity
.
For example, if you have an activity with :key
set to "activity.user.changed_avatar"
, the gem will look for a partial in app/views/public_activity/user/_changed_avatar.html.(|erb|haml|slim|something_else)
.
Hint: the "activity."
prefix in :key
is completely optional and kept for backwards compatibility, you can skip it in new projects.
If you would like to fallback to a partial, you can utilize the fallback
parameter to specify the path of a partial to use when one is missing:
<%= render_activity(@activity, fallback: 'default') %>
When used in this manner, if a partial with the specified :key
cannot be located it will use the partial defined in the fallback
instead. In the example above this would resolve to public_activity/_default.html.(|erb|haml|slim|something_else)
.
If a view file does not exist then ActionView::MisingTemplate will be raised. If you wish to fallback to the old behaviour and use an i18n based translation in this situation you can specify a :fallback
parameter of text
to fallback to this mechanism like such:
<%= render_activity(@activity, fallback: :text) %>
Translations are used by the #text
method, to which you can pass additional options in form of a hash. #render
method uses translations when view templates have not been provided. You can render pure i18n strings by passing {display: :i18n}
to #render_activity
or #render
.
Translations should be put in your locale .yml
files. To render pure strings from I18n Example structure:
activity:
article:
create: 'Article has been created'
update: 'Someone has edited the article'
destroy: 'Some user removed an article!'
This structure is valid for activities with keys "activity.article.create"
or "article.create"
. As mentioned before, "activity."
part of the key is optional.
For RSpec you can first disable public_activity
and add require helper methods in the rails_helper.rb
with:
#rails_helper.rb
require 'public_activity/testing'
PublicActivity.enabled = false
In your specs you can then blockwise decide whether to turn public_activity
on or off.
# file_spec.rb
PublicActivity.with_tracking do
# your test code goes here
end
PublicActivity.without_tracking do
# your test code goes here
end
For more documentation go here
You can set up a default value for :owner
by doing this:
PublicActivity::StoreController
in your ApplicationController
like this:class ApplicationController < ActionController::Base
include PublicActivity::StoreController
end
:owner
attribute for tracked
class method in your desired model. For example:class Article < ActiveRecord::Base
tracked owner: Proc.new{ |controller, model| controller.current_user }
end
Note: current_user
applies to Devise, if you are using a different authentication gem or your own code, change the current_user
to a method you use.
If you need to disable tracking temporarily, for example in tests or db/seeds.rb
then you can use PublicActivity.enabled=
attribute like below:
# Disable p_a globally
PublicActivity.enabled = false
# Perform some operations that would normally be tracked by p_a:
Article.create(title: 'New article')
# Switch it back on
PublicActivity.enabled = true
You can also disable public_activity for a specific class:
# Disable p_a for Article class
Article.public_activity_off
# p_a will not do anything here:
@article = Article.create(title: 'New article')
# But will be enabled for other classes:
# (creation of the comment will be recorded if you are tracking the Comment class)
@article.comments.create(body: 'some comment!')
# Enable it again for Article:
Article.public_activity_on
Besides standard, automatic activities created on CRUD actions on your model (deactivatable), you can post your own activities that can be triggered without modifying the tracked model. There are a few ways to do this, as PublicActivity gives three tiers of options to be set.
Because every activity needs a key (otherwise: NoKeyProvided
is raised), the shortest and minimal way to post an activity is:
@user.create_activity :mood_changed
# the key of the action will be user.mood_changed
@user.create_activity action: :mood_changed # this is exactly the same as above
Besides assigning your key (which is obvious from the code), it will take global options from User class (given in #tracked
method during class definition) and overwrite them with instance options (set on @user
by #activity
method). You can read more about options and how PublicActivity inherits them for you here.
Note the action parameter builds the key like this: "#{model_name}.#{action}"
. You can read further on options for #create_activity
here.
To provide more options, you can do:
@user.create_activity action: 'poke', parameters: {reason: 'bored'}, recipient: @friend, owner: current_user
In this example, we have provided all the things we could for a standard Activity.
Besides the few fields that every Activity has (key
, owner
, recipient
, trackable
, parameters
), you can also set custom fields. This could be very beneficial, as parameters
are a serialized hash, which cannot be queried easily from the database. That being said, use custom fields when you know that you will set them very often and search by them (don't forget database indexes :) ).
owner
and recipient
based on associationsclass Comment < ActiveRecord::Base
include PublicActivity::Model
tracked owner: :commenter, recipient: :commentee
belongs_to :commenter, :class_name => "User"
belongs_to :commentee, :class_name => "User"
end
class Post < ActiveRecord::Base
include PublicActivity::Model
tracked only: [:update], parameters: :tracked_values
def tracked_values
{}.tap do |hash|
hash[:tags] = tags if tags_changed?
end
end
end
Skip this step if you are using ActiveRecord in Rails 4 or Mongoid
The first step is similar in every ORM available (except mongoid):
PublicActivity::Activity.class_eval do
attr_accessible :custom_field
end
place this code under config/initializers/public_activity.rb
, you have to create it first.
To be able to assign to that field, we need to move it to the mass assignment sanitizer's whitelist.
If you're using ActiveRecord, you will also need to provide a migration to add the actual field to the Activity
. Taken from our tests:
class AddCustomFieldToActivities < ActiveRecord::Migration
def change
change_table :activities do |t|
t.string :custom_field
end
end
end
Assigning is done by the same methods that you use for normal parameters: #tracked
, #create_activity
. You can just pass the name of your custom variable and assign its value. Even better, you can pass it to #tracked
to tell us how to harvest your data for custom fields so we can do that for you.
class Article < ActiveRecord::Base
include PublicActivity::Model
tracked custom_field: proc {|controller, model| controller.some_helper }
end
If you need help with using public_activity please visit our discussion group and ask a question there:
https://groups.google.com/forum/?fromgroups#!forum/public-activity
Please do not ask general questions in the Github Issues.
Author: public-activity
Source code: https://github.com/public-activity/public_activity
License: MIT license
1597487472
Here, i will show you how to populate country state city in dropdown list in php mysql using ajax.
You can use the below given steps to retrieve and display country, state and city in dropdown list in PHP MySQL database using jQuery ajax onchange:
https://www.tutsmake.com/country-state-city-database-in-mysql-php-ajax/
#country state city drop down list in php mysql #country state city database in mysql php #country state city drop down list using ajax in php #country state city drop down list using ajax in php demo #country state city drop down list using ajax php example #country state city drop down list in php mysql ajax
1642576702
React sensor hooks that re-render on mouse position changes. useMouse
simply tracks mouse position; useMouseHovered
allows you to specify extra options:
bound
— to bind mouse coordinates within the elementwhenHovered
— whether to attach mousemove
event handler only when user hovers over the elementimport {useMouse} from 'react-use';
const Demo = () => {
const ref = React.useRef(null);
const {docX, docY, posX, posY, elX, elY, elW, elH} = useMouse(ref);
return (
<div ref={ref}>
<div>Mouse position in document - x:{docX} y:{docY}</div>
<div>Mouse position in element - x:{elX} y:{elY}</div>
<div>Element position- x:{posX} y:{posY}</div>
<div>Element dimensions - {elW}x{elH}</div>
</div>
);
};
useMouse(ref);
useMouseHovered(ref, {bound: false, whenHovered: false});
Original article source at https://github.com
#react #hook #reacthook #javascript #programming #developer
1597487833
Here, i will show you how to create dynamic depedent country state city dropdown list using ajax in laravel.
Follow Below given steps to create dynamic dependent country state city dropdown list with jQuery ajax in laravel:
https://www.tutsmake.com/ajax-country-state-city-dropdown-in-laravel/
#how to create dynamic dropdown list using laravel dynamic select box in laravel #laravel-country state city package #laravel country state city drop down #dynamic dropdown country city state list in laravel using ajax #country state city dropdown list using ajax in php laravel #country state city dropdown list using ajax in laravel demo
1670592011
By auto-populating dropdown you can restrict users selection based on the parent dropdown selection.
Data is changed on child dropdowns every time selection is changed.
In this tutorial, I show how you can create dynamic dependent dropdown with PostgreSQL data using jQuery AJAX and PHP.
I am using 3 tables in the example –
countries table (Store countries records) –
CREATE TABLE countries (
id serial PRIMARY KEY,
name varchar(80) NOT NULL
)
states table (Store states of the countries) –
CREATE TABLE states (
id serial PRIMARY KEY,
name varchar(80) NOT NULL,
country_id bigint NOT NULL
)
cities table (Store cities of the states) –
CREATE TABLE cities (
id serial PRIMARY KEY,
name varchar(80) NOT NULL,
state_id bigint NOT NULL
)
Create a new config.php
file.
Completed Code
<?php
$host = "localhost";
$user = "postgres";
$password = "root";
$dbname = "tutorial";
$con = pg_connect("host=$host dbname=$dbname user=$user password=$password");
if (!$con) {
die('Connection failed.');
}
Fetch records from countries
table and create 3 <select>
elements –
<select >
element is to display fetched countries
.Completed Code
<?php
include "config.php";
$sql = "select * from countries order by name";
$result = pg_query($con, $sql);
?>
<table>
<tr>
<td>Country</td>
<td>
<select id="country">
<option value="0" >– Select Country –</option>
<?php
while ($row = pg_fetch_assoc($result) ){
$id = $row['id'];
$name = $row['name'];
echo "<option value='".$id."' >".$name."</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td>State</td>
<td>
<select id="state" >
<option value="0" >– Select State –</option>
</select>
</td>
</tr>
<tr>
<td>City</td>
<td>
<select id="city" >
<option value="0" >– Select City –</option>
</select>
</td>
</tr>
</table>
Create ajaxfile.php
file.
Handle 2 AJAX requests –
states
table according to $country_id
value and assign to $result
. Loop on $result
and initialize $data
Array with id
and name
keys.Return $data
in JSON format.
cities
table according to $state_id
value and assign to $result
. Loop on $result
and initialize $data
Array with id
and name
keys.Return $data
in JSON format.
Completed Code
<?php
include 'config.php';
$request = "";
if(isset($_POST['request'])){
$request = $_POST['request'];
}
// Get states
if($request == 'getStates'){
$country_id = 0;
$result = array();$data = array();
if(isset($_POST['country_id'])){
$country_id = $_POST['country_id'];
$sql = "select * from states where country_id=$1";
$result = pg_query_params($con, $sql, array($country_id));
while ($row = pg_fetch_assoc($result) ){
$id = $row['id'];
$name = $row['name'];
$data[] = array(
"id" => $id,
"name" => $name
);
}
}
echo json_encode($data);
die;
}
// Get cities
if($request == 'getCities'){
$state_id = 0;
$result = array();$data = array();
if(isset($_POST['state_id'])){
$state_id = $_POST['state_id'];
$sql = "select * from cities where state_id=$1";
$result = pg_query_params($con, $sql, array($state_id));
while ($row = pg_fetch_assoc($result) ){
$id = $row['id'];
$name = $row['name'];
$data[] = array(
"id" => $id,
"name" => $name
);
}
}
echo json_encode($data);
die;
}
Define change
event on #country
and #state
.
#state
, and #city
dropdown. Send AJAX POST request to ajaxfile.php
, pass {request: 'getStates', country_id: country_id}
as data
, and set dataType: 'json'
.On successful callback loop on response
and add <option >
in #state
.
#city
dropdown and send AJAX POST request to ajaxfile.php
, pass {request: 'getCities', state_id: state_id}
as data
, and set dataType: 'json'
.On successful callback loop on response
and add <option >
in #city
.
Completed Code
$(document).ready(function(){
// Country
$('#country').change(function(){
// Country id
var country_id = $(this).val();
// Empty the dropdown
$('#state').find('option').not(':first').remove();
$('#city').find('option').not(':first').remove();
// AJAX request
$.ajax({
url: 'ajaxfile.php',
type: 'post',
data: {request: 'getStates', country_id: country_id},
dataType: 'json',
success: function(response){
var len = 0;
if(response != null){
len = response.length;
}
if(len > 0){
// Read data and create <option >
for(var i=0; i<len; i++){
var id = response[i].id;
var name = response[i].name;
var option = "<option value='"+id+"'>"+name+"</option>";
$("#state").append(option);
}
}
}
});
});
// Country
$('#state').change(function(){
// State id
var state_id = $(this).val();
// Empty the dropdown
$('#city').find('option').not(':first').remove();
// AJAX request
$.ajax({
url: 'ajaxfile.php',
type: 'post',
data: {request: 'getCities', state_id: state_id},
dataType: 'json',
success: function(response){
var len = 0;
if(response != null){
len = response.length;
}
if(len > 0){
// Read data and create <option >
for(var i=0; i<len; i++){
var id = response[i].id;
var name = response[i].name;
var option = "<option value='"+id+"'>"+name+"</option>";
$("#city").append(option);
}
}
}
});
});
});
In the example, I am auto-populating two dropdowns but you can follow the same steps to add it on more dropdowns.
If data is not loading in the dropdown then use the browser network tab to debug.
If you found this tutorial helpful then don't forget to share.
Original article source at: https://makitweb.com/