瀏覽代碼

Merge pull request #1689 from iljalukin/2.0

activate selected tab after page reload
Jiang Qinghua 3 年之前
父節點
當前提交
e2bb1ab806
共有 1 個文件被更改,包括 25 次插入2 次删除
  1. 25 2
      src/Widgets/Tab.php

+ 25 - 2
src/Widgets/Tab.php

@@ -2,6 +2,7 @@
 
 namespace Dcat\Admin\Widgets;
 
+use Dcat\Admin\Admin;
 use Illuminate\Contracts\Support\Renderable;
 
 class Tab extends Widget
@@ -33,12 +34,13 @@ class Tab extends Widget
      * @param  string  $title
      * @param  string|Renderable  $content
      * @param  bool  $active
+     * @param  string|null  $id
      * @return $this
      */
-    public function add($title, $content, $active = false)
+    public function add($title, $content, $active = false, $id = null)
     {
         $this->data['tabs'][] = [
-            'id'      => mt_rand(),
+            'id'      => $id ?: mt_rand(),
             'title'   => $title,
             'content' => $this->toString($this->formatRenderable($content)),
             'type'    => static::TYPE_CONTENT,
@@ -169,6 +171,27 @@ class Tab extends Widget
             ['attributes' => $this->formatHtmlAttributes()]
         );
 
+        $this->setupScript();
+
         return view($this->view, $data)->render();
     }
+
+    /**
+     * Setup script.
+     */
+    protected function setupScript()
+    {
+        $script = <<<'SCRIPT'
+var hash = document.location.hash;
+if (hash) {
+    $('.nav-tabs a[href="' + hash + '"]').tab('show');
+}
+
+// Change hash for page-reload
+$('.nav-tabs a').on('shown.bs.tab', function (e) {
+    history.pushState(null,null, e.target.hash);
+});
+SCRIPT;
+        Admin::script($script);
+    }
 }