Code Monkey home page Code Monkey logo

meteor-flow-router-title's Introduction

support support

Reactive page title

Change document.title on the fly in Meteor.js apps via flow-router-extra API.

Features:

  • ๐Ÿ‘จโ€๐Ÿ”ฌ 100% tests coverage;
  • ๐ŸŽ› Per route, per group, and default (all routes) title tag.

Various ways to set title, ordered by prioritization:

  • FlowRouter.route() [overrides all below]
  • FlowRouter.group()
  • FlowRouter.globals
  • Head template <title>Text</title> tag [might be overridden by any above]

Install:

meteor add ostrio:flow-router-title

Demos / Tests:

ES6 Import:

import { FlowRouterTitle } from 'meteor/ostrio:flow-router-title';

Related Packages:

Usage:

Initialize FlowRouterTitle class by passing FlowRouter object. Right after creating all routes:

import { FlowRouter }      from 'meteor/ostrio:flow-router-extra';
import { FlowRouterTitle } from 'meteor/ostrio:flow-router-title';

FlowRouter.route('/', {
  action() { /* ... */ },
  title: 'Title'
  /* ... */
});

new FlowRouterTitle(FlowRouter);

Set title via Route

Set title property in route's or group's configuration:

// Set default document.title value in
// case router has no title property
FlowRouter.globals.push({
  title: 'Default title'
});

FlowRouter.route('/me/account', {
  name: 'account',
  title: 'My Account'
});

.set() method

Set document.title during runtime (without route(s)):

FlowRouter.route('/', {/* ... */});

const titleHandler = new FlowRouterTitle(FlowRouter);
// `.set()` method accepts only String
titleHandler.set('My Awesome Title String'); // <- Returns `true`
titleHandler.set(() => { return 'Wrapped title'; }); // <- Returns `false`, as function can't be set into the `document.title`

Function context

Use function context (with data hook):

FlowRouter.route('/post/:_id', {
  name: 'post',
  waitOn(params) {
    return [Meteor.subscribe('post', params._id)];
  },
  data(params) {
    return Collections.Posts.findOne(params._id);
  },
  title(params, query, data) {
    if (data) {
      return data.title;
    }
    return '404: Page not found';
  }
});

Group context

Use group context:

const account = FlowRouter.group({
  prefix: '/account',
  title: 'Account',
  titlePrefix: 'Account > '
});

account.route('/', {
  name: 'accountIndex' // Title will be `Account`
});

account.route('/settings', {
  name: 'AccountSettings',
  title: 'My Settings' // Title will be `Account > My Settings`
});

Reactive data sources

To change title reactively, just pass it as function:

FlowRouter.route('/me/account', {
  name: 'account',
  title() {
    // In this example we used `ostrio:i18n` package
    return i18n.get('account.document.title');
  }
});

// Use params from route
FlowRouter.route('/page/:something', {
  name: 'somePage',
  title(params) {
    return 'Page ' + params.something;
  }
});

More examples

In all examples below title can be a Function or String:

import { FlowRouter } from 'meteor/ostrio:flow-router-extra';

FlowRouter.globals.push({
  title() {/* ... */} // <-- Suitable for reactive data source
});

FlowRouter.globals.push({
  title: 'Title text'
});

FlowRouter.group({
  title() {/* ... */}, // <-- Suitable for reactive data source
  titlePrefix() {/* ... */} // <-- Can accept reactive data source, but won't trigger re-computation
});

FlowRouter.group({
  title: 'Title text',
  titlePrefix: 'Title prefix text'
});

FlowRouter.route('/path', {
  title() {/* ... */} // <-- Reactive
});

FlowRouter.route('/path', {
  title: 'Title text'
});

Running Tests

  1. Clone this package
  2. In Terminal (Console) go to directory where package is cloned
  3. Then run:

Meteor/Tinytest

# Default
meteor test-packages ./

# With custom port
meteor test-packages ./ --port 8888

# With local MongoDB and custom port
MONGO_URL="mongodb://127.0.0.1:27017/flow-router-title-tests" meteor test-packages ./ --port 8888

Support this project:

meteor-flow-router-title's People

Contributors

afrokick avatar dr-dimitru avatar fishsaidno avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

meteor-flow-router-title's Issues

route title not reactive

