当前位置:网站首页>ng-tv-focusable

ng-tv-focusable

2022-06-13 01:26:00 Durian is not delicious

brief introduction

tv-focusable Is applicable to TV A framework for managing focus movement during web page development , With simple Api Let front-end web development be like android Develop the same automated focus .

download

npm i ng-tv-focusable

Effect of the sample
 Insert picture description here
vue-tv-focusable
react-tv-focusable

How to use

app.module.ts Add the following code to

 // app.module.ts
import {
     TvFocusableModule } from 'ng-tv-focusable';
@NgModule({
    
  declarations: [...],
  imports: [
    ...,
    TvFocusableModule
  ],
  ...
  bootstrap: [AppComponent]
})

1. Set the element to get focus

<div [ng-focusable]> Elements that can get focus </div>
<div> Elements that cannot get focus </div>

Follow android Are they very similar ~
To blame android Students of development popularize , It's going on android Of TV End development , The system will automatically give focusable=true Element of the distribution focus , for example :

    <TextView android:id="@+id/text1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:focusable="true" />
    <TextView android:id="@+id/text2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:focusable="true" />

Suppose the two elements are arranged left and right , When the focus is on the front one text1 Upper time , Press the right button on the remote control , The focus will automatically go to text2 On .
Now set... On the page tab [ng-focusable] Equivalent to android Set up android:focusable=“true”, When the user presses the remote control , The library will look like android That automatically moves the focus to the next focus , No developer processing .

2. Set the style of focus

The focused element will be added with a class="focus" ( You can define className, The default is focus)
Now you should know what to do , to focus Just set a unique style .
Such as this :

<div class="demo">
    <span 
    *ngFor='let in of counter(60) ;let i = index' 
    class="span" [ng-focusable]>
      {
    {
    i+1}}
    </span>
  </div>
...
.focus {
    
  transform: scale(1.1);
  border: 2px solid red;
  box-shadow: 0 0 20px red;
}

 Insert picture description here

Okay , So that's the setup , Now when you press the arrow key, the focus will automatically move to the next target element , Very simple. ~

3. Specifies that the focus is moved to an element

