Skip to content
This repository has been archived by the owner on Jul 6, 2021. It is now read-only.

Commit

Permalink
feat: allow to change locale globally
Browse files Browse the repository at this point in the history
  • Loading branch information
egoist committed Mar 19, 2019
1 parent aeb3d55 commit a6bac94
Show file tree
Hide file tree
Showing 7 changed files with 122 additions and 79 deletions.
51 changes: 32 additions & 19 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,18 @@ CDN: [UNPKG](https://unpkg.com/vue-timeago/dist/) | [jsDelivr](https://cdn.jsdel
For usages on version 4, please check out [this branch](https://github.com/egoist/vue-timeago/tree/4).

```js
import VueTimeago from 'vue-timeago'
import VueTimeago from "vue-timeago";

Vue.use(VueTimeago, {
name: 'Timeago', // Component name, `Timeago` by default
locale: 'en', // Default locale
name: "Timeago", // Component name, `Timeago` by default
locale: "en", // Default locale
// We use `date-fns` under the hood
// So you can use all locales from it
locales: {
'zh-CN': require('date-fns/locale/zh_cn'),
'ja': require('date-fns/locale/ja'),
"zh-CN": require("date-fns/locale/zh_cn"),
ja: require("date-fns/locale/ja")
}
})
});
```

Then in your lovely component:
Expand All @@ -49,53 +49,53 @@ Then in your lovely component:
## Plugin options

```js
Vue.use(VueTimeago, pluginOptions)
Vue.use(VueTimeago, pluginOptions);
```

### locales

- __Type__: `{ [localeName: string]: any }`
- **Type**: `{ [localeName: string]: any }`

An object of locales.

### locale

- __Type__: `string`
- **Type**: `string`

The default locale name.

### converter

- __Type__: `(date, locale, converterOptions) => string`
- **Type**: `(date, locale, converterOptions) => string`

A `converter` that formats regular dates in `xxx ago` or `in xxx` style.

Check out our [default converter](./src/converter.js) which uses [date-fns/distance_in_words_to_now](https://date-fns.org/v1.29.0/docs/distanceInWordsToNow) under the hood.

### converterOptions

- __Type__: `Object`
- **Type**: `Object`

Provide an object which will be available as argument `converterOptions` in the `converter` we mentioned above.

Our default converter supports most options that [date-fns/distance_in_words_to_now](https://date-fns.org/v1.29.0/docs/distanceInWordsToNow) library supports, namely:

- __includeSeconds__: (default: `false`) distances less than a minute are more detailed
- __addSuffix__: (default: `true`) result specifies if the second date is earlier or later than the first
- **includeSeconds**: (default: `false`) distances less than a minute are more detailed
- **addSuffix**: (default: `true`) result specifies if the second date is earlier or later than the first

## props

### datetime

- __Type__: `Date` `string` `number`
- __Required__: `true`
- **Type**: `Date` `string` `number`
- **Required**: `true`

The datetime to be formatted .

### autoUpdate

- __Type__: `number` `boolean`
- __Default__: `false`
- **Type**: `number` `boolean`
- **Default**: `false`

The period to update the component, in **seconds**.

Expand All @@ -115,6 +115,21 @@ Just like the `converter` option in the plugin options, but this could override

Just like the `converterOptions` option in the plugin options, but this could override the global one.

## Recipes

### Update Locale Globally

```js
Vue.use(VueTimeago, {
locale: "en",
locales: {
"zh-CN": require("date-fns/locale/zh_cn")
}
});
```

In your components you can use `this.$timeago.locale` to access the global locale, in this case it's `en`, the `<timeago>` component will get updated when you set it to another valid locale, e.g. `this.$timeago.locale = 'zh-CN'`.

## What about the good old [vue-timeago v3](https://github.com/egoist/vue-timeago/tree/3)?

The older version (700 bytes gzipped) is much smaller than the current version (2.8kB gzipped) that uses [`date-fns`](https://date-fns.org/).
Expand All @@ -134,5 +149,3 @@ yarn build
## License

MIT © [EGOIST](https://github.com/egoist)


38 changes: 22 additions & 16 deletions bili.config.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,35 @@
import { Config } from 'bili'
import { Config } from "bili";

const config: Config = {
input: 'src/index.js',
input: "src/index.js",
output: {
moduleName: 'VueTimeago',
format: ['esm', 'umd', 'cjs'],
moduleName: "VueTimeago",
format: ["esm", "umd", "cjs"],
fileName({ format }, defaultFileName) {
if (format === 'cjs') {
return 'vue-timeago.cjs.js'
if (format === "cjs") {
return "vue-timeago.cjs.js";
}
if (format === 'umd') {
return 'vue-timeago.js'
if (format === "umd") {
return "vue-timeago.js";
}
if (format === 'esm') {
return 'vue-timeago.es.js'
if (format === "esm") {
return "vue-timeago.es.js";
}
return defaultFileName
return defaultFileName;
}
},
babel: {
minimal: true
},
extendConfig(config, { format }) {
if (format === 'umd') {
config.output.minify = true
if (format === "umd") {
config.output.minify = true;
config.env = Object.assign({}, config.env, {
NODE_ENV: "production"
});
}
return config
return config;
}
}
};

export default config
export default config;
8 changes: 3 additions & 5 deletions example/app.vue
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
<template>
<div id="app">
<div class="header">
<select v-model="locale">
<option value="en">en</option>
<select v-model="$timeago.locale">
<option
v-for="name of localeNames"
:key="name"
Expand All @@ -13,10 +12,10 @@
</div>
<div class="main">
<input type="text" v-model="datetime1">
<timeago :datetime="datetime1" :locale="locale" :converter="converter" />
<timeago :datetime="datetime1" :converter="converter" />
<hr>
<input type="text" v-model="datetime2">
<timeago :datetime="datetime2" :locale="locale" :autoUpdate="autoUpdate ? 1 : 0" :converterOptions="{ includeSeconds: true }" /> <input type="checkbox" v-model="autoUpdate"> Auto Update in every second
<timeago :datetime="datetime2" :autoUpdate="autoUpdate ? 1 : 0" :converterOptions="{ includeSeconds: true }" /> <input type="checkbox" v-model="autoUpdate"> Auto Update in every second
</div>
</div>
</template>
Expand All @@ -29,7 +28,6 @@ export default {
data() {
return {
locale: 'en',
autoUpdate: false,
datetime1: '2022-02-12',
datetime2: format(new Date(), 'YYYY-MM-DD HH:mm:ss'),
Expand Down
1 change: 1 addition & 0 deletions example/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ r.keys().forEach(v => {
})

Vue.use(Timeago, {
locale: 'en',
locales,
converter
})
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
"filter"
],
"devDependencies": {
"bili": "^4.5.2",
"bili": "^4.5.3",
"commitizen": "^3.0.7",
"cz-conventional-changelog": "^2.1.0",
"eslint-config-prettier": "^4.1.0",
Expand Down
93 changes: 59 additions & 34 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import defaultConverter from './converter'
import defaultConverter from "./converter";

export const createTimeago = (opts = {}) => {
const locales = opts.locales || {}
const name = opts.name || 'Timeago'
const locales = opts.locales || {};
const name = opts.name || "Timeago";

return {
name,
Expand Down Expand Up @@ -31,94 +31,119 @@ export const createTimeago = (opts = {}) => {
data() {
return {
timeago: this.getTimeago()
};
},

computed: {
localeName() {
return this.locale || this.$timeago.locale;
}
},

mounted() {
this.startUpdater()
this.startUpdater();
},

beforeDestroy() {
this.stopUpdater()
this.stopUpdater();
},

render(h) {
return h(
'time',
"time",
{
attrs: {
datetime: new Date(this.datetime),
title:
typeof this.title === 'string' ?
this.title :
this.title === false ?
null :
this.timeago
typeof this.title === "string"
? this.title
: this.title === false
? null
: this.timeago
}
},
[this.timeago]
)
);
},

methods: {
getTimeago(datetime) {
const converter = this.converter || opts.converter || defaultConverter
return converter(datetime || this.datetime, locales[this.locale || opts.locale], this.converterOptions || {})
const converter = this.converter || opts.converter || defaultConverter;
return converter(
datetime || this.datetime,
locales[this.localeName],
this.converterOptions || {}
);
},

convert(datetime) {
this.timeago = this.getTimeago(datetime)
this.timeago = this.getTimeago(datetime);
},

startUpdater() {
if (this.autoUpdate) {
const autoUpdaye = this.autoUpdate === true ? 60 : this.autoUpdate
const autoUpdaye = this.autoUpdate === true ? 60 : this.autoUpdate;
this.updater = setInterval(() => {
this.convert()
}, autoUpdaye * 1000)
this.convert();
}, autoUpdaye * 1000);
}
},

stopUpdater() {
if (this.updater) {
clearInterval(this.updater)
this.updater = null
clearInterval(this.updater);
this.updater = null;
}
}
},

watch: {
autoUpdate(newValue) {
this.stopUpdater()
this.stopUpdater();
if (newValue) {
this.startUpdater()
this.startUpdater();
}
},

datetime() {
this.convert()
this.convert();
},
locale() {
this.convert()
localeName() {
this.convert();
},
converter() {
this.convert()
this.convert();
},
converterOptions: {
handler() {
this.convert()
this.convert();
},
deep: true
}
}
}
}
};
};

export const install = (Vue, opts) => {
const Component = createTimeago(opts)
Vue.component(Component.name, Component)
}
if (Vue.prototype.$timeago) {
return;
}

if (process.env.NODE_ENV === "development" && !Vue.observable) {
console.warn(`[vue-timeago] Vue 2.6 or above is recommended.`);
}

const $timeago = {
locale: opts.locale
};
Vue.prototype.$timeago = Vue.observable
? Vue.observable($timeago)
: new Vue({ data: $timeago });

const Component = createTimeago(opts);
Vue.component(Component.name, Component);
};

export const converter = defaultConverter
export const converter = defaultConverter;

export default install
export default install;
8 changes: 4 additions & 4 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1578,10 +1578,10 @@ big.js@^3.1.3:
version "3.2.0"
resolved "https://registry.npmjs.org/big.js/-/big.js-3.2.0.tgz#a5fc298b81b9e0dca2e458824784b65c52ba588e"

bili@^4.5.2:
version "4.5.2"
resolved "https://registry.npmjs.org/bili/-/bili-4.5.2.tgz#55a141cba2a2dd813223fffe18efdb4434fadc75"
integrity sha512-G91DajUqNKU3qmcHXCwUaqHc4jaNkjO8IfYcTy3d3XVdXtU1oYNM3duDWvd6lbEzz19HfgjMxFArzaYoXOGz7Q==
bili@^4.5.3:
version "4.5.3"
resolved "https://registry.npmjs.org/bili/-/bili-4.5.3.tgz#76e3c4b04c87543c6a1ff44532749f7e96c06c36"
integrity sha512-9NosJzbXfPF3w7F0tEieudEKS77iBF1S+hnMBWofUf4jGzk1op7NjFZyAzz0ZXQVReGw7y+hERzlVgGfs1rWLA==
dependencies:
"@babel/core" "^7.2.2"
"@babel/plugin-proposal-object-rest-spread" "^7.3.1"
Expand Down

0 comments on commit a6bac94

Please sign in to comment.