1667425500
Slate is a Jekyll theme for GitHub Pages. You can preview the theme to see what it looks like, or even use it today.
To use the Slate theme:
Add the following to your site's _config.yml
:
remote_theme: pages-themes/slate@v0.2.0
plugins:
- jekyll-remote-theme # add this line to the plugins list if you already have one
Optionally, if you'd like to preview your site on your computer, add the following to your site's Gemfile
:
gem "github-pages", group: :jekyll_plugins
Slate will respect the following variables, if set in your site's _config.yml
:
title: [The title of your site]
description: [A short description of your site's purpose]
Additionally, you may choose to set the following optional variables:
show_downloads: ["true" or "false" (unquoted) to indicate whether to provide a download URL]
google_analytics: [Your Google Analytics tracking ID]
If you'd like to add your own custom styles:
Create a file called /assets/css/style.scss
in your site
Add the following content to the top of the file, exactly as shown:
---
---
@import "{{ site.theme }}";
Add any custom CSS (or Sass, including imports) you'd like immediately after the @import
line
Note: If you'd like to change the theme's Sass variables, you must set new values before the @import
line in your stylesheet.
If you'd like to change the theme's HTML layout:
favicon
, you can add custom files in your local _includes
folder. The files provided with the theme provide a starting point and are included by the original layout template./_layouts/default.html
in your siteGoogle has released several iterations to their Google Analytics code over the years since this theme was first created. If you would like to take advantage of the latest code, paste it into _includes/head-custom-google-analytics.html
in your Jekyll site.
Templates often rely on URLs supplied by GitHub such as links to your repository or links to download your project. If you'd like to override one or more default URLs:
Look at the template source to determine the name of the variable. It will be in the form of {{ site.github.zip_url }}
.
Specify the URL that you'd like the template to use in your site's _config.yml
. For example, if the variable was site.github.url
, you'd add the following:
github:
zip_url: http://example.com/download.zip
another_url: another value
When your site is built, Jekyll will use the URL you specified, rather than the default one provided by GitHub.
Note: You must remove the site.
prefix, and each variable name (after the github.
) should be indent with two space below github:
.
For more information, see the Jekyll variables documentation.
See the open issues for a list of proposed features (and known issues).
The Slate theme is intended to make it quick and easy for GitHub Pages users to create their first (or 100th) website. The theme should meet the vast majority of users' needs out of the box, erring on the side of simplicity rather than flexibility, and provide users the opportunity to opt-in to additional complexity if they have specific needs or wish to further customize their experience (such as adding custom CSS or modifying the default layout). It should also look great, but that goes without saying.
Interested in contributing to Slate? We'd love your help. Slate is an open source project, built one contribution at a time by users like you. See the CONTRIBUTING file for instructions on how to contribute.
If you'd like to preview the theme locally (for example, in the process of proposing a change):
git clone https://github.com/pages-themes/slate
)cd
into the theme's directoryscript/bootstrap
to install the necessary dependenciesbundle exec jekyll serve
to start the preview serverlocalhost:4000
in your browser to preview the themeThe theme contains a minimal test suite, to ensure a site with the theme would build successfully. To run the tests, simply run script/cibuild
. You'll need to run script/bootstrap
once before the test script will work.
Author: Pages-themes
Source Code: https://github.com/pages-themes/slate
License: CC0-1.0 license
1667390820
Personal blog built with Bootstrap, powered by Jekyll and freely hosted in Github pages.
There are several alternatives to building and deploying the site:
build the site with GitHub Actions which pushes the resulting files (the contents of _site/
or ../sustain-pages/
) to the gh-pages branch. This is the approach that is currently used. See jekyll_build.yml for more details.
generate the site locally (more details below) and push the resulting HTML to a Github repository, that GitHub Pages then host;
build the site with travis-ci (with goodies from jekyll-travis) automatically pushing the generated HTML files to a gh-pages branch.
deploy the static website with Jekyll-compatible hosters, such as https://www.netlify.com/, that allow for deployment from the Github repo and publish the website using CDNs. Netlify has a free starter offer.
For option 2) simply clone this repository (master branch), and then run bundle exec jekyll serve
inside the directory. Upload the resulting _site/
(or ../sustain-pages/
) contents to your repository (master branch if uploading as your personal page (e.g. username.github.io) or gh-pages branch if uploading as a project page (as for the demo).
For option 3) you will need to set up travis-ci for your personal fork. Briefly all you need then is to change your details in _config.yml so that you can push to your github repo. You will also need to generate a secure key to add to your .travis.yml (you can find more info on how to do it in that file). Also make sure you read the documentation from jekyll-travis. This approach has clear advantages in that you simply push your file changes to GitHub and all the HTML files are generated for you and pushed to gh-pages. Also you get to know if everything is still fine with your site builds. Don't hesitate to contact me if you still have any issues (see below about issue tracking).
This install builds well with Ruby v2.6.3 and Jekyll v3.9.0. If you run into any problems please log them on the issue tracker.
Feel free pull-request your patches and fixes.
Home page
Blog page
Post page
Projects page
Profile picture from pexels.
Author: jekyllt
Source Code: https://github.com/jekyllt/sustain
License: MIT license
1667367780
Click Use this template button above for the quickest method of getting started with the Minimal Mistakes Jekyll theme.
Contains basic configuration to get you a site with:
Replace sample content with your own and configure as necessary.
If you have a question about using Jekyll, start a discussion on the Jekyll Forum or StackOverflow. Other resources:
No GitHub API authentication could be found. Some fields may be missing or have incorrect data.
warnings.Author: mmistakes
Source Code: https://github.com/mmistakes/mm-github-pages-starter
1667302221
GitHub Pages can't run custom Jekyll plug-ins so when generating Tables of Contents (TOCs), you're stuck with either a JavaScript solution or using kramdown's {:toc}
option. However, by using {:toc}
, you are forced to have that code next to your actual markdown and you can't place it in a layout. This means every. single. post. will need to have the snippet. If you choose the JavaScript approach, that's perfectly fine but what if JS is disabled on someone's browser or your page is just really long and it becomes inefficient.
Instead, I wrote this solution entirely in Liquid and can be used as an {% include %}
in any website you want, in any layout you want. Want to see it in action? Here are some awesome websites that I know of using this solution :heart:.
For more information regarding how this include works, read the blog post.
Want anchors next to your Jekyll headings without JavaScript or a plug-in?
Check out the sister project over at allejo/jekyll-anchor-headings.
Alright, so how do you use it?
Download the toc.html
file from the latest release or the master branch
Toss that file in your _includes
folder.
Use it in your template layout where you have {{ content }}
which is the HTML rendered from the markdown source with this liquid tag:
{% include toc.html html=content %}
This snippet is highly customizable. Here are the available parameters to change the behavior of the snippet.
Parameter | Type | Default | Description |
---|---|---|---|
html | string | * | the HTML of compiled markdown generated by kramdown in Jekyll |
sanitize | bool | false | when set to true, the headers will be stripped of any HTML in the TOC |
class | string | '' | a CSS class assigned to the TOC; concat multiple classes with '.' |
id | string | '' | an ID to be assigned to the TOC |
h_min | int | 1 | the minimum TOC header level to use; any heading lower than this value will be ignored |
h_max | int | 6 | the maximum TOC header level to use; any heading greater than this value will be ignored |
ordered | bool | false | when set to true, an ordered list will be outputted instead of an unordered list |
item_class | string | '' | add custom class for each list item; has support for %level% placeholder, which is the current heading level |
submenu_class | string | '' | add custom class(es) for each child group of headings; has support for %level% placeholder which is the current "submenu" heading level |
base_url | string | '' | add a base url to the TOC links for when your TOC is on another page than the actual content |
anchor_class | string | '' | add custom class(es) for each anchor element |
skip_no_ids | bool | false | skip headers that do not have an id attribute |
* This is a required parameter
baseurl
has been deprecated since 1.1.0, use base_url
insteadskipNoIDs
has been deprecated since 1.1.0, use skip_no_ids
insteadThe performance impact of this snippet on your site is pretty negligible. The stats below were gotten from Jekyll's --profile
option.
Filename | Count | Bytes | Time
--------------------------------------+-------+------------+--------
# performance on docs.docker.com from ~Feb 2017
_includes/toc.html | 813 | 524.17K | 6.422
# performance on the "Minimal Mistakes" Jekyll theme
_includes/toc.html | 94 | 29.43K | 0.413
Author: Allejo
Source Code: https://github.com/allejo/jekyll-toc
License: BSD-3 or MIT licenses.
1667103240
TL;DR UIPageViewController done properly.
Pageboy requires iOS 9 / tvOS 10; and is compatible with Swift 5.
Pageboy is compatible with Swift Package Manager and can be integrated via Xcode.
Pageboy is also available through CocoaPods:
pod 'Pageboy', '~> 3.7'
Pageboy is also available through Carthage:
github "uias/Pageboy" ~> 3.7
Create an instance of a PageboyViewController
and provide it with a PageboyViewControllerDataSource
.
class PageViewController: PageboyViewController, PageboyViewControllerDataSource {
override func viewDidLoad() {
super.viewDidLoad()
self.dataSource = self
}
}
Implement the PageboyViewControllerDataSource
functions.
func numberOfViewControllers(in pageboyViewController: PageboyViewController) -> Int {
return viewControllers.count
}
func viewController(for pageboyViewController: PageboyViewController,
at index: PageboyViewController.PageIndex) -> UIViewController? {
return viewControllers[index]
}
func defaultPage(for pageboyViewController: PageboyViewController) -> PageboyViewController.Page? {
return nil
}
The delegate functions provided by a PageboyViewController
are much more reliable and useful than what a raw UIPageViewController
provides. You can use them to find out exactly where the current page is, and when it's moved, where it's headed.
About to embark on a transition to a new page.
func pageboyViewController(_ pageboyViewController: PageboyViewController,
willScrollToPageAt index: Int,
direction: PageboyViewController.NavigationDirection,
animated: Bool)
Scrolled to a relative position along the way transitioning to a new page.
func pageboyViewController(_ pageboyViewController: PageboyViewController,
didScrollTo position: CGPoint,
direction: PageboyViewController.NavigationDirection,
animated: Bool)
Successfully completed a scroll transition to a page.
func pageboyViewController(_ pageboyViewController: PageboyViewController,
didScrollToPageAt index: Int,
direction: PageboyViewController.NavigationDirection,
animated: Bool)
Child view controllers have been reloaded.
func pageboyViewController(_ pageboyViewController: PageboyViewController,
didReloadWith currentViewController: UIViewController,
currentPageIndex: PageIndex)
You can navigate programmatically through a PageboyViewController
using scrollToPage()
:
pageViewController.scrollToPage(.next, animated: true)
.isInfiniteScrollEnabled
..isScrollEnabled
.Pageboy provides the ability to insert and delete pages dynamically in the PageboyViewController
.
func insertPage(at index: PageIndex, then updateBehavior: PageUpdateBehavior)
func deletePage(at index: PageIndex, then updateBehavior: PageUpdateBehavior)
This behaves similarly to the insertion of rows in UITableView
, in the fact that you have to update the data source prior to calling any of the update functions.
Example:
let index = 2
viewControllers.insert(UIViewController(), at: index)
pageViewController.insertPage(at: index)
The default behavior after inserting or deleting a page is to scroll to the update location, this however can be configured by passing a PageUpdateBehavior
value other than .scrollToUpdate
.
reloadData()
- Reload the view controllers in the page view controller. (Reloads the data source)..navigationOrientation
- Whether to orientate the pages horizontally or vertically..currentViewController
- The currently visible view controller if it exists..currentPosition
- The exact current relative position of the page view controller..currentIndex
- The index of the currently visible page..parentPageboy
- Access the immediate parent PageboyViewController
from any child view controller.Pageboy also provides custom transition support for animated transitions. This can be customized via the .transition
property on PageboyViewController
.
pageboyViewController.transition = Transition(style: .push, duration: 1.0)
Note: By default this is set to nil
, which uses the standard animation provided by UIPageViewController
.
PageboyAutoScroller
is available to set up timer based automatic scrolling of the PageboyViewController
:
pageboyViewController.autoScroller.enable()
Support for custom intermission duration and other scroll behaviors is also available.
Bug reports and pull requests are welcome on GitHub at https://github.com/uias/Pageboy.
Author: uias
Source Code: https://github.com/uias/Pageboy
License: MIT license
1660203660
A simple CMS to start projects in Laravel containing some modules.
Blog, Pages, Products, Mailbox, Image Gallery, Log Viewer and Users.
Frontend: Blog (httpp://localhost:8000/blog)
Languages: English (default), Portuguese, Spanish and Chinese
Quality
Contributions / Donate
Description | English | Português (Brasil) | Chinese (Help translate) |
---|---|---|---|
1. Installation Guide | EN | PT-BR | |
2. User Guide | EN | PT-BR | |
2.1 Routes | EN | PT-BR | |
2.2 Controllers | EN | PT-BR | |
2.3 Models | EN | PT-BR | |
2.4 Views | EN | PT-BR | |
2.5 Assets | EN | PT-BR | |
2.6 Uploads | EN | PT-BR | |
3. Modules | EN | PT-BR | |
4. Libraries | EN | PT-BR | |
5. Tips | EN | PT-BR |
Contributions
Want to help? How about a pull request or create an [issue] (https://github.com/odirleiborgert/borgert-cms/issues) with improvements.
We recommend cloud Digital Ocean
Earn $10 cloud dollars using our link
Author: Borgert-inc
Source Code: https://github.com/borgert-inc/borgert-cms
License: MIT license
1650896618
another_transformer_page_view
PageTransformer for flutter. Fork from transformer_page_view
import 'package:another_transformer_page_view/another_transformer_page_view.dart';
...
new TransformerPageView(
loop: true,
transformer: new AccordionTransformer(),
itemBuilder: (BuildContext context, int index) {
return new Container(
color: list[index%list.length],
child: new Center(
child: new Text("$index",style: new TextStyle(fontSize: 80.0,color: Colors.white),),
),
);
},
itemCount: 3)
Almost the same as PageView.builder, simplely specify a transformer
to TransformerPageView
, which is a sub class of PageTransformer
See code here
See code here
See code here
See code here
See code here
See code here
Add
another_transformer_page_view:
to your pubspec.yaml ,and run
flutter packages get
in your project's root directory.
Parameter | Default | Description |
---|---|---|
scrollDirection | Axis.horizontal | If Axis.horizontal , the scroll view's children are arranged horizontally in a row instead of vertically in a column. |
loop | false | Set to true to enable continuous loop mode. |
index | none | Index number of initial slide. if not set , it is controlled by the widget itself,otherwise, it is controlled by another widget, which is returned by itemBuilder |
onPageChanged | void onPageChanged(int index) | Called with the new index when the user swiped |
duration | new Duration(milliseconds:300) | The milliseconds of every transaction animation costs |
transformer | none | The most important property of this widget, it returns a transformed widget that based on the widget parameter. If the value is null, a itemBuilder must be specified |
itemCount | none | Number of the total items |
itemBuilder | none | A function that returns a widget based on index,if it's null,a transformer must be specified |
We provide 3 build-in parallaxes, which handle color、image and container
ParallaxColor
ParallaxColor handles the color transform, which controls the color transform from one to another.
ParallaxImage
ParallaxImage handles the image, which speed is slower than the PageView
ParallaxContainer
ParallaxContainer handles the text or other staff, which speed is faster than the PageView
3 build-in parallaxes are all used in subclass of PageTransform
,group these parallaxes together, we can create very cool things.
Inspired by page-transformer, and we have an easier way to create this.
See code here
Run this command:
With Flutter:
$ flutter pub add another_transformer_page_view
This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get
):
dependencies:
another_transformer_page_view: ^1.1.0
Alternatively, your editor might support flutter pub get
. Check the docs for your editor to learn more.
Now in your Dart code, you can use:
import 'package:another_transformer_page_view/another_transformer_page_view.dart';
import 'package:example/buildin_transformers.dart';
import 'package:example/images.dart';
import 'package:example/screens/product_list_view.dart';
import 'package:example/welcome.dart';
import 'package:example/zero.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:another_transformer_page_view/another_transformer_page_view.dart';
import 'dart:math' as math;
void main() => runApp(const MyApp());
List<Color> list = [Colors.yellow, Colors.green, Colors.blue];
List<String> images = [
'assets/Hepburn2.jpg',
'assets/Hepburn5.jpg',
'assets/Hepburn4.jpg',
];
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, this.title}) : super(key: key);
final String? title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
IndexController? _controller;
final List<String> _types = [
'AccordionTransformer',
'ThreeDTransformer',
'ScaleAndFadeTransformer',
'ZoomInPageTransformer',
'ZoomOutPageTransformer',
'DeepthPageTransformer'
];
String? _type;
FixedExtentScrollController? controller;
int? _index = 0;
double _viewportFraction = 1.0;
@override
void initState() {
_controller = IndexController();
_type = 'AccordionTransformer';
controller = FixedExtentScrollController();
super.initState();
}
PageTransformer getTransformer() {
switch (_type) {
case 'AccordionTransformer':
return AccordionTransformer();
case 'ThreeDTransformer':
return ThreeDTransformer();
case 'ScaleAndFadeTransformer':
return ScaleAndFadeTransformer();
case 'ZoomInPageTransformer':
return ZoomInPageTransformer();
case 'ZoomOutPageTransformer':
return ZoomOutPageTransformer();
case 'DeepthPageTransformer':
return DepthPageTransformer();
}
throw Exception('Not a type');
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title!),
actions: <Widget>[
InkWell(
onTap: () {
Navigator.push(context, MaterialPageRoute(builder: (c) {
return const ProductListView();
}));
},
child: const Text('route'),
)
],
),
body: Column(
children: <Widget>[
Wrap(
children: <Widget>[
ElevatedButton(
onPressed: () {
_controller!.move(math.Random().nextInt(5));
},
child: const Text('Random'),
),
ElevatedButton(
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(builder: (b) {
return Scaffold(
appBar: AppBar(
title: const Text('images'),
),
body: const ImageTest(),
);
}));
},
child: const Text('Image'),
),
ElevatedButton(
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(builder: (b) {
return Scaffold(
appBar: AppBar(
title: const Text('welcome'),
),
body: Welcome(0));
}));
},
child: const Text('Welcome'),
),
ElevatedButton(
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(builder: (b) {
return const Zero();
}));
},
child: const Text('Zero'),
),
],
),
Row(
children: <Widget>[
ElevatedButton(
onPressed: () {
_controller!.previous();
},
child: const Text('Preious'),
),
const SizedBox(
width: 8.0,
),
ElevatedButton(
onPressed: () {
_controller!.next();
},
child: const Text('Next'),
),
const SizedBox(
width: 8.0,
),
ElevatedButton(
onPressed: () {
showModalBottomSheet(
context: context,
builder: (_) {
return CupertinoPicker(
scrollController: controller,
itemExtent: 30.0,
onSelectedItemChanged: (int index) {
setState(() {
controller = FixedExtentScrollController(
initialItem: index);
_type = _types[index];
if (_type == 'ScaleAndFadeTransformer') {
_viewportFraction = 0.8;
} else {
_viewportFraction = 1.0;
}
});
},
children: _types.map((t) => Text(t)).toList());
});
},
child: const Text('Animation'),
),
],
),
Expanded(
child: SizedBox(
child: TransformerPageView(
loop: false,
index: _index,
viewportFraction: _viewportFraction,
controller: _controller,
transformer: getTransformer(),
onPageChanged: (int? index) {
setState(() {
_index = index;
});
},
itemBuilder: (BuildContext context, int index) {
return Image.asset(
images[index],
fit: BoxFit.fill,
);
},
itemCount: 3),
))
],
),
);
}
}
Download Details:
Author: juliansteenbakker
Source Code: https://github.com/juliansteenbakker/another_transformer_page_v
1645020080
データは常に視覚的に認識しやすくなっています。データの視覚化により、一定期間の傾向を確認したり、さまざまなデータセットを比較したり、合計、ハイライト、安値などを簡単に確認したりできます。
ソフトウェアでデータを視覚化する最も一般的な方法の1つは、分析パネルを使用することです。ほとんどのバックエンドシステムで、訪問者のエンゲージメントデータ、ユーザーアクティビティの指標、サーバーの統計情報、その他の指標を表示するためにそれらを確認しています。
この記事では、Svelteで分析ダッシュボードを構築します。コンポーネントを作成し、データをコードから分離し、ロジックを実装する方法に焦点を当てます。
参考までに、これが最終プロジェクトのソースコードです。
3つの異なるタイプのチャートを介して統計を表示するサーバー統計ダッシュボードを作成します。折れ線グラフが1つ、棒グラフが2つ、ドーナツグラフが3つあります。
折れ線グラフには、6か月間の訪問者の統計が表示されます。棒グラフには、最も訪問されたページと、サイトにトラフィックをもたらす上位のリファラーが表示されます。最後に、ドーナツチャートには、ユーザーOS、ブラウザー、およびデバイスの使用状況が表示されます。
分析ダッシュボードのレイアウトは、以下のワイヤーフレームに示されています。
新しいSvelteプロジェクトの足場を作るために、degitを使用します。ターミナルを開き、次のコマンドを実行しますnpx degit sveltejs/template svelte-analytics
。
その後、を実行して、作業ディレクトリを新しく作成したフォルダに変更しますcd svelte-analytics
。次に、コマンドを実行して、Svelteプロジェクトが機能するために必要なすべての依存関係をインストールしますnpm install
。
npm run dev
次に、ターミナルで実行し、ブラウザでhttp:// localhost:8080に移動します。次のようなSvelteプロジェクトプレビューが表示されます。
また、外部のnpmライブラリChart.jsをインストールします。これは、モダンな外観のインタラクティブなグラフを作成するのに役立ちます。npm install chart.js
ターミナルがパッケージのインストールを完了するまで実行して待ちます。
通常、データはデータベースからフェッチされます。分析コンポーネント自体の作成方法に焦点を当てるため、サンプルデータを別のファイルに作成し、必要に応じてインポートします。
フォルダに移動し、insidesrc
という名前の新しいファイルを作成します。data.js
次に、次のコードを必ず含めてください。
const colors = ["tomato", "gold", "lime green"];
export const visits = {
title: "Unique visitors",
type: "line",
backgroundColor: colors[0],
labels: ["January", "February", "March", "April", "May", "June"],
data: [275, 254, 261, 279, 262, 268]
};
export const pages = {
title: "Top pages",
type: "bar",
backgroundColor: colors[0],
labels: ["/gallery", "/blog", "/about", "/pricing", "/contact"],
data: [220, 176, 132, 88, 44]
};
export const referrers = {
title: "Top referrers",
type: "bar",
backgroundColor: colors[0],
labels: ["google", "twitter", "facebook", "linkedin", "dev.to"],
data: [23, 14, 6, 5, 2]
};
export const os = {
title: "OS usage",
type: "doughnut",
backgroundColor: colors,
labels: ["Win", "MacOS", "Linux"],
data: [400, 100, 200]
};
export const browsers = {
title: "Browser usage",
type: "doughnut",
backgroundColor: colors,
labels: ["Chrome", "Firefox", "Safari"],
data: [240, 100, 60]
};
export const devices = {
title: "Device usage",
type: "doughnut",
backgroundColor: colors,
labels: ["Phone", "Desktop"],
data: [220, 260]
};
最初に、チャートの背景色を定義する色配列を作成しました。事前定義されたHTMLカラー名「トマト」、「ゴールド」、「ライムグリーン」を使用しましたが、特定のプロジェクトに合わせて任意のカスタムカラーパレットに調整できます。
次に、チャートのタイトル、タイプ、背景色、ラベル、およびデータで構成される、チャートごとに個別のオブジェクトを作成しました。export
後でメインファイルにインポートしApp.svelte
て小道具として渡すことができるように、各変数にステートメントを使用しました。
データを視覚化するグラフコンポーネントを作成するcomponents
には、プロジェクトルートで呼び出される新しいフォルダーを作成し、そのChart.svelte
中に呼び出される新しいファイルを作成します。次に、新しく作成したファイルに次のコードを追加します。
<script>
import Chart from "chart.js/auto";
import { onMount } from "svelte";
let ctx;
let chartCanvas;
export let type;
export let labels;
export let data;
export let title;
export let backgroundColor;
export let showLegends = false;
onMount(async () => {
ctx = chartCanvas.getContext("2d");
const chart = new Chart(ctx, {
type,
data: {
labels,
datasets: [
{
backgroundColor,
data
}
]
},
options: {
plugins: {
title: {
display: true,
text: title
},
legend: {
display: showLegends,
position: "bottom"
}
}
}
});
});
</script>
<canvas bind:this={chartCanvas}></canvas>
まず、 Chart.jsライブラリChart
からコンポーネントをインポートしました。次に、コンポーネントが最初にDOMにレンダリングされた後に実行される組み込み関数をSvelteからインポートしました。onMount
次に、グラフ自体のコンテキスト変数とキャンバス変数(ctx
および)を作成し、コンポーネントをメインファイルchartCanvas
にインポートするときに渡す必要のある値の変数を作成しました。ChartApp.svelte
最後に、onMount
関数内で、すべてのグラフを作成するために使用される、、、およびパラメーターtype
をdata
作成しました。コンポーネントを画面にoptions
レンダリングするために、要素にバインドしました。ChartchartCanvascanvas
次に、データとグラフのコンポーネントをまとめましょう。src
フォルダに移動してを開きApp.js
ます。次のコードを追加します。
<script>
import Chart from "../components/Chart.svelte";
import { visits, pages, referrers, os, browsers, devices } from "./data.js";
</script>
<main>
<h3>Monthly Visitors</h3>
<section>
<Chart {...visits}/>
</section>
<h3>Top pages and Referrers</h3>
<div id="pages">
<section>
<Chart {...pages}/>
</section>
<section>
<Chart {...referrers}/>
</section>
</div>
<h3>OS, Browsers and Devices</h3>
<div id="devices">
<section>
<Chart {...os} showLegends={true}/>
</section>
<section>
<Chart {...browsers} showLegends={true}/>
</section>
<section>
<Chart {...devices} showLegends={true}/>
</section>
</div>
</main>
Chart
最初に、コンポーネントと以前に作成したすべてのデータオブジェクトをインポートしました。export
オブジェクト変数ごとにステートメントを使用したため、すべてを1行で簡単にインポートできました。
次に、main
アプリ全体のラッパーを使用し、ダッシュボードセクションのタイトルを作成し、セクションh3
のグリッドレイアウトラッパーを使用しました。これには、それぞれ2つと3つのチャートが含まれます。pagesdevices
次に、計画されたすべてのChart
コンポーネントを含めました。Chart
各コンポーネントをsection
タグでラップしていることに注意してください。これは、Chart.jsが幅を定義し、さまざまな画面幅で表示した場合の応答性を調整するために親要素を必要とするためです。
最後に、JavaScriptスプレッド構文Chart
を使用して、コンポーネントに必要な小道具を渡しました。最後の3つのグラフでは、凡例も表示されるため、そのオプションを有効にする追加の小道具が追加されました。
次に、要素が期待どおりに表示されるように、いくつかのスタイルシートルールをアプリに追加しましょう。ファイルに残っている間にApp.svelte
、以前に作成したScriptタグとHTMLの下に次のコードを追加します。
<style>
@import url("https://fonts.googleapis.com/css2?family=Montserrat&display=swap");
:global(*) {
margin: 0;
padding: 0;
}
:global(body) {
background-color: rgb(255, 137, 116);
font-family: "Montserrat", sans-serif;
}
main {
max-width: 800px;
min-height: 100vh;
margin: 0 auto;
padding: 0 20px;
background-color: rgb(245, 245, 245);
}
h3 {
padding: 20px 0;
}
section {
min-width: 100%;
background-color: white;
border-radius: 10px;
}
#pages {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 20px;
}
#devices {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 20px;
padding-bottom: 20px;
}
@media only screen and (max-width: 560px) {
#pages,
#devices {
grid-template-columns: 1fr;
}
}
</style>
まず、Montserratフォントをインポートし、アプリ全体で使用するように設定しました。また、パディングとマージンにリセットルールを使用したため、ダッシュボードはさまざまなブラウザーで同じように表示されます。ページの背景色をオレンジ色に設定しました。
ダッシュボード自体については、幅が超えないように設定800px
し、ビューポートの中央に配置しました。また、いくつかのパディングを使用し、背景色をライトグレーに設定しました。
セクションタイトルに上下のパディングを設定し、セクション自体の幅、背景色、境界線の半径を定義しました。
複数のグラフを含むラッパーの場合、レイアウトをグリッドに設定し、を使用します。これにより、メインラッパーの使用可能な幅が、間隔を空けgrid-template-columns
て同じ幅の2つまたは3つの列に分割されます。20px
最後に、両方のグリッドラッパーのCSSメディアルールを作成しました。画面幅がそれ以下の場合560px
、とのグリッドレイアウトは1つの列pages
にdevices
切り替わります。つまり、含まれているすべてのグラフが互いに真下に表示されます。
最後にすべきことは、アプリをテストすることです。開発サーバーがまだ実行されているかどうかを確認します。そうでない場合は、npm run dev
再度実行して、ブラウザでhttp:// localhost:8080にアクセスします。これで、次のような最終的なダッシュボードが表示されます。
このチュートリアルでは、再利用可能なチャートコンポーネントを作成する方法を学びました。分析ダッシュボードを作成するプロセス中に、データをコードから分離し、グラフのタイプ、データ、およびオプションをインポート、エクスポート、および渡す方法を学びました。
このテンプレートを自由に適応させて、独自のプロジェクトで使用してください。また、必要に応じて、データをデータベースに移動してバックエンドを実装し、プロジェクトの使用時にデータが更新されるようにすることもできます。
うまくいけば、あなたはある程度の知識を習得し、これからはSvelteでの作業中にダッシュボードをより快適に実装できるようになるでしょう。
リンク:https ://blog.logrocket.com/building-analytic-dashboards-svelte/
1644998400
Los datos siempre han sido más fáciles de percibir visualmente. La visualización de datos nos permite ver tendencias durante períodos de tiempo, nos permite comparar diferentes conjuntos de datos y facilita ver los totales, los puntos destacados, los mínimos, etc.
Una de las formas más comunes de visualizar datos en el software es a través de paneles de análisis. Los vemos en la mayoría de los sistemas de back-end para mostrar los datos de participación de los visitantes, las métricas de actividad del usuario, las estadísticas del servidor y otras métricas.
En este artículo, crearemos un tablero de análisis en Svelte . Nos centraremos en cómo crear los componentes, separar los datos del código e implementar la lógica.
Como referencia, aquí está el código fuente del proyecto final.
Crearemos un tablero de estadísticas del servidor que mostrará estadísticas a través de tres tipos diferentes de gráficos. Habrá un gráfico de líneas, dos gráficos de barras y tres gráficos de anillos.
El gráfico de líneas mostrará las estadísticas de visitantes a lo largo de seis meses. Los gráficos de barras mostrarán las páginas más visitadas, así como las principales referencias que traen tráfico al sitio. Finalmente, los gráficos de anillos mostrarán los usos del sistema operativo, el navegador y el dispositivo del usuario.
El diseño del tablero de análisis se muestra en la siguiente estructura:
Para montar un nuevo proyecto Svelte, usaremos degit . Abre tu terminal y ejecuta el siguiente comando: npx degit sveltejs/template svelte-analytics
.
Después, cambie su directorio de trabajo a la carpeta recién creada ejecutando cd svelte-analytics
. Luego instale todas las dependencias necesarias para que el proyecto Svelte funcione ejecutando el comando npm install
.
Ahora ejecútelo npm run dev
en su terminal y navegue hasta http://localhost:8080 en su navegador. Se le debe presentar una vista previa del proyecto Svelte que se ve así:
También instalaremos la biblioteca npm externa Chart.js , que nos ayudará a crear gráficos interactivos y de aspecto moderno. Ejecute npm install chart.js
y espere mientras la terminal termina de instalar el paquete.
Normalmente, los datos se obtendrían de la base de datos. Debido a que nos centraremos en cómo crear los propios componentes analíticos, crearemos datos de muestra en un archivo separado y luego los importaremos donde sea necesario.
Navegue a la src
carpeta y cree un nuevo archivo llamado data.js
dentro. A continuación, asegúrese de incluir el siguiente código en él:
const colors = ["tomato", "gold", "lime green"];
export const visits = {
title: "Unique visitors",
type: "line",
backgroundColor: colors[0],
labels: ["January", "February", "March", "April", "May", "June"],
data: [275, 254, 261, 279, 262, 268]
};
export const pages = {
title: "Top pages",
type: "bar",
backgroundColor: colors[0],
labels: ["/gallery", "/blog", "/about", "/pricing", "/contact"],
data: [220, 176, 132, 88, 44]
};
export const referrers = {
title: "Top referrers",
type: "bar",
backgroundColor: colors[0],
labels: ["google", "twitter", "facebook", "linkedin", "dev.to"],
data: [23, 14, 6, 5, 2]
};
export const os = {
title: "OS usage",
type: "doughnut",
backgroundColor: colors,
labels: ["Win", "MacOS", "Linux"],
data: [400, 100, 200]
};
export const browsers = {
title: "Browser usage",
type: "doughnut",
backgroundColor: colors,
labels: ["Chrome", "Firefox", "Safari"],
data: [240, 100, 60]
};
export const devices = {
title: "Device usage",
type: "doughnut",
backgroundColor: colors,
labels: ["Phone", "Desktop"],
data: [220, 260]
};
Primero creamos una matriz de colores que definirá el color de fondo de los gráficos. Usamos nombres de color HTML predefinidos "tomate", "gold" y "lime green", pero puede ajustarlos a cualquier paleta de colores personalizada que desee para su proyecto específico.
Luego, creamos un objeto separado para cada gráfico que consiste en el título, el tipo, el color de fondo, las etiquetas y los datos del gráfico. Usamos export
declaraciones para cada variable para que luego podamos importarlas al archivo principal App.svelte
y pasarlas como accesorios.
Para crear un componente de gráfico que visualizará nuestros datos, cree una nueva carpeta llamada components
en la raíz del proyecto y cree un nuevo archivo llamado Chart.svelte
dentro de ella. Ahora, agregue el siguiente código en el archivo recién creado:
<script>
import Chart from "chart.js/auto";
import { onMount } from "svelte";
let ctx;
let chartCanvas;
export let type;
export let labels;
export let data;
export let title;
export let backgroundColor;
export let showLegends = false;
onMount(async () => {
ctx = chartCanvas.getContext("2d");
const chart = new Chart(ctx, {
type,
data: {
labels,
datasets: [
{
backgroundColor,
data
}
]
},
options: {
plugins: {
title: {
display: true,
text: title
},
legend: {
display: showLegends,
position: "bottom"
}
}
}
});
});
</script>
<canvas bind:this={chartCanvas}></canvas>
Primero importamos el Chart
componente de la biblioteca Chart.js . Luego, importamos la onMount
función integrada de Svelte , que se ejecuta después de que el componente se representa por primera vez en el DOM.
Luego, creamos variables de contexto y lienzo ( ctx
y chartCanvas
) para el gráfico en sí y creamos variables para los valores que necesitaremos pasar cuando importemos el Chart
componente en el App.svelte
archivo principal.
Finalmente, dentro de las onMount
funciones, creamos type
, data
y options
parámetros que se usarán para construir todos los gráficos. Para representar el Chart
componente en la pantalla, lo vinculamos chartCanvas
al canvas
elemento.
Ahora pongamos los datos y los componentes del gráfico juntos. Navegue hasta la src
carpeta y abra App.js
. Añádele el siguiente código:
<script>
import Chart from "../components/Chart.svelte";
import { visits, pages, referrers, os, browsers, devices } from "./data.js";
</script>
<main>
<h3>Monthly Visitors</h3>
<section>
<Chart {...visits}/>
</section>
<h3>Top pages and Referrers</h3>
<div id="pages">
<section>
<Chart {...pages}/>
</section>
<section>
<Chart {...referrers}/>
</section>
</div>
<h3>OS, Browsers and Devices</h3>
<div id="devices">
<section>
<Chart {...os} showLegends={true}/>
</section>
<section>
<Chart {...browsers} showLegends={true}/>
</section>
<section>
<Chart {...devices} showLegends={true}/>
</section>
</div>
</main>
Primero importamos el Chart
componente y todos los objetos de datos que creamos anteriormente. Debido a que usamos export
declaraciones para cada variable de objeto, fue fácil importar todo en una sola línea.
A continuación, usamos un main
envoltorio alrededor de toda la aplicación, creamos los h3
títulos para las secciones del tablero y usamos envoltorios de diseño de cuadrícula para las secciones pages
y devices
, que incluirán dos y tres gráficos, respectivamente.
Luego incluimos todos los Chart
componentes planificados. Observe que envolvimos cada Chart
componente dentro de una section
etiqueta. Esto se debe a que Chart.js necesita un elemento principal para definir el ancho y ajustar la capacidad de respuesta cuando se ve en diferentes anchos de pantalla.
Finalmente, usamos una sintaxis extendida de JavaScript para pasar los accesorios necesarios para los Chart
componentes. Para los últimos tres gráficos, también mostraremos las leyendas, por lo que se agregó un accesorio adicional que habilitó esa opción.
Ahora agreguemos algunas reglas de hoja de estilo a nuestra aplicación para que los elementos se muestren como se esperaba. Mientras aún está en el App.svelte
archivo, agregue el siguiente código debajo de las etiquetas Script y HTML escritas anteriormente:
<style>
@import url("https://fonts.googleapis.com/css2?family=Montserrat&display=swap");
:global(*) {
margin: 0;
padding: 0;
}
:global(body) {
background-color: rgb(255, 137, 116);
font-family: "Montserrat", sans-serif;
}
main {
max-width: 800px;
min-height: 100vh;
margin: 0 auto;
padding: 0 20px;
background-color: rgb(245, 245, 245);
}
h3 {
padding: 20px 0;
}
section {
min-width: 100%;
background-color: white;
border-radius: 10px;
}
#pages {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 20px;
}
#devices {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 20px;
padding-bottom: 20px;
}
@media only screen and (max-width: 560px) {
#pages,
#devices {
grid-template-columns: 1fr;
}
}
</style>
Primero, importamos la fuente Montserrat y la configuramos para que se usara en toda la aplicación. También usamos reglas de reinicio para el relleno y el margen, por lo que el tablero se ve igual en los diferentes navegadores. Configuramos el color de fondo de la página para que sea naranja.
Para el tablero en sí, configuramos el ancho para que nunca exceda 800px
y lo centramos en la ventana gráfica. También usamos algo de relleno y configuramos el color de fondo en gris claro.
Establecimos un relleno superior e inferior para los títulos de las secciones, y también definimos el ancho, el color de fondo y el radio del borde para las secciones mismas.
Para los envoltorios que incluirán múltiples gráficos, configuramos el diseño para que sea una cuadrícula y usamos grid-template-columns
, que divide el ancho disponible del envoltorio principal en dos o tres columnas con el mismo ancho, con un 20px
espacio entre ellas.
Finalmente, creamos una regla de medios CSS para ambos envoltorios de cuadrícula. Si el ancho de la pantalla es 560px
o menor, el diseño de la cuadrícula pages
cambia devices
a una columna, lo que significa que todos los gráficos incluidos se muestran directamente uno debajo del otro.
Lo último que queda por hacer es probar la aplicación. Compruebe si el servidor de desarrollo todavía se está ejecutando. Si no es así, npm run dev
vuelva a ejecutar y visite http://localhost:8080 en su navegador. Ahora debería aparecer el tablero final, que se ve así:
En este tutorial, aprendimos cómo crear componentes de gráficos reutilizables. Durante el proceso de creación del panel de análisis, aprendimos a separar los datos del código y cómo importar, exportar y pasar el tipo, los datos y las opciones de los gráficos.
Siéntete libre de adaptar y usar esta plantilla en tus propios proyectos. Además, si lo desea, puede mover los datos a la base de datos e implementar el backend para que los datos se actualicen cuando se utiliza el proyecto.
Con suerte, adquirió algunos conocimientos y, a partir de ahora, se sentirá más cómodo implementando paneles mientras trabaja con Svelte.
Enlace: https://blog.logrocket.com/building-analytic-dashboards-svelte/
1625681940
In this video tutorial, we create the bottom navigation bar for our application and create empty pages for our items in the bottom navigation.
Link to source code: https://github.com/Flutter-Zone/Flutter-Zone-Food-App
Design Inspirations:
https://www.behance.net/gallery/74505097/Foodiee-Food-ordering-App-UI-kit?tracking_source=search|food app
Keep calm and watch the tutorial.
#food delivery app #navigation and pages #navigation #pages