In the above demonstration, the first element captures the focus at the beginning , In fact, when you use , You need to specify which element to focus on , It seems more appropriate for the user to specify this , You can use the following method to specify that the focus moves to an element ( If you don't want to scroll the animation , Add a parameter The default is true Need animation ,false No animation is required ):

<div class="box">
    <div class="item">s</div>
</div>
...
import {
     $tv } from 'ng-tv-focusable';
$tv.requestFocus($tv.getElementByPath('//div[@class="box"]/div[1]'));

As for how to get Element It's not going to unfold anymore ,ng-tv-focus Provides xpath obtain Element:

$tv.requestFocus($tv.getElementByPath('//div[@class="demo"]/div[2]'));//  Give Way demo The next 2 individual div  focusing 

commonly TV When the page at the end is just loaded , The product will require a certain element to be focused , Then you use this api 了 .
Be careful : When entering the page, you want to focus an element , To be in ngAfterViewInit Callback , Otherwise, the focus will not move as you want because the page is not fully loaded .

XPath obtain DOM—getElementByPath(string)

obtain Element Of ,ng-tv-focusable Provides xPath Way to obtain

<body>
    <div class="content">
        <span class="item1">1</span>
        <span class="item2">2</span>
        <span class="item3">3</span>
    </div>
</body>
$tv.getElementByPath('//div[@class="content"]/span[2]');
$tv.getElementByPath($tv.readXPath(document.querySelector('.item2')));
// result : <span class="item2">2</span>
according to DOM Reverse access XPth route —readXPath(el)

ng-tv-focusable according to DOM Reverse access XPth route

<body>
    <div class="content">
        <span class="item1">1</span>
        <span class="item2">2</span>
        <span class="item3">3</span>
    </div>
</body>
$tv.readXPath(document.querySelector('.item2')) 
$tv.readXPath($tv.getElementByPath('//div[@class="content"]/span[2]');) 
// result : "/html/body/div[1]/span[2]"

4. Custom focus movement

The framework has its own set of focus finding algorithms , But sometimes the product requires you to press the right arrow key of the remote control on an element , Let a damned element in the bottom left corner of the screen focus , Then you have to define the focus shift according to the product requirements document .
have access to (up),(right),(down),(left) These properties specify the method to be called when the corresponding direction key of the remote control is pressed , Then you can pass through the method requestFocus Focus the target element , If you call in your own method requestFocus Method , The library will no longer perform the default focus move operation , Otherwise, it will still help you perform the default focus movement .
Example :

<div class="focus-item" [ng-focusable] *ngFor='let in of counter(100) ;let i = index'  (down)="down(i)">
...
  down(index: number) {
    
    if (index === 2) {
     // In the 2 individual div When you press the direction key up , The focus moves directly to the 30 individual div On 
      $tv.requestFocus($tv.getElementByPath('//div[@class="wrapper"]/div[30]'));
    }
  }

 Insert picture description here

5. The form controls , Press the OK key to fill in ,

// formAutofocus: Default true
 $tv.formAutofocus=false;//  Cannot enter 
 $tv.formAutofocus=true;//  You can enter  

 Insert picture description here

All right. , Here should be able to meet all the basic TV The focus needs .

You're still watching ???
ok , I guess you may have some other needs ~

Other

1. Mention initialization

You can set global settings or single page settings

    //  Initialize configuration 
    //  Global configuration can be done in app.component.ts in 
    //1.init initialization (init All configuration items of can be viewed in the last table )
  import {
     $tv } from 'ng-tv-focusable';
  $tv.init({
    
    focusClassName: "on-focus", //  Focus on the elements className ( Default focus)
     KEYS: {
    
      KEY_LEFT: [37, 21], 
      KEY_UP: [38, 19], 
      KEY_RIGHT: [39, 22], 
      KEY_DOWN: [40, 20],
      KEY_ENTER: [40, 20]
     }, //  Custom key value 
     longPressTime: 800, //  Long press response time ( Company : millisecond ), Default 500ms
     distanceToCenter: false //  The focus is always in the middle of the range ,  Default false
    });


// 2. Individual configuration initialization 
  $tv.KEYS=  {
    
    KEY_LEFT: [37, 21], 
    KEY_UP: [38, 19], 
    KEY_RIGHT: [39, 22], 
    KEY_DOWN: [40, 20],
    KEY_ENTER: [40, 20]
  };  
 $tv.longPressTime= 800;
    

Warning : In order not to affect the global configuration , If the page is configured , Remember to reset the page when you destroy it

ngAfterViewInit(){
    
    $tv.findFocusType=0  ;   
}
ngOnDestroy() {
    
    $tv.resetFindFocusType(); //$tv.findFocusType = 1;
}

If you have the need to customize some parameters , You can set these parameters through initialization , Otherwise, initialization is not required .
Here are some descriptions of the parameters :

1. Custom focus class(focusClassName)

You took over projects from other groups , They have put focus This word is used as a common className Yes , And it is used in many places , You must not want to put their code in focus Change to focus1,focus2 What? , So that you can use the library normally focus This name is used as the focus style .
Then go through the initialization focusClassName Property to redefine the focus style name of the library .

2. Custom key value (KEYS- Configure up, down, left and right , Get lost focus ,enter event , Long press event )

The key values of remote controllers from different manufacturers may be different , Some are not in accordance with android Key value , Moreover, the product may require to support both remote control and keyboard operation , At this point, you need to specify the up, down, left and right direction keys , For example, the above configuration KEY_LEFT: [37, 21] It supports the left arrow key on the keyboard and the left direction key on the remote control .

3. Customize the focus finding method (findFocusType,initDis)

findFocusType=1, That is, the default method of finding the nearest focus , In the default mode, you can't actually use initDis Parameters
 Insert picture description here

findFocusType=0,initDis = 49
 Insert picture description here

initDis Why? 49? Just the next one div The distance between the horizontal centerline of and the centerline of the current focus element is greater than initDis value , Think it is not on the same level as the current focus , Now? div2 Horizontal centerline ratio of div1 High 50px, So if you don't want users to div1 When you press the right arrow key, the focus goes to div2 On , You can set the focus mode to linear mode , And pass initDis To control the deviation range .

4. Edge distance (offsetDistance)

When you reach the edge , Give the focus a distance from the edge .

$tv.offsetDistance = 50 //  When you reach the edge, you are away from the edge 50 Pixels 
$tv.offsetDistance = 250 //  When you reach the edge, you are away from the edge 250 Pixels 

Pictured :
 Insert picture description here

2. Partial scrolling (setScrollEl/resetScrollEl)

TV Most end pages scroll through the page , Scroll bar on browser window , If your scrolling content is in a part of the whole page , You need to specify a scrolling container .
**setScrollEl(Element): Set the of scrolling el
**resetScrollEl(): Reset el, That is, scroll the browser's scroll bar
Take a chestnut

<div class="demo">
      <div class="wrapper">
        <div class="focus-item" [ng-focusable]  *ngFor='let in of counter(300) ;let i = index'  :key="index">
          {
    {
     i+1}}
        </div>
      </div>
</div>
<script>
  ...
  ngAfterViewInit() {
    
  	this.$tv.scrollEl=this.$tv.getElementByPath('//div[@class="demo"]');
  }
  ngOnDestroy() {
    
   // To avoid affecting the global configuration, reset the page when destroying it
    $tv.resetScrollEl();
  }
  ...
</script> 
<style>
  .demo {
    
    background:#ccc; margin: 0 auto; width: 400px; height: 400px; 
    position: relative; padding: 20px; overflow: hidden;
    .wrapper {
     width: 800px; }
    .focus-item {
    ...}
  }
</style>

 Insert picture description here

3. Monitor the focus status

(onFocus): Focus of attention
(onBlur): Lose focus

<div class="focus-item" [ng-focusable] *ngFor='let in of counter(105) ;let i = index'  (down)="down(i)"
             (onFocus)="focus(i,$event)" (onBlur)="blur(i)">
          {
    {
     i+1}}
        </div>
...
  focus(index: number, event: any) {
    
    console.log(event.detail.el); // The current element 
    console.log('focus:' + index);
  }

  blur(index: number) {
    
    console.log('blur:' + index);
  }

You don't need to get the current element $event 了 .

4. Long press

(longPress)

<div class="focus-item" [ng-focusable] (longPress)="longPress()">11</div>
...
  longPress() {
    
    console.log('longPress'); //  Long press over 500ms Print it out automatically , It can be done by $tv.init.longPressTime Configure the time 
  }

5. Reset individual configurations

//  Reset to plug-in defaults ,reset+ Property name (), for example 
$tv.resetScrollEl();
$tv.resetFocusClassName();
$tv.resetFindFocusType();
$tv.resetInitDis();
$tv.resetKEYS();
$tv.resetLimitingEl();
...

//  Independent configuration init Every item in it ,$tv. Property name =xx,  as follows :
$tv.focusClassName = XX;
$tv.KEYS = {
    
      KEY_LEFT: [XX,XX,XX],
      KEY_UP: [XX],
      KEY_RIGHT: [XX, XX],
      KEY_DOWN: [XX],
      KEY_ENTER:[XX]
  };
$tv.offsetDistance = XX;
$tv.longPressTime = XX;

6. Clear all configurations and restore to the default configuration of the plug-in

$tv.reset()

7. All configurable items

Initialize configuration init
init(…)

name describe The default value is Whether must
focusableClassName Focusable classname,( Set up focusable You don't need to set this item when ) An empty string no
focusClassName Specify the focus element class name . The default is “ The focus of ” “focus”focusno
initDis Difference value 20no
findFocusType Mobile type ,1: Search nearby 0: A straight line lookup 1no
KEYS Up, down, left and right key values { KEY_LEFT: [37, 21], KEY_UP: [38, 19], KEY_RIGHT: [39, 22], KEY_DOWN: [40, 20], KEY_ENTER:[13, 23] }no
offsetDistance Edge distance 50no
longPressTime Long press response time 500no
distanceToCenter Whether the focus remains in the play in the scrolling area falseno
limitingEl The whole interface , Only limitingEl The focus within can be focused nullno
formAutofocus Whether the form control can input or edit true

Set each item independently

name describe Use
focusableClassName Focusable classname,( Set up focusable You don't need to set this item when )$tv.focusableClassName= XX;
focusClassName Specify the focus element class name . The default is “ The focus of ” “focus”this.$tv.focusClassName = XX;
itemAttrname Focusable attribute name tv.itemAttrname= XX;
Get all the focusable dom attribute console.log($tv.itemAttrname)
findFocusType Mobile type ,1: Search nearby 0: A straight line lookup this.$tv.findFocusType = XX;
initDis Difference value this.$tv.initDis = XX;
KEYS Up, down, left and right key values this.$tv.KEYS = {…};
offsetDistance Edge distance this.$tv.offsetDistance = XX;
longPressTime Long press response time this.$tv.longPressTime = XX;
scrollEl Set scrollable elthis.$tv.scrollEl = XX;
limitingEl The whole interface , Only limitingEl The focus within can be focused this.$tv.limitingEl = XX;
distanceToCenter Whether the focus remains in the play in the scrolling area this.$tv.distanceToCenter = XX;
formAutofocus Whether the form control can input or edit $tv.formAutofocus= XX;
smoothTime Animation time $tv.smoothTime= 200;
spacingTime Animation fluency ( The smaller the number, the smoother the animation , But the more performance is consumed ) , When smoothTime Set to 40 when ,spacingTime=20 and spacingTime=1 The effect is different $tv.spacingTime = 20
scrollSpeedX How many milliseconds to scroll in the horizontal direction when the key is pressed and not lifted , The greater the value, the more energy can be saved , Default 0, Unit millisecond $tv.scrollSpeedX = 200
scrollSpeedY How many milliseconds to scroll in the vertical direction when the key is pressed and not lifted , The greater the value, the more energy can be saved , Default 0, Unit millisecond $tv.scrollSpeedY = 200
scrollSpeed When the key is pressed and not lifted, it is horizontal / How many milliseconds to scroll vertically , The greater the value, the more energy can be saved , Default 0, Unit millisecond $tv.scrollSpeed = 200

scrollEl

name describe type Parameters Whether the parameter is required
$tv.setScrollEl(el) / $tv.scrollEl = el Set the of scrolling elFunction /elElement / nothing yes
$tv.resetScrollEl Reset to browser scrolling Function No parameters

reset

name describe type Parameters
$tv.resetFocusableClassName() Reset focusableClassNameFunction nothing
$tv.resetFocusClassName() Reset focusClassNameFunction nothing
$tv.resetInitDis() Reset initDisFunction nothing
$tv.resetFindFocusType() Reset findFocusTypeFunction nothing
$tv.resetKEYS() Reset KEYSFunction nothing
$tv.resetOffsetDistance() Reset offsetDistanceFunction nothing
$tv.resetLongPressTime() Reset longPressTimeFunction nothing
$tv.resetDistanceToCenter() Reset distanceToCenterFunction nothing
$tv.resetScrollEl() Reset scrollElFunction nothing
$tv.resetLimitingEl() Reset limitingElFunction nothing
$tv.resetFormAutofocus() Reset formAutofocusFunction nothing
$tv.reset()r Reset all Function nothing

other

name describe type Parameters Whether the parameter is required
requestFocus Directly call the specified elFunctionElement: The jump el, bool: Whether animation is enabled Element: yes ,bool: no
getElementByPath Use xPath obtain elFunctionstr yes
readXPath according to DOM Reverse access XPth route Functionel yes

event

name describe
up Move upward ( Configurable KEY_UP Modify key values )
right Move right ( Configurable KEY_RIGHT Modify key values )
down Move down ( Configurable KEY_DOWN Modify key values )
left Move left ( Configurable KEY_LEFT Modify key values )
onFocus Get focus
onBlur Lose focus
longPress Long press ( Configurable KEY_ENTER Modify key values ), $tv.init.longPressTime Long press time can be configured , Default 500ms
click Press enter Can be triggered when click( Configurable KEY_ENTER Modify key values )

Please stamp the source code of the case here

If you have any questions , You can join the group chat and exchange discussion

Q Group 377202993 remarks : tv

原网站

版权声明
本文为[Durian is not delicious]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202280552463527.html