I have found that the title function is not reactive-sensitive. my test ( have subbed out the post title with "my blog" for now:

This prints undefined then my blog post name, demonstrating reactivity.

blogSection.route('/:date/:postTitle/', {
    name: 'Post',
    title: function(params){
        Tracker.autorun(()=>{
            var blog = Blog.findOne({
                name: "My Blog",
            });
            console.log("route: ",blog && blog.name); // TODO remove

        })

    },

this prints undefined, and does not set the title to the blog name. If this function were reactive it would as per the example above

blogSection.route('/:date/:postTitle/', {
    name: 'Post',
    title: function(params){
            var blog = Blog.findOne({
                name: "My Blog",
            });
            console.log("route: ",blog && blog.name); 
                        return blog.name;
    },

[request] recursively search ancestor groups

a titlePrefix and default title will affect all routes in a group, but not routes in a child groups group. It would be great to set these properties for the whole app through a single global group. Thanks!

Title don't reactive with TAPi18n?

Title don't reactive

title: function () {
        return TAPi18n.__('core.exchange.title');
    },

I try to change language in the same route, it don't reactive.

FlowRouterTitle undefined

This is what I get after meteor add and using "new FlowRouterTitle" after I have created all the routes. Any idea why? Maybe I am doing something wrong? I am declaring all the routes in a jsx file.

W20160423-23:58:04.011(2)? (STDERR)
W20160423-23:58:04.012(2)? (STDERR) /home/giordano/.meteor/packages/meteor-tool/.1.3.0_3.a5p6a8++os.linux.x86_64+web.browser+web.cordova/mt-os.linux.x86_64/dev_bundle/server-lib/node_modules/fibers/future.js:267
W20160423-23:58:04.013(2)? (STDERR) throw(ex);
W20160423-23:58:04.013(2)? (STDERR) ^
W20160423-23:58:04.196(2)? (STDERR) ReferenceError: FlowRouterTitle is not defined
W20160423-23:58:04.197(2)? (STDERR) at meteorInstall.app.routes.jsx (app/routes.jsx:80:5)
W20160423-23:58:04.197(2)? (STDERR) at fileEvaluate (packages/modules-runtime.js:158:9)
W20160423-23:58:04.198(2)? (STDERR) at require (packages/modules-runtime.js:92:16)
W20160423-23:58:04.198(2)? (STDERR) at /home/giordano/git/shopluxurystyles/.meteor/local/build/programs/server/app/app.js:4092:1
W20160423-23:58:04.198(2)? (STDERR) at /home/giordano/git/shopluxurystyles/.meteor/local/build/programs/server/boot.js:283:10
W20160423-23:58:04.199(2)? (STDERR) at Array.forEach (native)
W20160423-23:58:04.199(2)? (STDERR) at Function..each..forEach (/home/giordano/.meteor/packages/meteor-tool/.1.3.0_3.a5p6a8++os.linux.x86_64+web.browser+web.cordova/mt-os.linux.x86_64/dev_bundle/server-lib/node_modules/underscore/underscore.js:79:11)
W20160423-23:58:04.199(2)? (STDERR) at /home/giordano/git/shopluxurystyles/.meteor/local/build/programs/server/boot.js:133:5
=> Exited with code: 8

TypeError: FlowRouterTitle is not a constructor

Trying to use this library for the first time.
The extra package (dependency) works without issues.
I can also import this package.
I removed the original FlowRouter packages (as per the instructions).

But when I add this line to instantiate it, as per the docs, I get the error "TypeError: FlowRouterTitle is not a constructor"

import { FlowRouter } from 'meteor/ostrio:flow-router-extra';
import {FlowRouterTitle} from 'meteor/ostrio:flow-router-title';
[I DECLARE SOME ROUTES HERE]
new FlowRouterTitle(FlowRouter);  <-- THROWS ERROR

Latest flow-router-title version
Meteor 2.8.1 (latest)
Chrome
Mac

Reactive title doesn't work

Page title doesn't change. Computation runs only one.

Example code for Collection:

import { FlowRouter } from 'meteor/ostrio:flow-router-extra';
import { Mongo } from 'meteor/mongo';

const TestCollection = new Mongo.Collection('testColl', { connection: null });

Meteor.setInterval(() => {
  if (TestCollection.find({}).count()) {
    TestCollection.remove({});
  } else {
    TestCollection.insert({ counter: true });
  }
}, 1000);

Tracker.autorun(() => {
  const [s] = TestCollection.find({}).fetch();

  console.log(`Tracker: ${s ? 'founded' : 'not founded'}`);
});

FlowRouter.route('*', {
  name: 'App.notFound',
  action() {
    console.log('rendered');
  },
  title() {
    const [s] = TestCollection.find({}).fetch();

    return s ? 'founded' : 'not founded';
  },
});

Example code for ReactiveVar:

import { FlowRouter } from 'meteor/ostrio:flow-router-extra';
 
const test = new ReactiveVar(1);
 
Meteor.setInterval(() => {
  test.set(test.get() + 1);
  console.log(`new:${test.get()}`);
}, 1000);
 
FlowRouter.route('*', {
  name: 'Test.name',
  action() {
    console.log('rendered');
  },
  title() {
    const t = test.get();
 
    console.log(`change title:${t}`);
 
    return `count ${t}`;
  },
});

Env:

Route title function isn't reactive

Here's a example of route definition:

FlowRouter.route('/:storyId', {
  name: 'story',
  title({storyId}) {
    // This is only fired once, cursors are empty
    // Subscriptions are done in templates
    // When data is available, this doesn't run again
    const story = Stories.find(storyId).fetch()[0]
    return story && story.title
  },
  action: function(params, queryParams) {
    BlazeLayout.render(...)
  }
})

I also tried const story = Stories.find(storyId).fetch() (without [0]), or even const story = Stories.find(storyId), no luck. The title() function should run again when the cursor isn't empty anymore. Also tried with some Session.get() tests, nothing happens neither.

Thanks.

NB. This follows #6

Duplicate ReactiveDict name: activeRouteConfig

Meteor version 1.4.4.1

Duplicate ReactiveDict name: activeRouteConfig error begins to show as soon as Meteor flow router title was added with meteor add ostrio:flow-router-title (even without any code level changes).

Plugin still seems to work once the required code is added in FlowRouter routes, the error still persists.

screen shot 2017-06-07 at 17 46 50

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.