我正在尝试为编辑应用程序实现ctrl-x/v
(不是文本,而是屏幕上显示的内容,所以我不能只使用浏览器复制/粘贴)。
这一切都在使用以下设置:
model.ctrlPressed
设置为True(在KeyCode 17上)但是,当我单击时,我可以按下ctrl按钮几次,然后KeyUp
永远不会传递给Elm并且model.ctrlPressed
卡在错误的状态。
所以我尝试了PageVisibility
库并且 - 在Hidden
订阅 - 我将ctrlPressed设置为False。这有助于我最小化浏览器或切换选项卡,但不是我点击开发控制台时我持有ctrl的实例。
也许这是一个只会在开发中真正发生的错误,但我不想冒这个风险。任何人都有建议解决这个问题?
答案 0 :(得分:0)
你想要document.hasFocus()
。但它不会触发事件,你必须轮询它。
以下是一个示例(run):
port module Main exposing (..)
import Html as H exposing (Html)
import Time
port focusStateRequest : () -> Cmd msg
port focusStateResponse : (Bool -> msg) -> Sub msg
type alias Model =
{ windowFocused : Bool }
type Msg
= FocusStateRequest
| FocusStateResponse Bool
main : Program Never Model Msg
main =
H.program
{ init = init
, update = update
, view = view
, subscriptions = subscriptions
}
init : ( Model, Cmd Msg )
init =
( { windowFocused = True }
, Cmd.none
)
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
FocusStateRequest ->
( model
, focusStateRequest ()
)
FocusStateResponse isFocused ->
-- reset your ctrlPressed here if False
( { model | windowFocused = isFocused }
, Cmd.none
)
view : Model -> Html Msg
view model =
model
|> toString
|> H.text
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.batch
[ Time.every (500 * Time.millisecond) (\_ -> FocusStateRequest)
, focusStateResponse FocusStateResponse
]
在JS方面:
var app = Elm.Main.fullscreen();
app.ports.focusStateRequest.subscribe(function() {
var hasFocus = document.hasFocus();
app.ports.focusStateResponse.send(hasFocus);
});